Example usage for com.lowagie.text Document addKeywords

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

Introduction

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

Prototype


public boolean addKeywords(String keywords) 

Source Link

Document

Adds the keywords to a Document.

Usage

From source file:org.jboss.as.quickstarts.ejbinwar.ejb.GreeterEJB.java

License:Apache License

public ByteArrayOutputStream generatePDFDocumentBytes(String selectedTariff) throws DocumentException {
    java.util.Set<String> users = getRestUsers(selectedTariff);

    Document doc = new Document();

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter docWriter = null;//from   ww  w .j  av  a2s .  co m

    try {
        docWriter = PdfWriter.getInstance(doc, baosPDF);

        doc.addAuthor(this.getClass().getName());
        doc.addCreationDate();
        doc.addProducer();
        doc.addCreator(this.getClass().getName());
        doc.addTitle(selectedTariff + " clients");
        doc.addKeywords("pdf, itext, Java, ecare, http");

        doc.setPageSize(PageSize.LETTER);

        HeaderFooter footer = new HeaderFooter(new Phrase("E-Care report"), false);

        doc.setFooter(footer);

        doc.open();

        doc.add(new Paragraph(selectedTariff + " clients"));
        doc.add(new Paragraph("\n"));
        doc.add(new Paragraph("\n"));

        PdfPTable table = new PdfPTable(4); // 3 columns.

        PdfPCell cell1 = new PdfPCell(new Paragraph("Name"));
        PdfPCell cell2 = new PdfPCell(new Paragraph("Surname"));
        PdfPCell cell3 = new PdfPCell(new Paragraph("Address"));
        PdfPCell cell4 = new PdfPCell(new Paragraph("Email"));

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);
        table.addCell(cell4);

        for (Iterator<String> it = users.iterator(); it.hasNext();) {
            String user = it.next();

            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[0])));
            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[1])));
            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[2])));
            table.addCell(new PdfPCell(new Paragraph(user.split(" ")[3])));
        }

        doc.add(table);

    } catch (DocumentException dex) {
        baosPDF.reset();
        throw dex;
    } finally {
        if (doc != null) {
            doc.close();
        }
        if (docWriter != null) {
            docWriter.close();
        }
    }

    if (baosPDF.size() < 1) {
        throw new DocumentException("document has " + baosPDF.size() + " bytes");
    }
    return baosPDF;

}

From source file:org.jrimum.bopepo.pdf.PDFs.java

License:Apache License

/**
 * Junta varios arquivos pdf em um s./*from   w  w  w. j a  v a2 s . co m*/
 * 
 * @param pdfFiles
 *            Coleo de array de bytes
 * @param info
 *            Usa somente as informaes
 *            (title,subject,keywords,author,creator)
 * 
 * @return Arquivo PDF em forma de byte
 * 
 * @since 0.2
 */
public static byte[] mergeFiles(Collection<byte[]> pdfFiles, PdfDocInfo info) {

    try {

        ByteArrayOutputStream byteOS = new ByteArrayOutputStream();

        Document document = new Document();

        PdfCopy copy = new PdfCopy(document, byteOS);

        document.open();

        for (byte[] f : pdfFiles) {

            PdfReader reader = new PdfReader(f);

            for (int page = 1; page <= reader.getNumberOfPages(); page++) {

                copy.addPage(copy.getImportedPage(reader, page));
            }

            reader.close();
        }

        document.addCreationDate();

        if (info != null) {

            document.addAuthor(info.author());
            document.addCreator(info.creator());
            document.addTitle(info.title());
            document.addSubject(info.subject());
            document.addKeywords(info.keywords());
        }

        copy.close();
        document.close();
        byteOS.close();

        return byteOS.toByteArray();

    } catch (Exception e) {
        return Exceptions.throwIllegalStateException(e);
    }
}

From source file:org.mapfish.print.config.layout.MetaData.java

License:Open Source License

public void render(PJsonObject params, RenderingContext context) {
    final Document doc = context.getDocument();

    if (title != null) {
        doc.addTitle(PDFUtils.evalString(context, params, title));
    }//  ww w.  j  a  v a  2s .c  o  m

    if (author != null) {
        doc.addAuthor(PDFUtils.evalString(context, params, author));
    }

    if (subject != null) {
        doc.addSubject(PDFUtils.evalString(context, params, subject));
    }

    if (keywords != null) {
        doc.addKeywords(PDFUtils.evalString(context, params, keywords));
    }

    if (creator != null) {
        doc.addCreator(PDFUtils.evalString(context, params, creator));
    }
}

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

License:Open Source License

