Example usage for org.apache.pdfbox.pdmodel PDDocumentInformation PDDocumentInformation

List of usage examples for org.apache.pdfbox.pdmodel PDDocumentInformation PDDocumentInformation

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocumentInformation PDDocumentInformation.

Prototype

public PDDocumentInformation() 

Source Link

Document

Default Constructor.

Usage

From source file:at.medevit.elexis.impfplan.ui.handlers.PrintVaccinationEntriesHandler.java

License:Open Source License

private void createPDF(Patient patient, Image image) throws IOException, COSVisitorException {
    PDDocumentInformation pdi = new PDDocumentInformation();
    Mandant mandant = (Mandant) ElexisEventDispatcher.getSelected(Mandant.class);
    pdi.setAuthor(mandant.getName() + " " + mandant.getVorname());
    pdi.setCreationDate(new GregorianCalendar());
    pdi.setTitle("Impfausweis " + patient.getLabel());

    PDDocument document = new PDDocument();
    document.setDocumentInformation(pdi);

    PDPage page = new PDPage();
    page.setMediaBox(PDPage.PAGE_SIZE_A4);
    document.addPage(page);//from w w w  .  j  av a2s . c om

    PDRectangle pageSize = page.findMediaBox();
    PDFont font = PDType1Font.HELVETICA_BOLD;

    PDFont subFont = PDType1Font.HELVETICA;

    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.beginText();
    contentStream.setFont(font, 14);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 40);
    contentStream.drawString(patient.getLabel());
    contentStream.endText();

    String dateLabel = sdf.format(Calendar.getInstance().getTime());
    String title = Person.load(mandant.getId()).get(Person.TITLE);
    String mandantLabel = title + " " + mandant.getName() + " " + mandant.getVorname();
    contentStream.beginText();
    contentStream.setFont(subFont, 10);
    contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 55);
    contentStream.drawString("Ausstellung " + dateLabel + ", " + mandantLabel);
    contentStream.endText();

    BufferedImage imageAwt = convertToAWT(image.getImageData());

    PDXObjectImage pdPixelMap = new PDPixelMap(document, imageAwt);
    contentStream.drawXObject(pdPixelMap, 40, 30, pageSize.getWidth() - 80, pageSize.getHeight() - 100);
    contentStream.close();

    String outputPath = CoreHub.userCfg.get(PreferencePage.VAC_PDF_OUTPUTDIR,
            CoreHub.getWritableUserDir().getAbsolutePath());
    if (outputPath.equals(CoreHub.getWritableUserDir().getAbsolutePath())) {
        SWTHelper.showInfo("Kein Ausgabeverzeichnis definiert", "Ausgabe erfolgt in: " + outputPath
                + "\nDas Ausgabeverzeichnis kann unter Einstellungen\\Klinische Hilfsmittel\\Impfplan definiert werden.");
    }
    File outputDir = new File(outputPath);
    File pdf = new File(outputDir, "impfplan_" + patient.getPatCode() + ".pdf");
    document.save(pdf);
    document.close();
    Desktop.getDesktop().open(pdf);
}

From source file:au.org.alfred.icu.pdf.services.factories.ICUDischargeSummaryFactory.java

public static void addDocumentInformation(PDDocument pdf, String title, String subject, String keywords,
        String creator, String author) {

    PDDocumentInformation info = new PDDocumentInformation();

    info.setAuthor(author);//from  w w  w .ja  va 2  s.  c  o  m
    info.setCreationDate(Calendar.getInstance());
    info.setCreator(creator);
    info.setKeywords(keywords);
    info.setSubject(subject);
    info.setTitle("ICU Discharge Summary");

    pdf.setDocumentInformation(info);

}

From source file:com.helger.pdflayout.PageLayoutPDF.java

License:Apache License

/**
 * Render this layout to an OutputStream.
 *
 * @param aCustomizer//from   www.  ja  va  2 s.  c  om
 *        The customizer to be invoked before the document is written to the
 *        stream. May be <code>null</code>.
 * @param aOS
 *        The output stream to write to. May not be <code>null</code>. Is
 *        closed automatically.
 * @throws PDFCreationException
 *         In case of an error
 */
