Example usage for com.lowagie.text Document addAuthor

List of usage examples for com.lowagie.text Document addAuthor

Introduction

In this page you can find the example usage for com.lowagie.text Document addAuthor.

Prototype


public boolean addAuthor(String author) 

Source Link

Document

Adds the author to a Document.

Usage

From source file:org.mnsoft.pdfocr.PDFTrans.java

License:Open Source License

/**
 * @param args the command line arguments
 *//*from   w w  w .j  a va2s .c  om*/
@SuppressWarnings({ "deprecation", "rawtypes" })
public static void main(String[] args) {
    if (args.length < 2) {
        usage();
    }

    String input_file = null, output_file = null, doc_title = null, doc_subject = null, doc_keywords = null,
            doc_creator = null, doc_author = null, user_passwd = null, owner_passwd = null;

    boolean encrypt = false;
    boolean encryption_bits = PdfWriter.STRENGTH128BITS;
    int permissions = 0;
    boolean print_info = false;
    boolean print_keywords = false;

    /*
     *  parse options
     */
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("--title")) {
            doc_title = args[++i];
        } else if (args[i].equals("--subject")) {
            doc_subject = args[++i];
        } else if (args[i].equals("--keywords")) {
            doc_keywords = args[++i];
        } else if (args[i].equals("--creator")) {
            doc_creator = args[++i];
        } else if (args[i].equals("--author")) {
            doc_author = args[++i];
        } else if (args[i].equals("--print-info")) {
            print_info = true;
        } else if (args[i].equals("--print-keywords")) {
            print_keywords = true;
        } else if (args[i].equals("--user-password")) {
            encrypt = true;
            user_passwd = args[++i];
        } else if (args[i].equals("--master-password")) {
            encrypt = true;
            owner_passwd = args[++i];
        } else if (args[i].equals("--encryption-bits")) {
            i++;
            encrypt = true;

            if (args[i].equals("128")) {
                encryption_bits = PdfWriter.STRENGTH128BITS;
            } else if (args[i].equals("40")) {
                encryption_bits = PdfWriter.STRENGTH40BITS;
            } else {
                usage();
            }

            continue;
        } else if (args[i].equals("--permissions")) {
            i++;

            StringTokenizer st = new StringTokenizer(args[i], ",");
            while (st.hasMoreTokens()) {
                String s = st.nextToken();
                if (s.equals("print")) {
                    permissions |= PdfWriter.AllowPrinting;
                } else if (s.equals("degraded-print")) {
                    permissions |= PdfWriter.AllowDegradedPrinting;
                } else if (s.equals("copy")) {
                    permissions |= PdfWriter.AllowCopy;
                } else if (s.equals("modify-contents")) {
                    permissions |= PdfWriter.AllowModifyContents;
                } else if (s.equals("modify-annotations")) {
                    permissions |= PdfWriter.AllowModifyAnnotations;
                } else if (s.equals("assembly")) {
                    permissions |= PdfWriter.AllowAssembly;
                } else if (s.equals("fill-in")) {
                    permissions |= PdfWriter.AllowFillIn;
                } else if (s.equals("screen-readers")) {
                    permissions |= PdfWriter.AllowScreenReaders;
                } else {
                    warning("Unknown permission '" + s + "' ignored");
                }
            }

            continue;
        } else if (args[i].startsWith("--")) {
            error("Unknown option '" + args[i] + "'");
        } else if (input_file == null) {
            input_file = args[i];
        } else if (output_file == null) {
            output_file = args[i];
        } else {
            usage();
        }
    }

    if (!print_keywords) {
        if ((input_file == null) || (output_file == null)) {
            usage();
        }

        if (input_file.equals(output_file)) {
            error("Input and output files must be different");
        }
    }

    try {
        /*
         *  we create a reader for the input file
         */
        if (!print_keywords) {
            System.out.println("Reading " + input_file + "...");
        }

        PdfReader reader = new PdfReader(input_file);

        /*
         *  we retrieve the total number of pages
         */
        final int n = reader.getNumberOfPages();
        if (!print_keywords) {
            System.out.println("There are " + n + " pages in the original file.");
        }

        /*
         *  get the document information
         */
        final Map info = reader.getInfo();

        /*
         *  print the document information if asked to do so
         */
        if (print_info) {
            System.out.println("Document information:");

            final Iterator it = info.entrySet().iterator();
            while (it.hasNext()) {
                final Map.Entry entry = (Map.Entry) it.next();
                System.out.println(entry.getKey() + " = \"" + entry.getValue() + "\"");
            }
        }

        if (print_keywords) {
            String keywords = "" + info.get("Keywords");
            if ((null == keywords) || "null".equals(keywords)) {
                keywords = "";
            }

            System.out.println(keywords);
            System.exit(0);
        }

        /*
         *  if any meta data field is unspecified,
         *  copy the value from the input document
         */
        if (doc_title == null) {
            doc_title = (String) info.get("Title");
        }

        if (doc_subject == null) {
            doc_subject = (String) info.get("Subject");
        }

        if (doc_keywords == null) {
            doc_keywords = (String) info.get("Keywords");
        }

        if (doc_creator == null) {
            doc_creator = (String) info.get("Creator");
        }

        if (doc_author == null) {
            doc_author = (String) info.get("Author");
        }

        // null metadata field are simply set to the empty string
        if (doc_title == null) {
            doc_title = "";
        }

        if (doc_subject == null) {
            doc_subject = "";
        }

        if (doc_keywords == null) {
            doc_keywords = "";
        }

        if (doc_creator == null) {
            doc_creator = "";
        }

        if (doc_author == null) {
            doc_author = "";
        }

        /*
         *  step 1: creation of a document-object
         */
        final Document document = new Document(reader.getPageSizeWithRotation(1));

        /*
         *  step 2: we create a writer that listens to the document
         */
        final PdfCopy writer = new PdfCopy(document, new FileOutputStream(output_file));

        /*
         *  step 3.1: we add the meta data
         */
        document.addTitle(doc_title);
        document.addSubject(doc_subject);
        document.addKeywords(doc_keywords);
        document.addCreator(doc_creator);
        document.addAuthor(doc_author);

        /*
         *  step 3.2: we set up the protection and encryption parameters
         */
        if (encrypt) {
            writer.setEncryption(encryption_bits, user_passwd, owner_passwd, permissions);
        }

        /*
         *  step 4: we open the document
         */
        System.out.print("Writing " + output_file + "... ");
        document.open();

        PdfImportedPage page;

        int i = 0;

        // step 5: we add content
        while (i < n) {
            i++;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);

            System.out.print("[" + i + "] ");
        }

        final PRAcroForm form = reader.getAcroForm();
        if (form != null) {
            writer.copyAcroForm(reader);
        }

        System.out.println();

        // step 6: we close the document
        document.close();
    } catch (Exception e) {
        error(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:org.nuxeo.dam.pdf.export.PDFCreator.java

License:Open Source License

public boolean createPDF(String title, OutputStream out) throws ClientException {
    try {//from   w  ww .  j  av a2s .c o  m
        Document document = new Document();
        PdfWriter.getInstance(document, out);

        document.addTitle(title);
        document.addAuthor(Functions.principalFullName(currentUser));
        document.addCreator(Functions.principalFullName(currentUser));

        document.open();

        document.add(new Paragraph("\n\n\n\n\n\n\n\n\n\n"));
        Font titleFont = new Font(Font.HELVETICA, 36, Font.BOLD);
        Paragraph titleParagraph = new Paragraph(title, titleFont);
        titleParagraph.setAlignment(Element.ALIGN_CENTER);
        document.add(titleParagraph);
        Font authorFont = new Font(Font.HELVETICA, 20);
        Paragraph authorParagraph = new Paragraph("By " + Functions.principalFullName(currentUser), authorFont);
        authorParagraph.setAlignment(Element.ALIGN_CENTER);
        document.add(authorParagraph);

        document.newPage();

        boolean foundOnePicture = false;
        for (DocumentModel doc : docs) {
            if (!doc.hasSchema(PICTURE_SCHEMA)) {
                continue;
            }
            foundOnePicture = true;

            PictureResourceAdapter picture = doc.getAdapter(PictureResourceAdapter.class);
            Blob blob = picture.getPictureFromTitle(ORIGINAL_JPEG_VIEW);
            Rectangle pageSize = document.getPageSize();
            if (blob != null) {
                Paragraph imageTitle = new Paragraph(doc.getTitle(), font);
                imageTitle.setAlignment(Paragraph.ALIGN_CENTER);
                document.add(imageTitle);

                Image image = Image.getInstance(blob.getByteArray());
                image.scaleToFit(pageSize.getWidth() - 20, pageSize.getHeight() - 100);
                image.setAlignment(Image.MIDDLE);
                Paragraph imageParagraph = new Paragraph();
                imageParagraph.add(image);
                imageParagraph.setAlignment(Paragraph.ALIGN_MIDDLE);
                document.add(imageParagraph);

                document.newPage();
            }
        }
        if (foundOnePicture) {
            document.close();
            return true;
        }
    } catch (Exception e) {
        throw ClientException.wrap(e);
    }
    return false;
}

From source file:org.oscarehr.phr.web.PHRUserManagementAction.java

License:Open Source License

public ByteArrayOutputStream generateUserRegistrationLetter(String demographicNo, String username,
        String password) throws Exception {
    log.debug("Demographic " + demographicNo + " username " + username + " password " + password);
    DemographicDao demographicDao = (DemographicDao) SpringUtils.getBean("demographicDao");
    Demographic demographic = demographicDao.getDemographic(demographicNo);

    final String PAGESIZE = "printPageSize";
    Document document = new Document();

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter writer = null;//  w w  w .java 2  s.  c om

    try {
        writer = PdfWriter.getInstance(document, baosPDF);

        String title = "TITLE";
        String template = "MyOscarLetterHead.pdf";

        Properties printCfg = getCfgProp();

        String[] cfgVal = null;
        StringBuilder tempName = null;

        // get the print prop values

        Properties props = new Properties();
        props.setProperty("letterDate", UtilDateUtilities.getToday("yyyy-MM-dd"));
        props.setProperty("name", demographic.getFirstName() + " " + demographic.getLastName());
        props.setProperty("dearname", demographic.getFirstName() + " " + demographic.getLastName());
        props.setProperty("address", demographic.getAddress());
        props.setProperty("city", demographic.getCity() + ", " + demographic.getProvince());
        props.setProperty("postalCode", demographic.getPostal());
        props.setProperty("credHeading", "MyOscar User Account Details");
        props.setProperty("username", "Username: " + username);
        props.setProperty("password", "Password: " + password);
        //Temporary - the intro will change to be dynamic
        props.setProperty("intro",
                "We are pleased to provide you with a log in and password for your new MyOSCAR Personal Health Record. This account will allow you to connect electronically with our clinic. Please take a few minutes to review the accompanying literature for further information.We look forward to you benefiting from this service.");

        document.addTitle(title);
        document.addSubject("");
        document.addKeywords("pdf, itext");
        document.addCreator("OSCAR");
        document.addAuthor("");
        document.addHeader("Expires", "0");

        Rectangle pageSize = PageSize.LETTER;

        document.setPageSize(pageSize);
        document.open();

        // create a reader for a certain document
        String propFilename = oscar.OscarProperties.getInstance().getProperty("pdfFORMDIR", "") + "/"
                + template;
        PdfReader reader = null;
        try {
            reader = new PdfReader(propFilename);
            log.debug("Found template at " + propFilename);
        } catch (Exception dex) {
            log.debug("change path to inside oscar from :" + propFilename);
            reader = new PdfReader("/oscar/form/prop/" + template);
            log.debug("Found template at /oscar/form/prop/" + template);
        }

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // retrieve the size of the first page
        Rectangle pSize = reader.getPageSize(1);
        float width = pSize.getWidth();
        float height = pSize.getHeight();
        log.debug("Width :" + width + " Height: " + height);

        PdfContentByte cb = writer.getDirectContent();
        ColumnText ct = new ColumnText(cb);
        int fontFlags = 0;

        document.newPage();
        PdfImportedPage page1 = writer.getImportedPage(reader, 1);
        cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);

        BaseFont bf; // = normFont;
        String encoding;

        cb.setRGBColorStroke(0, 0, 255);

        String[] fontType;
        for (Enumeration e = printCfg.propertyNames(); e.hasMoreElements();) {
            tempName = new StringBuilder(e.nextElement().toString());
            cfgVal = printCfg.getProperty(tempName.toString()).split(" *, *");

            if (cfgVal[4].indexOf(";") > -1) {
                fontType = cfgVal[4].split(";");
                if (fontType[1].trim().equals("italic"))
                    fontFlags = Font.ITALIC;
                else if (fontType[1].trim().equals("bold"))
                    fontFlags = Font.BOLD;
                else if (fontType[1].trim().equals("bolditalic"))
                    fontFlags = Font.BOLDITALIC;
                else
                    fontFlags = Font.NORMAL;
            } else {
                fontFlags = Font.NORMAL;
                fontType = new String[] { cfgVal[4].trim() };
            }

            if (fontType[0].trim().equals("BaseFont.HELVETICA")) {
                fontType[0] = BaseFont.HELVETICA;
                encoding = BaseFont.CP1252; //latin1 encoding
            } else if (fontType[0].trim().equals("BaseFont.HELVETICA_OBLIQUE")) {
                fontType[0] = BaseFont.HELVETICA_OBLIQUE;
                encoding = BaseFont.CP1252;
            } else if (fontType[0].trim().equals("BaseFont.ZAPFDINGBATS")) {
                fontType[0] = BaseFont.ZAPFDINGBATS;
                encoding = BaseFont.ZAPFDINGBATS;
            } else {
                fontType[0] = BaseFont.COURIER;
                encoding = BaseFont.CP1252;
            }

            bf = BaseFont.createFont(fontType[0], encoding, BaseFont.NOT_EMBEDDED);

            // write in a rectangle area
            if (cfgVal.length >= 9) {
                Font font = new Font(bf, Integer.parseInt(cfgVal[5].trim()), fontFlags);
                ct.setSimpleColumn(Integer.parseInt(cfgVal[1].trim()),
                        (height - Integer.parseInt(cfgVal[2].trim())), Integer.parseInt(cfgVal[7].trim()),
                        (height - Integer.parseInt(cfgVal[8].trim())), Integer.parseInt(cfgVal[9].trim()),
                        (cfgVal[0].trim().equals("left") ? Element.ALIGN_LEFT
                                : (cfgVal[0].trim().equals("right") ? Element.ALIGN_RIGHT
                                        : Element.ALIGN_CENTER)));

                ct.setText(new Phrase(12, props.getProperty(tempName.toString(), ""), font));
                ct.go();
                continue;
            }

            // draw line directly
            if (tempName.toString().startsWith("__$line")) {
                cb.setRGBColorStrokeF(0f, 0f, 0f);
                cb.setLineWidth(Float.parseFloat(cfgVal[4].trim()));
                cb.moveTo(Float.parseFloat(cfgVal[0].trim()), Float.parseFloat(cfgVal[1].trim()));
                cb.lineTo(Float.parseFloat(cfgVal[2].trim()), Float.parseFloat(cfgVal[3].trim()));
                // stroke the lines
                cb.stroke();
                // write text directly

            } else if (tempName.toString().startsWith("__")) {
                cb.beginText();
                cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
                cb.showTextAligned(
                        (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                                : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                        : PdfContentByte.ALIGN_CENTER)),
                        (cfgVal.length >= 7 ? (cfgVal[6].trim()) : props.getProperty(tempName.toString(), "")),
                        Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0);

                cb.endText();
            } else if (tempName.toString().equals("forms_promotext")) {
                if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) {
                    cb.beginText();
                    cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
                    cb.showTextAligned(
                            (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                                    : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                            : PdfContentByte.ALIGN_CENTER)),
                            OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"),
                            Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())),
                            0);

                    cb.endText();
                }
            } else { // write prop text

                cb.beginText();
                cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim()));
                cb.showTextAligned(
                        (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT
                                : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT
                                        : PdfContentByte.ALIGN_CENTER)),
                        (cfgVal.length >= 7 ? ((props.getProperty(tempName.toString(), "").equals("") ? ""
                                : cfgVal[6].trim())) : props.getProperty(tempName.toString(), "")),
                        Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0);

                cb.endText();
            }
        }

    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } finally {
        if (document != null)
            document.close();
        if (writer != null)
            writer.close();
    }
    return baosPDF;
}