/**
 * @param args/*  w w w  .  ja  v  a 2s.c  o m*/
 * @throws DocumentException
 * @throws IOException
 * @throws IOException
 * @throws BadPdfFormatException
 */
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws DocumentException, IOException {
    /*
     * Verify arguments
     */
    if ((args == null) || (args.length < 2)) {
        System.err.println("Usage: first parameter: Creator to set, following parameters: Files to work on.");
        System.exit(1);
    }

    final String creator = args[0];

    for (int i = 1; i < args.length; i++) {
        final File f = new File(args[i]);

        if ((f == null) || !f.exists() || !f.isFile() || !f.getName().endsWith(".pdf")) {
            System.err.println("! ERROR: Could not read " + args[i] + " or this is not a .pdf");

            continue;
        }

        final String p = f.getAbsolutePath();

        /*
         * Open the reader
         */
        PdfReader reader;

        try {
            reader = new PdfReader(p);
        } catch (Exception e) {
            System.err.println("! ERROR: " + e.getMessage() + " File: " + p);

            continue;
        }

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

        /*
         * Get the document creator. If the document
         * has already been worked on, continue with
         * the next document.
         */
        String doc_creator = (String) info.get("Creator");

        if (creator.equals(doc_creator)) {
            System.out.println("+ INFO: File " + p + " had already the right creator.");

            continue;
        }

        /*
         * Get the document time stamp so that we can set it later.
         */
        final Date doc_timestamp = new Date(f.lastModified());

        /*
         * Get the number of pages in the original file
         */
        int nOri = reader.getNumberOfPages();

        System.out.print("+ INFO: Working on: " + p + " (" + nOri + " pages) ... ");

        /*
         * Get the remaining meta data
         */
        String doc_title = ((String) info.get("Title") == null) ? "" : (String) info.get("Title");
        String doc_subject = ((String) info.get("Subject") == null) ? "" : (String) info.get("Subject");
        String doc_keywords = ((String) info.get("Keywords") == null) ? "" : (String) info.get("Keywords");
        String doc_author = ((String) info.get("Author") == null) ? "" : (String) info.get("Author");

        reader.close();

        /*
         * Set the creator to our marker
         */
        doc_creator = creator;

        /*
         * Merge the new document with the meta
         * data from the original document
         */
        try {
            reader = new PdfReader(p);
        } catch (Exception e) {
            System.err.println("! ERROR: " + e.getMessage() + " File: " + p);

            continue;
        }

        /*
         * Get the document information
         */
        info = reader.getInfo();

        /*
         * Get the document creator. If the document
         * has already been worked on, we assume we
         * have had a successful output from the OCR
         * engine
         */
        String doc_creator_copy = (String) info.get("Creator");

        if (creator.equals(doc_creator_copy)) {
            System.out.println();

            continue;
        }

        /*
         * 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
         */
        PdfCopy writer = new PdfCopy(document, new FileOutputStream(p + ".tmp"));

        /*
         * Step 3: we add the meta data
         */
        document.addTitle(doc_title);
        document.addSubject(doc_subject);
        document.addKeywords(doc_keywords);
        document.addCreator(creator);
        document.addAuthor(doc_author);

        /*
         * Step 4: we open the document
         */
        document.open();

        PdfImportedPage page;

        int j = 0;

        /*
         * Step 5: we add content
         */
        while (j < nOri) {
            j++;
            page = writer.getImportedPage(reader, j);
            writer.addPage(page);

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

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

        System.out.println();

        /*
         * Step 6: we close the document
         */
        document.close();
        reader.close();

        /*
         * Set the file access time and
         * rename the file.
         */
        File file = new File(p + ".tmp");

        if (file.exists()) {
            deleteFile(p);
            file.setLastModified(doc_timestamp.getTime());
            file.renameTo(new File(p));
        }
    }
}

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

License:Open Source License

/**
 * @param args the command line arguments
 *//*  w w  w.j a  v  a 2s .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.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;//from w w  w  .j  a v a2s .  c o m

    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  ww .ja  v a  2  s  .com
 * 
 * @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:oscar.eform.util.EFormPDFServlet.java

License:Open Source License

private void addDocumentProps(Document document, String title, Properties props) {
    document.addTitle(title);//  w  w w  .  java  2 s  .  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());
    }/* ww w .  ja v  a  2  s  . c o 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:questions.metadata.ReplaceXMP.java

@SuppressWarnings("unchecked")
public static void createOriginal() {
    // step 1:/*from   www .ja  v a  2s.  com*/
    Document document = new Document();
    try {
        document.addAuthor("Bruno Lowagie");
        document.addKeywords("Hello World, XMP, Metadata");
        // step 2:
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(ORIGINAL));
        // step 3:
        writer.createXmpMetadata();
        document.open();
        // step 4:
        document.add(new Paragraph("Hello World"));
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    // step 5:
    document.close();
}