public void renderTo(@Nullable final IPDDocumentCustomizer aCustomizer,
        @Nonnull @WillClose final OutputStream aOS) throws PDFCreationException {
    // create a new document
    PDDocument aDoc = null;

    try {
        aDoc = new PDDocument();

        // Set document properties
        {
            final PDDocumentInformation aProperties = new PDDocumentInformation();
            if (StringHelper.hasText(m_sDocumentAuthor))
                aProperties.setAuthor(m_sDocumentAuthor);
            if (m_aDocumentCreationDate != null)
                aProperties.setCreationDate(m_aDocumentCreationDate);
            if (StringHelper.hasText(m_sDocumentCreator))
                aProperties.setCreator(m_sDocumentCreator);
            if (StringHelper.hasText(m_sDocumentTitle))
                aProperties.setTitle(m_sDocumentTitle);
            if (StringHelper.hasText(m_sDocumentKeywords))
                aProperties.setKeywords(m_sDocumentKeywords);
            if (StringHelper.hasText(m_sDocumentSubject))
                aProperties.setSubject(m_sDocumentSubject);
            aProperties.setProducer("ph-pdf-layout - https://github.com/phax/ph-pdf-layout");
            // add the created properties
            aDoc.setDocumentInformation(aProperties);
        }

        // Prepare all page sets
        final PageSetPrepareResult[] aPRs = new PageSetPrepareResult[m_aPageSets.size()];
        int nPageSetIndex = 0;
        int nTotalPageCount = 0;
        for (final PLPageSet aPageSet : m_aPageSets) {
            final PageSetPrepareResult aPR = aPageSet.prepareAllPages();
            aPRs[nPageSetIndex] = aPR;
            nTotalPageCount += aPR.getPageCount();
            nPageSetIndex++;
        }

        // Start applying all page sets
        nPageSetIndex = 0;
        int nTotalPageIndex = 0;
        for (final PLPageSet aPageSet : m_aPageSets) {
            final PageSetPrepareResult aPR = aPRs[nPageSetIndex];
            aPageSet.renderAllPages(aPR, aDoc, m_bDebug, nPageSetIndex, nTotalPageIndex, nTotalPageCount);
            // Inc afterwards
            nTotalPageIndex += aPR.getPageCount();
            nPageSetIndex++;
        }

        // Customize the whole document (optional)
        if (aCustomizer != null)
            aCustomizer.customizeDocument(aDoc);

        // save document to output stream
        aDoc.save(aOS);

        if (s_aLogger.isDebugEnabled())
            s_aLogger.debug("PDF successfully created");
    } catch (final IOException ex) {
        throw new PDFCreationException("IO Error", ex);
    } catch (final Throwable t) {
        throw new PDFCreationException("Internal error", t);
    } finally {
        // close document
        if (aDoc != null) {
            try {
                aDoc.close();
            } catch (final IOException ex) {
                s_aLogger.error("Failed to close PDF document " + aDoc, ex);
            }
        }

        // Necessary in case of an exception
        StreamUtils.close(aOS);
    }
}

From source file:io.github.qwefgh90.akka.pdf.PDFUtilWrapper.java

License:Apache License

private static PDDocumentInformation createPDFDocumentInfo(String title, String creator, String subject) {
    LOG.info("Setting document info (title, author, subject) for merged PDF");
    PDDocumentInformation documentInformation = new PDDocumentInformation();
    documentInformation.setTitle(title);
    documentInformation.setCreator(creator);
    documentInformation.setSubject(subject);
    return documentInformation;
}

From source file:javaexample.RadialTextPdf.java

License:Open Source License