From source file:org.schreibubi.JCombinations.ui.GridChartPanel.java

License:Open Source License

/**
 * Create PDF//from  w w w . j  av a 2s  .c om
 * 
 * @param name
 *            Filename
 * @param selection
 *            Selected Nodes
 * @param dm
 *            DataModel
 * @param pl
 *            ProgressListener
 */
@SuppressWarnings("unchecked")
public static void generatePDF(File name, DataModel dm, ArrayList<TreePath> selection, ProgressListener pl) {
    com.lowagie.text.Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);
    try {
        ArrayList<ExtendedJFreeChart> charts = dm.getCharts(selection);
        if (charts.size() > 0) {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name));
            writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
            document.addAuthor("Jrg Werner");
            document.addSubject("Created by JCombinations");
            document.addKeywords("JCombinations");
            document.addCreator("JCombinations using iText");

            // we define a header and a footer
            HeaderFooter header = new HeaderFooter(new Phrase("JCombinations by Jrg Werner"), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));
            footer.setAlignment(Element.ALIGN_CENTER);
            document.setHeader(header);
            document.setFooter(footer);

            document.open();
            DefaultFontMapper mapper = new DefaultFontMapper();
            FontFactory.registerDirectories();
            mapper.insertDirectory("c:\\WINNT\\fonts");

            PdfContentByte cb = writer.getDirectContent();

            pl.progressStarted(new ProgressEvent(GridChartPanel.class, 0, charts.size()));
            for (int i = 0; i < charts.size(); i++) {
                ExtendedJFreeChart chart = charts.get(i);
                PdfTemplate tp = cb.createTemplate(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                Graphics2D g2d = tp.createGraphics(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN), mapper);
                Rectangle2D r2d = new Rectangle2D.Double(0, 0,
                        document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                chart.draw(g2d, r2d);
                g2d.dispose();
                cb.addTemplate(tp, document.left(EXTRA_MARGIN), document.bottom(EXTRA_MARGIN));
                PdfDestination destination = new PdfDestination(PdfDestination.FIT);
                TreePath treePath = chart.getTreePath();
                PdfOutline po = cb.getRootOutline();
                for (int j = 0; j < treePath.getPathCount(); j++) {
                    ArrayList<PdfOutline> lpo = po.getKids();
                    PdfOutline cpo = null;
                    for (PdfOutline outline : lpo)
                        if (outline.getTitle().compareTo(treePath.getPathComponent(j).toString()) == 0)
                            cpo = outline;
                    if (cpo == null)
                        cpo = new PdfOutline(po, destination, treePath.getPathComponent(j).toString());
                    po = cpo;
                }
                document.newPage();
                pl.progressIncremented(new ProgressEvent(GridChartPanel.class, i));
            }
            document.close();
            pl.progressEnded(new ProgressEvent(GridChartPanel.class));

        }
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:org.silverpeas.components.almanach.control.AlmanachPdfGenerator.java

