Example usage for com.lowagie.text Document addSubject

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

Introduction

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

Prototype


public boolean addSubject(String subject) 

Source Link

Document

Adds the subject to a Document.

Usage

From source file:org.jbpm.designer.web.server.TransformerServlet.java

License:Apache License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String formattedSvgEncoded = req.getParameter("fsvg");
    String uuid = Utils.getUUID(req);
    String profileName = Utils.getDefaultProfileName(req.getParameter("profile"));
    String transformto = req.getParameter("transformto");
    String jpdl = req.getParameter("jpdl");
    String gpd = req.getParameter("gpd");
    String bpmn2in = req.getParameter("bpmn2");
    String jsonin = req.getParameter("json");
    String preprocessingData = req.getParameter("pp");
    String respaction = req.getParameter("respaction");
    String pp = req.getParameter("pp");
    String processid = req.getParameter("processid");
    String sourceEnc = req.getParameter("enc");
    String convertServiceTasks = req.getParameter("convertservicetasks");
    String htmlSourceEnc = req.getParameter("htmlenc");

    String formattedSvg = (formattedSvgEncoded == null ? ""
            : new String(Base64.decodeBase64(formattedSvgEncoded), "UTF-8"));

    String htmlSource = (htmlSourceEnc == null ? "" : new String(Base64.decodeBase64(htmlSourceEnc), "UTF-8"));

    if (sourceEnc != null && sourceEnc.equals("true")) {
        bpmn2in = new String(Base64.decodeBase64(bpmn2in), "UTF-8");
    }/*from w w w  .j  a v a2 s. c  om*/

    if (profile == null) {
        profile = _profileService.findProfile(req, profileName);
    }

    DroolsFactoryImpl.init();
    BpsimFactoryImpl.init();

    Repository repository = profile.getRepository();

    if (transformto != null && transformto.equals(TO_PDF)) {
        if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) {

            try {
                ByteArrayOutputStream pdfBout = new ByteArrayOutputStream();
                Document pdfDoc = new Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, pdfBout);
                pdfDoc.open();
                pdfDoc.addCreationDate();

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");

                float widthHint = getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH);
                float heightHint = getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT);
                String objStyle = "style=\"width:" + widthHint + "px;height:" + heightHint + "px;\"";
                t.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, widthHint);
                t.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, heightHint);

                ByteArrayOutputStream imageBout = new ByteArrayOutputStream();
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(imageBout);
                t.transcode(input, output);

                Image processImage = Image.getInstance(imageBout.toByteArray());
                scalePDFImage(pdfDoc, processImage);
                pdfDoc.add(processImage);

                pdfDoc.close();

                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/plain");

                resp.getWriter()
                        .write("<object type=\"application/pdf\" " + objStyle
                                + " data=\"data:application/pdf;base64,"
                                + Base64.encodeBase64String(pdfBout.toByteArray()) + "\"></object>");
            } catch (Exception e) {
                resp.sendError(500, e.getMessage());
            }
        } else {
            storeInRepository(uuid, formattedSvg, transformto, processid, repository);

            try {
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("application/pdf");
                if (processid != null) {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\"");
                } else {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\"");
                }

                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                Document pdfDoc = new Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream());
                pdfDoc.open();
                pdfDoc.addCreationDate();

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);

                Image processImage = Image.getInstance(bout.toByteArray());
                scalePDFImage(pdfDoc, processImage);
                pdfDoc.add(processImage);

                pdfDoc.close();
            } catch (Exception e) {
                resp.sendError(500, e.getMessage());
            }
        }
    } else if (transformto != null && transformto.equals(TO_PNG)) {
        try {
            if (respaction != null && respaction.equals(RESPACTION_SHOWURL)) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(bout);
                t.transcode(input, output);
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/plain");
                if (req.getParameter(SVG_WIDTH_PARAM) != null && req.getParameter(SVG_HEIGHT_PARAM) != null) {
                    int widthHint = (int) getFloatParam(req, SVG_WIDTH_PARAM, DEFAULT_PDF_WIDTH);
                    int heightHint = (int) getFloatParam(req, SVG_HEIGHT_PARAM, DEFAULT_PDF_HEIGHT);
                    resp.getWriter()
                            .write("<img width=\"" + widthHint + "\" height=\"" + heightHint
                                    + "\" src=\"data:image/png;base64,"
                                    + Base64.encodeBase64String(bout.toByteArray()) + "\">");
                } else {
                    resp.getWriter().write("<img src=\"data:image/png;base64,"
                            + Base64.encodeBase64String(bout.toByteArray()) + "\">");
                }
            } else {
                storeInRepository(uuid, formattedSvg, transformto, processid, repository);
                resp.setContentType("image/png");
                if (processid != null) {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".png\"");
                } else {
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".png\"");
                }

                PNGTranscoder t = new PNGTranscoder();
                t.addTranscodingHint(ImageTranscoder.KEY_MEDIA, "screen");
                TranscoderInput input = new TranscoderInput(new StringReader(formattedSvg));
                TranscoderOutput output = new TranscoderOutput(resp.getOutputStream());
                t.transcode(input, output);
            }
        } catch (TranscoderException e) {
            resp.sendError(500, e.getMessage());
        }
    } else if (transformto != null && transformto.equals(TO_SVG)) {
        storeInRepository(uuid, formattedSvg, transformto, processid, repository);
    } else if (transformto != null && transformto.equals(BPMN2_TO_JSON)) {
        try {
            if (convertServiceTasks != null && convertServiceTasks.equals("true")) {
                bpmn2in = bpmn2in.replaceAll("drools:taskName=\".*?\"", "drools:taskName=\"ReadOnlyService\"");
                bpmn2in = bpmn2in.replaceAll("tns:taskName=\".*?\"", "tns:taskName=\"ReadOnlyService\"");
            }

            Definitions def = ((JbpmProfileImpl) profile).getDefinitions(bpmn2in);
            def.setTargetNamespace("http://www.omg.org/bpmn20");

            if (convertServiceTasks != null && convertServiceTasks.equals("true")) {
                // fix the data input associations for converted tasks
                List<RootElement> rootElements = def.getRootElements();
                for (RootElement root : rootElements) {
                    if (root instanceof Process) {
                        updateTaskDataInputs((Process) root, def);
                    }
                }
            }

            // get the xml from Definitions
            ResourceSet rSet = new ResourceSetImpl();
            rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2",
                    new JBPMBpmn2ResourceFactoryImpl());
            JBPMBpmn2ResourceImpl bpmn2resource = (JBPMBpmn2ResourceImpl) rSet
                    .createResource(URI.createURI("virtual.bpmn2"));
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_ENCODING, "UTF-8");
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DEFER_IDREF_RESOLUTION,
                    true);
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_DISABLE_NOTIFY, true);
            bpmn2resource.getDefaultLoadOptions().put(JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF,
                    JBPMBpmn2ResourceImpl.OPTION_PROCESS_DANGLING_HREF_RECORD);
            bpmn2resource.setEncoding("UTF-8");
            rSet.getResources().add(bpmn2resource);
            bpmn2resource.getContents().add(def);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bpmn2resource.save(outputStream, new HashMap<Object, Object>());
            String revisedXmlModel = outputStream.toString();
            String json = profile.createUnmarshaller().parseModel(revisedXmlModel, profile, pp);
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json");
            resp.getWriter().print(json);
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
            resp.setContentType("application/json");
            resp.getWriter().print("{}");
        }
    } else if (transformto != null && transformto.equals(JSON_TO_BPMN2)) {
        try {
            DroolsFactoryImpl.init();
            BpsimFactoryImpl.init();
            if (preprocessingData == null) {
                preprocessingData = "";
            }
            String processXML = profile.createMarshaller().parseModel(jsonin, preprocessingData);
            resp.setContentType("application/xml");
            resp.getWriter().print(processXML);
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
            resp.setContentType("application/xml");
            resp.getWriter().print("");
        }
    } else if (transformto != null && transformto.equals(HTML_TO_PDF)) {
        try {
            resp.setContentType("application/pdf");
            if (processid != null) {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + processid + ".pdf\"");
            } else {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + uuid + ".pdf\"");
            }

            Document pdfDoc = new Document(PageSize.A4);
            PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, resp.getOutputStream());
            pdfDoc.open();
            pdfDoc.addCreator("jBPM Designer");
            pdfDoc.addSubject("Business Process Documentation");
            pdfDoc.addCreationDate();
            pdfDoc.addTitle("Process Documentation");

            HTMLWorker htmlWorker = new HTMLWorker(pdfDoc);
            htmlWorker.parse(new StringReader(htmlSource));
            pdfDoc.close();
        } catch (DocumentException e) {
            resp.sendError(500, e.getMessage());
        }
    }
}

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