public void generateDocument() throws IOException, COSVisitorException {
    PDDocument document = new PDDocument();

    try {//from  w  w w.j av a  2 s . c  om
        // Sets some document metadata.
        PDDocumentInformation information = new PDDocumentInformation();
        information.setTitle("Radial Text PDF example with Apache PDFBox");
        information.setAuthor("Andrea Binello (\"andbin\")");
        document.setDocumentInformation(information);

        // Generates and saves the document.
        generatePage(document);
        document.save(filename);
    } finally {
        try {
            document.close();
        } catch (IOException e) {
        }
    }
}

From source file:javaexample.StandardFontsDemoPdf.java

License:Open Source License

public void generateDocument() throws IOException, COSVisitorException {
    document = new PDDocument();

    try {/*from w  w w.  ja  v a  2  s .c  o  m*/
        // Sets some document metadata.
        PDDocumentInformation information = new PDDocumentInformation();
        information.setTitle("Standard fonts demo PDF example with Apache PDFBox");
        information.setAuthor("Andrea Binello (\"andbin\")");
        document.setDocumentInformation(information);

        // Generates and saves the document.
        generatePages();
        document.save(filename);
    } finally {
        try {
            document.close();
        } catch (IOException e) {
        }
    }
}

From source file:net.sf.jabref.plugins.pdftasks.PDFTaskSidePane.java

License:Open Source License