License:Open Source License

static public void buildPdf(String name, AlmanachSessionController almanach, String mode)
        throws AlmanachRuntimeException {
    try {//from w  ww  .  j  av  a2 s .  com

        String fileName = FileRepositoryManager.getTemporaryPath(almanach.getSpaceId(),
                almanach.getComponentId()) + name;
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor(almanach.getSettings().getString("author", ""));
        document.addSubject(almanach.getSettings().getString("subject", ""));
        document.addCreationDate();

        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        try {
            Calendar currentDay = Calendar.getInstance();
            currentDay.setTime(almanach.getCurrentDay());
            String sHeader = almanach.getString("events");
            if (mode.equals(PDF_MONTH_ALLDAYS) || mode.equals(PDF_MONTH_EVENTSONLY)) {
                sHeader += " " + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH));
            }
            sHeader += " " + currentDay.get(Calendar.YEAR);
            HeaderFooter header = new HeaderFooter(new Phrase(sHeader), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
            footer.setAlignment(Element.ALIGN_CENTER);

            document.setHeader(header);
            document.setFooter(footer);

            createFirstPage(almanach, document);
            document.newPage();

            Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255));
            Paragraph cTitle = new Paragraph(almanach.getString("Almanach") + " "
                    + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH)) + " "
                    + currentDay.get(Calendar.YEAR), titleFont);
            Chapter chapter = new Chapter(cTitle, 1);

            // Collection<EventDetail> events =
            // almanach.getListRecurrentEvent(mode.equals(PDF_YEAR_EVENTSONLY));
            AlmanachCalendarView almanachView;
            if (PDF_YEAR_EVENTSONLY.equals(mode)) {
                almanachView = almanach.getYearlyAlmanachCalendarView();
            } else {
                almanachView = almanach.getMonthlyAlmanachCalendarView();
            }

            List<DisplayableEventOccurrence> occurrences = almanachView.getEvents();
            generateAlmanach(chapter, almanach, occurrences, mode);

            document.add(chapter);
        } catch (Exception ex) {
            throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                    "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", ex);
        }

        document.close();

    } catch (Exception e) {
        throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", e);
    }

}