License:Apache License

/**
 * Junta varios arquivos pdf em um s.//from   w ww.  jav 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.jrimum.bopepo.pdf.PDFUtil.java

License:Apache License

/**
 * <p>/*  ww  w  .j  a va  2  s . c o m*/
 * Junta varios arquivos pdf em um soh.
 * </p>
 * 
 * @param pdfFiles
 *            Lista de array de bytes
 * 
 * @return Arquivo PDF em forma de byte
 * @since 0.2
 */
@SuppressWarnings("unchecked")
public static byte[] mergeFiles(List<byte[]> pdfFiles) {

    // retorno
    byte[] bytes = null;

    if (isNotNull(pdfFiles) && !pdfFiles.isEmpty()) {

        int pageOffset = 0;
        boolean first = true;

        ArrayList master = null;
        Document document = null;
        PdfCopy writer = null;
        ByteArrayOutputStream byteOS = null;

        try {

            byteOS = new ByteArrayOutputStream();
            master = new ArrayList();

            for (byte[] doc : pdfFiles) {

                if (isNotNull(doc)) {

                    // cria-se um reader para cada documento

                    PdfReader reader = new PdfReader(doc);

                    if (reader.isEncrypted()) {
                        reader = new PdfReader(doc, "".getBytes());
                    }

                    reader.consolidateNamedDestinations();

                    // pega-se o numero total de paginas
                    int n = reader.getNumberOfPages();
                    List bookmarks = SimpleBookmark.getBookmark(reader);

                    if (isNotNull(bookmarks)) {
                        if (pageOffset != 0) {
                            SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                        }
                        master.addAll(bookmarks);
                    }

                    pageOffset += n;

                    if (first) {

                        // passo 1: criar um document-object
                        document = new Document(reader.getPageSizeWithRotation(1));

                        // passo 2: criar um writer que observa o documento
                        writer = new PdfCopy(document, byteOS);
                        document.addAuthor("JRimum Group");
                        document.addSubject("JRimum Merged Document");
                        document.addCreator("JRimum Utilix");

                        // passo 3: abre-se o documento
                        document.open();
                        first = false;
                    }

                    // passo 4: adciona-se o conteudo
                    PdfImportedPage page;
                    for (int i = 0; i < n;) {
                        ++i;
                        page = writer.getImportedPage(reader, i);

                        writer.addPage(page);
                    }
                }
            }

            if (master.size() > 0) {
                writer.setOutlines(master);
            }

            // passo 5: fecha-se o documento
            if (isNotNull(document)) {
                document.close();
            }

            bytes = byteOS.toByteArray();

        } catch (Exception e) {
            LOG.error("", e);
        }
    }
    return bytes;
}

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));
    }/*from  w  w w .j a  v  a 2  s  . 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  ww  .j av a2  s.com
 * @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 ww.  j  av  a2  s.com
@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;/*  w w  w  .java2 s.com*/

    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/*  w ww.  j  a va  2 s .  c  o m*/
 * 
 * @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 w w.j ava  2  s.c om

        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);/*from   ww w  .j av a  2s  .  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();
}