List of usage examples for org.apache.pdfbox.pdmodel PDDocument setDocumentInformation
public void setDocumentInformation(PDDocumentInformation info)
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 ww w. j a va2 s . 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);// ww 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//ww w .j a v a2 s . c o m * 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:de.offis.health.icardea.cied.pdf.extractor.PDFApachePDFBoxExtractor.java
License:Apache License
@SuppressWarnings("unchecked") public byte[] getPDFPages(int fromPageNumber, int toPageNumber) { ByteArrayOutputStream byteArrayOutputStream = null; boolean extractionSuccessful = false; if (pdfDocument != null) { int numberOfPages = getNumberOfPages(); /*/*from w w w .j a va 2 s .c o m*/ * Check if the given page numbers are in the allowed range. */ if (fromPageNumber > 0 && fromPageNumber <= numberOfPages && toPageNumber > 0 && toPageNumber <= numberOfPages) { /* * Now check if the given fromPageNumber is smaller * as the given toPageNumber. If not swap the numbers. */ if (fromPageNumber > toPageNumber) { int tmpPageNumber = toPageNumber; toPageNumber = fromPageNumber; fromPageNumber = tmpPageNumber; } /* * Now extract the pages * * NOTE * ==== * Since Apache PDFBox v1.5.0 there exists the class * org.apache.pdfbox.util.PageExtractor */ /* boolean isApachePageExtractorAvailable = false; Class<?> pageExtractorClass = null; try { pageExtractorClass = getClass().getClassLoader().loadClass("org.apache.pdfbox.util.PageExtractor"); Constructor<?> pdfExtractConstructor = pageExtractorClass.getConstructor(PDDocument.class, int.class, int.class); Method pdfExtractMethod = pageExtractorClass.getMethod("extract"); isApachePageExtractorAvailable = true; } catch (ClassNotFoundException ex) { } catch (SecurityException ex) { } catch (NoSuchMethodException ex) { } */ try { PDDocument extractedDocumentPages = new PDDocument(); extractedDocumentPages.setDocumentInformation(this.pdfDocument.getDocumentInformation()); extractedDocumentPages.getDocumentCatalog() .setViewerPreferences(this.pdfDocument.getDocumentCatalog().getViewerPreferences()); List<PDPage> pages = (List<PDPage>) this.pdfDocument.getDocumentCatalog().getAllPages(); int pageCounter = 1; for (PDPage page : pages) { if (pageCounter >= fromPageNumber && pageCounter <= toPageNumber) { PDPage importedPdfPage; importedPdfPage = extractedDocumentPages.importPage(page); importedPdfPage.setCropBox(page.findCropBox()); importedPdfPage.setMediaBox(page.findMediaBox()); importedPdfPage.setResources(page.findResources()); importedPdfPage.setRotation(page.findRotation()); } pageCounter++; } // end for byteArrayOutputStream = new ByteArrayOutputStream(); extractedDocumentPages.save(byteArrayOutputStream); extractedDocumentPages.close(); extractionSuccessful = true; } catch (COSVisitorException ex) { // TODO: Create an own exception for PDF processing errors. logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex); } catch (IOException ex) { // TODO: Create an own exception for PDF processing errors. logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex); } finally { if (!extractionSuccessful) { byteArrayOutputStream = null; } } // end try..catch..finally } // end if checking range of given pages } // end if (pdfDocument != null) if (byteArrayOutputStream != null) { return byteArrayOutputStream.toByteArray(); } return null; }
From source file:io.konik.carriage.pdfbox.PDFBoxInvoiceAppender.java
License:Open Source License
private void setMetadata(PDDocument doc, AppendParameter appendParameter) throws IOException, TransformerException, BadFieldValueException, XmpSerializationException { Calendar now = Calendar.getInstance(); PDDocumentCatalog catalog = doc.getDocumentCatalog(); PDMetadata metadata = new PDMetadata(doc); catalog.setMetadata(metadata);//from w ww. j ava 2 s .c o m XMPMetadata xmp = XMPMetadata.createXMPMetadata(); PDFAIdentificationSchema pdfaid = new PDFAIdentificationSchema(xmp); pdfaid.setPart(Integer.valueOf(3)); pdfaid.setConformance("B"); xmp.addSchema(pdfaid); DublinCoreSchema dublicCore = new DublinCoreSchema(xmp); xmp.addSchema(dublicCore); XMPBasicSchema basicSchema = new XMPBasicSchema(xmp); basicSchema.setCreatorTool(PRODUCER); basicSchema.setCreateDate(now); xmp.addSchema(basicSchema); PDDocumentInformation pdi = doc.getDocumentInformation(); pdi.setModificationDate(now); pdi.setProducer(PRODUCER); pdi.setAuthor(getAuthor()); doc.setDocumentInformation(pdi); AdobePDFSchema pdf = new AdobePDFSchema(xmp); pdf.setProducer(PRODUCER); xmp.addSchema(pdf); PDMarkInfo markinfo = new PDMarkInfo(); markinfo.setMarked(true); doc.getDocumentCatalog().setMarkInfo(markinfo); xmp.addSchema(zfDefaultXmp.getPDFExtensionSchema()); XMPSchemaZugferd1p0 zf = new XMPSchemaZugferd1p0(xmp); zf.setConformanceLevel(appendParameter.zugferdConformanceLevel()); zf.setVersion(appendParameter.zugferdVersion()); xmp.addSchema(zf); new XmpSerializer().serialize(xmp, metadata.createOutputStream(), true); }
From source file:javaexample.RadialTextPdf.java
License:Open Source License
public void generateDocument() throws IOException, COSVisitorException { PDDocument document = new PDDocument(); try {/*ww w . j av a 2s . c o m*/ // 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: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 www . java 2 s .com } // 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.crossref.pdfmark.Main.java
License:Open Source License
public static void writeInfoDictionary(FileInputStream in, String outputFile, byte[] xmp) throws IOException, COSVisitorException { PDFParser parser = new PDFParser(in); parser.parse();// w ww . j av a 2 s. co m PDDocument document = parser.getPDDocument(); PDDocumentInformation info = document.getDocumentInformation(); for (Entry<String, String> entry : XmpUtils.toInfo(xmp).entrySet()) { info.setCustomMetadataValue(entry.getKey(), entry.getValue()); } document.setDocumentInformation(info); document.save(outputFile); document.close(); }
From source file:org.nuxeo.pdf.PDFUtils.java
License:Open Source License
/** * Convenience method: If a parameter is null or "", it is not modified * * @param inPdfDoc// w w w . ja va 2 s . c om * @param inTitle * @param inSubject * @param inAuthor * */ public static void setInfos(PDDocument inPdfDoc, String inTitle, String inSubject, String inAuthor) { if (inTitle != null && inTitle.isEmpty()) { inTitle = null; } if (inSubject != null && inSubject.isEmpty()) { inSubject = null; } if (inAuthor != null && inAuthor.isEmpty()) { inAuthor = null; } if (inTitle != null || inAuthor != null || inSubject != null) { PDDocumentInformation docInfo = inPdfDoc.getDocumentInformation(); if (inTitle != null) { docInfo.setTitle(inTitle); } if (inSubject != null) { docInfo.setSubject(inSubject); } if (inAuthor != null) { docInfo.setAuthor(inAuthor); } inPdfDoc.setDocumentInformation(docInfo); } }
From source file:org.pdfmetamodifier.IOHelper.java
License:Apache License
/** * Update Metadata.//from www . j a va2 s. co m * * @param pdfFile * Source PDF file. * @param metadataFile * File with Metadata in user-frendly format. * @throws IOException */ /* * See: * https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ExtractMetadata.java?view=markup */ public static void updateMetadata(final File pdfFile, final File metadataFile) throws IOException { // Read bookmark list from text file. final List<String> lines = Files.readAllLines(metadataFile.toPath()); PDDocument document = null; try { // Open PDF file. document = PDDocument.load(pdfFile); if (document.isEncrypted()) { throw new IOException("Document is encrypted."); } // Convert. final PDDocumentInformation information = MetadataHelper.stringListToMetadata(lines); // Set Metadata. document.setDocumentInformation(information); // Create temporary PDF file for result. if (TEMP_PDF.exists()) { TEMP_PDF.delete(); } // Save result to temporary PDF file. document.save(TEMP_PDF); // Replace original PDF file. pdfFile.delete(); Files.move(Paths.get(TEMP_PDF.toURI()), Paths.get(pdfFile.toURI())); } finally { if (document != null) { document.close(); } } }