From source file:oscar.eform.util.EFormPDFServlet.java

License:Open Source License

private void addDocumentProps(Document document, String title, Properties props) {
    document.addTitle(title);//w  ww  . j  av a2s  .  c o  m
    document.addSubject("");
    document.addKeywords("pdf, itext");
    document.addCreator("OSCAR");
    document.addAuthor("");
    document.addHeader("Expires", "0");

    // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA
    // and FLSE
    // the following shows a temp way to get a print page size
    final String PAGESIZE = "printPageSize";
    Rectangle pageSize = PageSize.LETTER;
    if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE)))
        pageSize = PageSize.HALFLETTER;
    if ("PageSize.A6".equals(props.getProperty(PAGESIZE)))
        pageSize = PageSize.A6;
    document.setPageSize(pageSize);
    document.open();
}

From source file:oscar.form.pdfservlet.FrmCustomedPDFServlet.java

License:Open Source License

protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx)
        throws DocumentException {
    logger.debug("***in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***");
    // added by vic, hsfo
    Enumeration<String> em = req.getParameterNames();
    while (em.hasMoreElements()) {
        logger.debug("para=" + em.nextElement());
    }// www.j  av  a  2s.  co  m
    em = req.getAttributeNames();
    while (em.hasMoreElements())
        logger.debug("attr: " + em.nextElement());

    if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title"))) {
        return generateHsfoRxPDF(req);
    }
    String newline = System.getProperty("line.separator");

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter writer = null;
    String method = req.getParameter("__method");
    String origPrintDate = null;
    String numPrint = null;
    if (method != null && method.equalsIgnoreCase("rePrint")) {
        origPrintDate = req.getParameter("origPrintDate");
        numPrint = req.getParameter("numPrints");
    }

    logger.debug("method in generatePDFDocumentBytes " + method);
    String clinicName;
    String clinicTel;
    String clinicFax;
    // check if satellite clinic is used
    String useSatelliteClinic = req.getParameter("useSC");
    logger.debug(useSatelliteClinic);
    if (useSatelliteClinic != null && useSatelliteClinic.equalsIgnoreCase("true")) {
        String scAddress = req.getParameter("scAddress");
        logger.debug("clinic detail" + "=" + scAddress);
        HashMap<String, String> hm = parseSCAddress(scAddress);
        clinicName = hm.get("clinicName");
        clinicTel = hm.get("clinicTel");
        clinicFax = hm.get("clinicFax");
    } else {
        // parameters need to be passed to header and footer
        clinicName = req.getParameter("clinicName");
        logger.debug("clinicName" + "=" + clinicName);
        clinicTel = req.getParameter("clinicPhone");
        clinicFax = req.getParameter("clinicFax");
    }
    String patientPhone = req.getParameter("patientPhone");
    String patientCityPostal = req.getParameter("patientCityPostal");
    String patientAddress = req.getParameter("patientAddress");
    String patientName = req.getParameter("patientName");
    String sigDoctorName = req.getParameter("sigDoctorName");
    String rxDate = req.getParameter("rxDate");
    String rx = req.getParameter("rx");
    String patientDOB = req.getParameter("patientDOB");
    String showPatientDOB = req.getParameter("showPatientDOB");
    String imgFile = req.getParameter("imgFile");
    String patientHIN = req.getParameter("patientHIN");
    String patientChartNo = req.getParameter("patientChartNo");
    String pracNo = req.getParameter("pracNo");
    Locale locale = req.getLocale();

    boolean isShowDemoDOB = false;
    if (showPatientDOB != null && showPatientDOB.equalsIgnoreCase("true")) {
        isShowDemoDOB = true;
    }
    if (!isShowDemoDOB)
        patientDOB = "";
    if (rx == null) {
        rx = "";
    }

    String additNotes = req.getParameter("additNotes");
    String[] rxA = rx.split(newline);
    List<String> listRx = new ArrayList<String>();
    String listElem = "";
    // parse rx and put into a list of rx;
    for (String s : rxA) {

        if (s.equals("") || s.equals(newline) || s.length() == 1) {
            listRx.add(listElem);
            listElem = "";
        } else {
            listElem = listElem + s;
            listElem += newline;
        }

    }

    // get the print prop values
    Properties props = new Properties();
    StringBuilder temp = new StringBuilder();
    for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) {
        temp = new StringBuilder(e.nextElement().toString());
        props.setProperty(temp.toString(), req.getParameter(temp.toString()));
    }

    for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) {
        temp = new StringBuilder(e.nextElement().toString());
        props.setProperty(temp.toString(), req.getAttribute(temp.toString()).toString());
    }
    Document document = new Document();

    try {
        String title = req.getParameter("__title") != null ? req.getParameter("__title") : "Unknown";

        // specify the page of the picture using __graphicPage, it may be used multiple times to specify multiple pages
        // however the same graphic will be applied to all pages
        // ie. __graphicPage=2&__graphicPage=3
        String[] cfgGraphicFile = req.getParameterValues("__cfgGraphicFile");
        int cfgGraphicFileNo = cfgGraphicFile == null ? 0 : cfgGraphicFile.length;
        if (cfgGraphicFile != null) {
            // for (String s : cfgGraphicFile) {
            // p("cfgGraphicFile", s);
            // }
        }

        String[] graphicPage = req.getParameterValues("__graphicPage");
        ArrayList<String> graphicPageArray = new ArrayList<String>();
        if (graphicPage != null) {
            // for (String s : graphicPage) {
            // p("graphicPage", s);
            // }
            graphicPageArray = new ArrayList<String>(Arrays.asList(graphicPage));
        }

        // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA
        // and FLSE
        // the following shows a temp way to get a print page size
        Rectangle pageSize = PageSize.LETTER;
        String pageSizeParameter = req.getParameter("rxPageSize");
        if (pageSizeParameter != null) {
            if ("PageSize.HALFLETTER".equals(pageSizeParameter)) {
                pageSize = PageSize.HALFLETTER;
            } else if ("PageSize.A6".equals(pageSizeParameter)) {
                pageSize = PageSize.A6;
            } else if ("PageSize.A4".equals(pageSizeParameter)) {
                pageSize = PageSize.A4;
            }
        }
        /*
         * if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A6; } else if
         * ("PageSize.A4".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A4; }
         */
        // p("size of page ", props.getProperty(PAGESIZE));

        document.setPageSize(pageSize);
        // 285=left margin+width of box, 5f is space for looking nice
        document.setMargins(15, pageSize.getWidth() - 285f + 5f, 170, 60);// left, right, top , bottom

        writer = PdfWriter.getInstance(document, baosPDF);
        writer.setPageEvent(new EndPage(clinicName, clinicTel, clinicFax, patientPhone, patientCityPostal,
                patientAddress, patientName, patientDOB, sigDoctorName, rxDate, origPrintDate, numPrint,
                imgFile, patientHIN, patientChartNo, pracNo, locale));
        document.addTitle(title);
        document.addSubject("");
        document.addKeywords("pdf, itext");
        document.addCreator("OSCAR");
        document.addAuthor("");
        document.addHeader("Expires", "0");

        document.open();
        document.newPage();

        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf; // = normFont;

        cb.setRGBColorStroke(0, 0, 255);
        // render prescriptions
        for (String rxStr : listRx) {
            bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph p = new Paragraph(new Phrase(rxStr, new Font(bf, 10)));
            p.setKeepTogether(true);
            p.setSpacingBefore(5f);
            document.add(p);
        }
        // render additional notes
        if (additNotes != null && !additNotes.equals("")) {
            bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph p = new Paragraph(new Phrase(additNotes, new Font(bf, 10)));
            p.setKeepTogether(true);
            p.setSpacingBefore(10f);
            document.add(p);
        }
        // render optometristEyeParam
        if (req.getAttribute("optometristEyeParam") != null) {
            bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph p = new Paragraph(
                    new Phrase("Eye " + (String) req.getAttribute("optometristEyeParam"), new Font(bf, 10)));
            p.setKeepTogether(true);
            p.setSpacingBefore(15f);
            document.add(p);
        }

        // render QrCode
        if (PrescriptionQrCodeUIBean.isPrescriptionQrCodeEnabledForCurrentProvider()) {
            Integer scriptId = Integer.parseInt(req.getParameter("scriptId"));
            byte[] qrCodeImage = PrescriptionQrCodeUIBean.getPrescriptionHl7QrCodeImage(scriptId);
            Image qrCode = Image.getInstance(qrCodeImage);
            document.add(qrCode);
        }

    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } catch (Exception e) {
        logger.error("Error", e);
    } finally {
        if (document != null) {
            document.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
    logger.debug("***END in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***");
    return baosPDF;
}

From source file:peakml.graphics.JFreeChartTools.java

License:Open Source License

/**
 * This method writes the given graph to the output stream in the PDF format. As a vector
 * based file format it allows some freedom to be changed (e.g. colors, line thickness, etc.),
 * which can be convenient for presentation purposes.
 * /*from   w w  w  . j  a  va 2 s.c  om*/
 * @param out         The output stream to write to.
 * @param chart         The chart to be written.
 * @param width         The width of the image.
 * @param height      The height of the image.
 * @throws IOException   Thrown when an error occurs with the IO.
 */
public static void writeAsPDF(OutputStream out, JFreeChart chart, int width, int height) throws IOException {
    Document document = new Document(new Rectangle(width, height), 50, 50, 50, 50);
    document.addAuthor("");
    document.addSubject("");

    try {
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);

        java.awt.Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
        chart.draw(g2, new java.awt.geom.Rectangle2D.Double(0, 0, width, height));

        g2.dispose();
        cb.addTemplate(tp, 0, 0);
    } catch (DocumentException de) {
        throw new IOException(de.getMessage());
    }

    document.close();
}