private void doTasks() {

    // PDF file type representation
    final ExternalFileType pdf_type = Globals.prefs.getExternalFileTypeByExt("pdf");

    // get Bibtex database associated with the current tab
    final BasePanel db_panel = frame.basePanel();
    final BibtexDatabase db = db_panel.database();
    final MetaData db_meta = db_panel.metaData();

    // get selected Bibtex entries from the current tab
    final BibtexEntry[] db_entries = db_panel.getSelectedEntries();

    // get Bibtex database file for current tab
    final File db_file = db_panel.getFile();
    if (db_file == null || db_file.getParentFile() == null) {
        JOptionPane.showMessageDialog(frame, "Bibtex database must be saved before performing PDF tasks.",
                title, JOptionPane.INFORMATION_MESSAGE);
        return;/*from   ww w.j av a 2 s  . c o m*/
    }

    // get array of directories that PDF files could possibly be in
    final List<File> db_dirs = new LinkedList<File>();
    for (String dir : db_meta.getFileDirectory(GUIGlobals.FILE_FIELD)) {
        db_dirs.add(new File(dir));
    }
    if (db_dirs.size() == 0 || !db_dirs.contains(db_file.getParentFile())) {
        db_dirs.add(db_file.getParentFile());
    }

    // return if no entries are selected
    if (db_entries.length == 0) {
        JOptionPane.showMessageDialog(frame, "No entries selected for PDF tasks.", title,
                JOptionPane.INFORMATION_MESSAGE);
        return;
    }

    // get PDF file directory
    final File pdf_dir = absoluteFile(pdf_dir_txt.getText(), db_file.getParentFile());

    // do tasks encapsulated in a worker-thread class
    AbstractWorker tasks = new AbstractWorker() {

        boolean cancelled = false;
        boolean confirmed = false;
        boolean erred = false;

        // get user confirmation for PDF file modifications
        private boolean getUserConfirmation() {
            if (!confirmed) {
                confirmed = JOptionPane.showConfirmDialog(frame,
                        "Are you sure you want to rename, move, and/or modify PDF files?\n"
                                + "This operations cannot be undone.",
                        title, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
            }
            return confirmed;
        }

        public void init() {

            // block main window
            frame.block();

        }

        public void run() {

            // for debugging purposes
            final boolean modifyDatabase = true;

            // iterate over selected Bibtex entries
            int entry_count = 0;
            for (BibtexEntry entry : db_entries) {
                ++entry_count;

                // get Bibtex key, check is not null
                String key = entry.getCiteKey();
                if (key == null || key.length() == 0) {
                    JOptionPane.showMessageDialog(frame,
                            "BibTeX entry '" + entry.getId() + "' does not have a key!", title,
                            JOptionPane.ERROR_MESSAGE);
                    erred = true;
                    return;
                }

                // update status bar
                frame.output(String.format("Processing BibTeX entry: %s (%d of %d)...", key, entry_count,
                        db_entries.length));

                // get table of file links for this Bibtex entry
                FileListTableModel files = new FileListTableModel();
                files.setContent(entry.getField(GUIGlobals.FILE_FIELD));

                for (int fileindex = 0; fileindex < files.getRowCount(); ++fileindex) {
                    FileListEntry file_entry = files.getEntry(fileindex);

                    // skip if this is not a PDF file link
                    if (!file_entry.getType().equals(pdf_type))
                        continue;

                    // get PDF file
                    File pdf_file = null;
                    for (File db_dir : db_dirs) {
                        pdf_file = absoluteFile(file_entry.getLink(), db_dir);
                        if (pdf_file.isFile()) {
                            break;
                        }
                        pdf_file = null;
                    }
                    if (pdf_file == null) {
                        String errmsg = "Could not find PDF file '" + file_entry.getLink() + "' in '"
                                + db_dirs.get(0);
                        for (int i = 1; i < db_dirs.size(); ++i) {
                            errmsg += "', '" + db_dirs.get(i);
                        }
                        errmsg += "'!";
                        JOptionPane.showMessageDialog(frame, errmsg, title, JOptionPane.ERROR_MESSAGE);
                        erred = true;
                        return;
                    }

                    // get PDF file description
                    String pdf_desc = file_entry.getDescription();

                    // new PDF file
                    File new_pdf_file = pdf_file;

                    // rename PDF file
                    if (rename_pdfs_chk.isSelected()) {

                        // build new PDF name
                        String new_name = key;
                        if (!pdf_desc.isEmpty()) {
                            new_name += "_" + pdf_desc.replace(" ", "_");
                        }
                        new_name += "." + pdf_type.getExtension();

                        // set new PDF file
                        new_pdf_file = absoluteFile(new_name, new_pdf_file.getParentFile());

                    }

                    // move PDF file
                    if (move_to_pdf_dir_chk.isSelected()) {
                        new_pdf_file = absoluteFile(new_pdf_file.getName(), pdf_dir);
                    }

                    // if PDF file needs to be moved
                    if (!new_pdf_file.equals(pdf_file)) {

                        // get user confirmation
                        if (!getUserConfirmation()) {
                            cancelled = true;
                            return;
                        }

                        // perform move/rename operations
                        if (modifyDatabase) {
                            String errmsg = "";
                            try {

                                // create parent directories
                                File new_pdf_dir = new_pdf_file.getParentFile();
                                if (new_pdf_dir != null && !new_pdf_dir.isDirectory()) {
                                    errmsg = "Could not create directory '"
                                            + new_pdf_file.getParentFile().getPath() + "'";
                                    erred = !new_pdf_file.getParentFile().mkdirs();
                                }
                                if (!erred) {

                                    // check if PDF file already exists, and ask for confirmation to replace it
                                    if (new_pdf_file.isFile()) {
                                        switch (JOptionPane.showConfirmDialog(frame,
                                                "PDF file '" + new_pdf_file.getPath() + "' already exists.\n"
                                                        + "Are you sure you want to replace it with "
                                                        + "PDF file '" + pdf_file.getPath() + "'?\n"
                                                        + "This operation cannot be undone.",
                                                title, JOptionPane.YES_NO_CANCEL_OPTION)) {
                                        case JOptionPane.NO_OPTION:
                                            continue;
                                        case JOptionPane.CANCEL_OPTION:
                                            cancelled = true;
                                            return;
                                        case JOptionPane.YES_OPTION:
                                            errmsg = "Could not delete PDF file '" + new_pdf_file.getPath()
                                                    + "'";
                                            erred = !new_pdf_file.delete();
                                        }
                                    }
                                    // otherwise test that we can create the new PDF file
                                    else {
                                        errmsg = "Could not access PDF file '" + new_pdf_file.getPath() + "'";
                                        erred = !new_pdf_file.createNewFile() || !new_pdf_file.delete();
                                    }

                                    if (!erred) {

                                        // try to move/rename PDF file
                                        errmsg = "Could not rename PDF file '" + pdf_file.getPath() + "' to '"
                                                + new_pdf_file.getPath() + "'";
                                        erred = !pdf_file.renameTo(new_pdf_file);

                                    }

                                }
                            }

                            // possible exceptions
                            catch (SecurityException e) {
                                erred = true;
                                errmsg += ": insufficient permissions";
                            } catch (IOException e) {
                                e.printStackTrace();
                                erred = true;
                                errmsg += ": an I/O exception occurred";
                            }
                            if (erred) {
                                JOptionPane.showMessageDialog(frame, errmsg + ".", title,
                                        JOptionPane.ERROR_MESSAGE);
                                return;
                            }

                            // everything was successful
                            pdf_file = new_pdf_file;

                        }
                    }

                    // update file entry table and Bibtex entry
                    file_entry.setLink(relativePath(pdf_file, db_dirs.get(0)));
                    if (modifyDatabase) {
                        String new_files = files.getStringRepresentation();
                        if (!new_files.equals(entry.getField(GUIGlobals.FILE_FIELD))) {
                            entry.setField(GUIGlobals.FILE_FIELD, new_files);
                            db_panel.markNonUndoableBaseChanged();
                        }
                    }

                    // perform operations on PDF file contents
                    if (write_pdf_docinfo_chk.isSelected()) {

                        if (erase_pdf_docinfo_chk.isSelected()) {

                            // get user confirmation
                            if (!getUserConfirmation()) {
                                cancelled = true;
                                return;
                            }

                            // open PDF file
                            PDDocument document = null;
                            try {
                                document = PDDocument.load(pdf_file);
                            } catch (IOException e) {
                                e.printStackTrace();
                                erred = true;
                                JOptionPane.showMessageDialog(frame,
                                        "Could not open PDF file '" + pdf_file.getPath()
                                                + "': an I/O exception occurred.",
                                        title, JOptionPane.ERROR_MESSAGE);
                                return;
                            }

                            // erase document information
                            document.setDocumentInformation(new PDDocumentInformation());

                            // erase XML metadata
                            document.getDocumentCatalog().setMetadata(null);

                            // save and close PDF file
                            try {
                                document.save(pdf_file.getPath());
                                document.close();
                            } catch (COSVisitorException e) {
                                e.printStackTrace();
                                erred = true;
                                JOptionPane.showMessageDialog(frame,
                                        "Could not save PDF file '" + pdf_file.getPath()
                                                + "': an exception occurred.",
                                        title, JOptionPane.ERROR_MESSAGE);
                                return;
                            } catch (IOException e) {
                                e.printStackTrace();
                                erred = true;
                                JOptionPane.showMessageDialog(frame,
                                        "Could not save/close PDF file '" + pdf_file.getPath()
                                                + "': an I/O exception occurred.",
                                        title, JOptionPane.ERROR_MESSAGE);
                                return;
                            }

                        }

                        // write XMP / PDF document catalog metadata
                        try {
                            XMPUtil.writeXMP(pdf_file, entry, db);
                        } catch (IOException e) {
                            e.printStackTrace();
                            erred = true;
                            JOptionPane.showMessageDialog(frame,
                                    "Could not write XMP to PDF file '" + pdf_file.getPath()
                                            + "': an I/O exception occurred.",
                                    title, JOptionPane.ERROR_MESSAGE);
                            return;
                        } catch (TransformerException e) {
                            e.printStackTrace();
                            erred = true;
                            JOptionPane
                                    .showMessageDialog(frame,
                                            "Could not write XMP to PDF file '" + pdf_file.getPath()
                                                    + "': an exception occurred.",
                                            title, JOptionPane.ERROR_MESSAGE);
                            return;
                        }

                    }

                }

            }

        }

        public void update() {

            // unblock main window
            frame.unblock();

            // print to status bar
            if (erred) {
                frame.output("An error occurred during PDF Tasks");
            } else if (cancelled) {
                frame.output("Cancelled PDF Tasks");
            } else {
                frame.output("Completed PDF Tasks");
            }

        }

    };

    // run task thread (based on code in BasePanel.runCommand())
    try {
        tasks.init();
        tasks.getWorker().run();
        tasks.getCallBack().update();
    } catch (Throwable e) {
        frame.unblock();
        e.printStackTrace();
    }

}

From source file:org.mustangproject.ZUGFeRD.ZUGFeRDExporter.java

License:Open Source License

protected void prepareDocument() throws IOException {
    String fullProducer = producer + " (via mustangproject.org " + org.mustangproject.ZUGFeRD.Version.VERSION
            + ")";

    PDDocumentCatalog cat = doc.getDocumentCatalog();
    metadata = new PDMetadata(doc);
    cat.setMetadata(metadata);//from w w  w  .  j  a  v  a 2s . c o m

    xmp = XMPMetadata.createXMPMetadata();

    pdfaid = new PDFAIdentificationSchema(xmp);

    xmp.addSchema(pdfaid);

    DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();

    dc.addCreator(creator);

    XMPBasicSchema xsb = xmp.createAndAddXMPBasicSchema();

    xsb.setCreatorTool(creatorTool);
    xsb.setCreateDate(GregorianCalendar.getInstance());
    // PDDocumentInformation pdi=doc.getDocumentInformation();
    PDDocumentInformation pdi = new PDDocumentInformation();
    pdi.setProducer(fullProducer);
    pdi.setAuthor(creator);
    doc.setDocumentInformation(pdi);

    AdobePDFSchema pdf = xmp.createAndAddAdobePDFSchema();
    pdf.setProducer(fullProducer);
    if (ensurePDFisUpgraded) {
        try {
            pdfaid.setConformance(conformanceLevel.getLetter());// $NON-NLS-1$ //$NON-NLS-1$
        } catch (BadFieldValueException ex) {
            // This should be impossible, because it would occur only if an illegal
            // conformance level is supplied,
            // however the enum enforces that the conformance level is valid.
            throw new Error(ex);
        }

        pdfaid.setPart(3);
    }
    addXMP(xmp); /*
                    * this is the only line where we do something Zugferd-specific, i.e. add PDF
                    * metadata specifically for Zugferd, not generically for a embedded file
                    */

    try {
        metadata.importXMPMetadata(serializeXmpMetadata(xmp));

    } catch (TransformerException e) {
        throw new ZUGFeRDExportException("Could not export XmpMetadata", e);
    }
    documentPrepared = true;
}

From source file:org.pdfmetamodifier.MetadataHelper.java

License:Apache License

/**
 * Convert list of lines to Metadata object.
 * /*from ww  w  .j  a  v  a 2  s .  c o m*/
 * @param lineList
 *            Source list of lines with Metadata representation.
 * @return Metadata object.
 */
public static PDDocumentInformation stringListToMetadata(final List<String> lineList) {
    final PDDocumentInformation documentInformation = new PDDocumentInformation();

    if (lineList != null) {
        for (String line : lineList) {
            final Matcher matcher = METADATA_LINE_PATTERN.matcher(line);
            if (!matcher.matches()) {
                throw new IllegalArgumentException(
                        String.format("Metadata line have a wrong format: '%s'!", line));
            }
            documentInformation.setCustomMetadataValue(matcher.group("key"), matcher.group("value"));
        }
    }

    return documentInformation;
}

From source file:org.primaresearch.pdf.PageToPdfConverterUsingPdfBox.java

License:Apache License

private void addMetadata(PDDocument doc, Page page) {
    MetaData pageMetadata = page.getMetaData();

    PDDocumentInformation info = new PDDocumentInformation();

    //Creator/*from  w w w . java2s .c  o  m*/
    if (pageMetadata.getCreator() != null && !pageMetadata.getCreator().isEmpty())
        info.setCreator(pageMetadata.getCreator());

    //Comments
    if (pageMetadata.getComments() != null && !pageMetadata.getComments().isEmpty())
        info.setCustomMetadataValue("Comments", pageMetadata.getComments());

    //TODO

    doc.setDocumentInformation(info);
}