From source file:pentaho.kettle.step.plugs.pdfout.PDFOutputGenerate.java

License:Apache License

public void generatePDF(String OutputFileName) throws IOException {

    if (Const.isWindows()) {
        if (OutputFileName.startsWith("file:///"))
            OutputFileName = OutputFileName.substring(8);
        OutputFileName = OutputFileName.replace("\\", "\\\\");
    }/*ww  w  .j  a va2  s  . c  o  m*/

    Document document = new Document();

    PdfWriter writer;
    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(OutputFileName));

        document.open();

        document.add(new Paragraph("Hello Rishu Here !!"));

        /*
         * Setting up File Attributes - Document Description
         */
        document.addAuthor("Rishu Shrivastava");
        document.addCreationDate();
        document.addCreator("Rishu");
        document.addTitle("Set Attribute Example");
        document.addSubject("An example to show how attributes can be added to pdf files.");

        document.close();
        writer.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:proyecto.Main.java

private void jp_flujo_guardarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jp_flujo_guardarMouseClicked
    JFileChooser jfc = new JFileChooser();
    FileFilter filtro = new FileNameExtensionFilter("PNG", "png");
    FileFilter filtro2 = new FileNameExtensionFilter("JPG", "jpg");
    FileFilter filtro3 = new FileNameExtensionFilter("PDF", "pdf");
    FileFilter filtro4 = new FileNameExtensionFilter("JPEG", "jpeg");
    FileFilter filtro5 = new FileNameExtensionFilter("Dany", "dany");
    jfc.addChoosableFileFilter(filtro);//from w  w w  . java2s  .co  m
    jfc.addChoosableFileFilter(filtro2);
    jfc.addChoosableFileFilter(filtro3);
    jfc.addChoosableFileFilter(filtro4);
    jfc.addChoosableFileFilter(filtro5);

    int op = jfc.showSaveDialog(jfc);

    if (op == JFileChooser.APPROVE_OPTION) {
        if (jfc.getFileFilter().getDescription().equals("PNG")) {
            try {
                BufferedImage bi = new BufferedImage(jp_flujo.getWidth(), jp_flujo.getHeight(),
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bi.createGraphics();
                jp_flujo.paint(g);
                File archivo = new File(jfc.getSelectedFile().toString() + ".png");
                ImageIO.write(bi, "png", archivo);
            } catch (Exception ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (jfc.getFileFilter().getDescription().equals("JPG")) {
            try {
                BufferedImage bi = new BufferedImage(jp_flujo.getWidth(), jp_flujo.getHeight(),
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bi.createGraphics();
                jp_flujo.paint(g);
                File archivo = new File(jfc.getSelectedFile().toString() + ".jpg");
                ImageIO.write(bi, "jpg", archivo);
            } catch (Exception ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (jfc.getFileFilter().getDescription().equals("PDF")) {
            try {
                Document documentPDF = new Document();
                PdfWriter pdf = PdfWriter.getInstance(documentPDF,
                        new FileOutputStream(jfc.getSelectedFile().getPath() + ".pdf"));
                documentPDF.open();

                documentPDF.addAuthor("Dany Cheong");
                documentPDF.addCreator("DC");

                BufferedImage bi = new BufferedImage(jp_flujo.getWidth(), jp_flujo.getHeight(),
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bi.createGraphics();
                jp_flujo.paint(g);
                File archivo = new File(jfc.getSelectedFile().toString() + ".png");
                ImageIO.write(bi, "png", archivo);
                documentPDF.add(com.lowagie.text.Image.getInstance(jfc.getSelectedFile().toString() + ".png"));
                archivo.delete();

                documentPDF.close();
            } catch (Exception ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (jfc.getFileFilter().getDescription().equals("JPEG")) {
            try {
                BufferedImage bi = new BufferedImage(jp_flujo.getWidth(), jp_flujo.getHeight(),
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bi.createGraphics();
                jp_flujo.paint(g);
                File archivo = new File(jfc.getSelectedFile().toString() + ".jpeg");
                ImageIO.write(bi, "jpeg", archivo);
            } catch (Exception ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (jfc.getFileFilter().getDescription().equals("Dany")) {
            if (jfc.getSelectedFile().exists()) {//si el archivo ya existe, y salvo el panel en ese mismo archivo
                try {
                    File archivo = null;
                    archivo = new File(jfc.getSelectedFile().getPath());

                    FileInputStream fis = new FileInputStream(archivo);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    Pane_temp panel;
                    ArrayList<Pane_temp> lista2 = new ArrayList();
                    try {
                        while ((panel = (Pane_temp) ois.readObject()) != null) {
                            lista2.add(panel);
                        }
                    } catch (Exception e) {

                    } finally {
                        fis.close();
                        ois.close();
                    }

                    for (int i = 0; i < lista.size(); i++) {
                        lista2.add(lista.get(i));
                    }

                    FileOutputStream fos = new FileOutputStream(archivo);
                    ObjectOutputStream oos = new ObjectOutputStream(fos);

                    for (Pane_temp temporal : lista2) {
                        oos.writeObject(temporal);
                    }
                    oos.flush();
                    oos.close();
                    fos.close();
                } catch (Exception e) {

                }
            } else { //si el archivo no existe y estoy creando uno nuevo
                File archivo = null;
                try {
                    archivo = new File(jfc.getSelectedFile().getPath() + ".dany");
                    //crear archivo que no existe
                    FileOutputStream fos = new FileOutputStream(archivo);
                    ObjectOutputStream oos = new ObjectOutputStream(fos);
                    for (int i = 0; i < lista.size(); i++) {
                        oos.writeObject(lista.get(i));
                    }
                    oos.flush();
                    fos.close();
                    oos.close();
                    lista.removeAll(lista);
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {

                }
            }
        }

    }
}