List of usage examples for org.apache.pdfbox.pdmodel PDDocument save
public void save(OutputStream output) throws IOException
From source file:org.primaresearch.pdf.PageToPdfConverterUsingPdfBox.java
License:Apache License
public void convert(Collection<Page> pages, String targetPdf) { try {//from www . j a v a2 s . c o m // Create a new empty document PDDocument document = new PDDocument(); //Metadata (use first page) if (pages.size() > 0) addMetadata(document, pages.iterator().next()); //Font createFont(document); //Add pages for (Iterator<Page> it = pages.iterator(); it.hasNext();) addPage(document, it.next()); // Save the newly created document document.save(targetPdf); // finally make sure that the document is properly // closed. document.close(); } catch (Exception exc) { exc.printStackTrace(); } }
From source file:org.primaresearch.pdf.PageToPdfConverterUsingPdfBox.java
License:Apache License
public void convert(Page page, String targetPdf) { try {/*w ww .j a v a 2 s . co m*/ // Create a new empty document PDDocument document = new PDDocument(); //Metadata addMetadata(document, page); //Font createFont(document); //Add page addPage(document, page); // Save the newly created document document.save(targetPdf); // finally make sure that the document is properly // closed. document.close(); } catch (Exception exc) { exc.printStackTrace(); } }
From source file:org.socialbiz.cog.util.PDFUtil.java
License:Apache License
public static void main(String[] args) { //For test try {/*from ww w . j av a 2 s. c o m*/ String path = args[0]; PDDocument document = new PDDocument(); PDPage page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); document.addPage(page); PDFont font = PDType1Font.HELVETICA; PDPageContentStream contentStream = new PDPageContentStream(document, page, false, false); contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 800); String x = "hello world"; contentStream.drawString(x); contentStream.moveTextPositionByAmount(-90, -15); contentStream.setFont(font, 12); contentStream.drawString("Hello World3"); contentStream.endText(); contentStream.close(); document.save(path); document.close(); System.out.println("DONE.."); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.wangwei.pdf.AddImageToPDF.java
License:Apache License
/** * Add an image to an existing PDF document. * * @param inputFile The input PDF to add the image to. * @param image The filename of the image to put in the PDF. * @param outputFile The file to write to the pdf to. * @throws IOException If there is an error writing the data. * @throws COSVisitorException If there is an error writing the PDF. *//*from www. ja v a2s .com*/ public void createPDFFromImage(String inputFile, String image, String outputFile) throws IOException, COSVisitorException { // the document PDDocument doc = null; try { doc = PDDocument.load(inputFile); // we will add the image to the first page. PDPage page = (PDPage) doc.getDocumentCatalog().getAllPages().get(0); PDXObjectImage ximage = null; if (image.toLowerCase().endsWith(".jpg")) { ximage = new PDJpeg(doc, new FileInputStream(image)); } else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff")) { ximage = new PDCcitt(doc, new RandomAccessFile(new File(image), "r")); } else { BufferedImage awtImage = ImageIO.read(new File(image)); ximage = new PDPixelMap(doc, awtImage); } PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true); // contentStream.drawImage(ximage, 20, 20 ); // better method inspired by http://stackoverflow.com/a/22318681/535646 float scale = 1f; // reduce this value if the image is too large contentStream.drawXObject(ximage, 20, 20, ximage.getWidth() * scale, ximage.getHeight() * scale); contentStream.close(); doc.save(outputFile); } finally { if (doc != null) { doc.close(); } } }
From source file:org.wso2.carbon.apimgt.impl.reportgen.ReportGenerator.java
License:Open Source License
/** * Generate PDF file for API microgateway request summary * * @param table object containing table headers and row data * @return InputStream pdf as a stream/*from w w w . j a va 2 s.c om*/ * @throws IOException * @throws COSVisitorException */ public InputStream generateMGRequestSummeryPDF(TableData table) throws IOException, COSVisitorException { String[] columnHeaders = table.getColumnHeaders(); PDDocument document = new PDDocument(); PDPage page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); page.setRotation(0); document.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(document, page, false, false); // add logo InputStream in = APIManagerComponent.class.getResourceAsStream("/report/wso2-logo.jpg"); PDJpeg img = new PDJpeg(document, in); contentStream.drawImage(img, 375, 755); // Add topic contentStream.setFont(PDType1Font.HELVETICA_BOLD, 16); writeContent(contentStream, CELL_MARGIN, 770, "API Microgateway request summary"); // Add generated time contentStream.setFont(PDType1Font.HELVETICA_BOLD, FONT_SIZE); writeContent(contentStream, CELL_MARGIN, 730, "Report generated on: " + new Date().toString()); contentStream.setFont(TEXT_FONT, FONT_SIZE); // add table with data drowTableGrid(contentStream, table.getRows().size()); writeRowsContent(contentStream, columnHeaders, table.getRows()); // Add meta data // Whenever the summary report structure is updated this should be changed String requestCount = table.getRows().get(0).getEntries().get(2); document.getDocumentInformation().setCustomMetadataValue(MGW_META, getMetaCount(requestCount)); contentStream.close(); ByteArrayOutputStream out = new ByteArrayOutputStream(); document.save(out); document.close(); return new ByteArrayInputStream(out.toByteArray()); }
From source file:org.xstudiosys.pdfxmp.AddMetadataFromDocInfo.java
License:Apache License
/** * This will print the documents data.//from ww w . j a v a 2 s . c o m * * @param args The command line arguments. * * @throws Exception If there is an error parsing the document. */ public static void main(String[] args) throws Exception { if (args.length != 2) { usage(); } else { PDDocument document = null; try { document = PDDocument.load(args[0]); if (document.isEncrypted()) { System.err.println("Error: Cannot add metadata to encrypted document."); System.exit(1); } PDDocumentCatalog catalog = document.getDocumentCatalog(); PDDocumentInformation info = document.getDocumentInformation(); XMPMetadata metadata = new XMPMetadata(); XMPSchemaPDF pdfSchema = metadata.addPDFSchema(); pdfSchema.setKeywords(info.getKeywords()); pdfSchema.setProducer(info.getProducer()); XMPSchemaBasic basicSchema = metadata.addBasicSchema(); basicSchema.setModifyDate(info.getModificationDate()); basicSchema.setCreateDate(info.getCreationDate()); basicSchema.setCreatorTool(info.getCreator()); basicSchema.setMetadataDate(new GregorianCalendar()); XMPSchemaDublinCore dcSchema = metadata.addDublinCoreSchema(); dcSchema.setTitle(info.getTitle()); dcSchema.addCreator("PDFBox"); dcSchema.setDescription(info.getSubject()); PDMetadata metadataStream = new PDMetadata(document); metadataStream.importXMPMetadata(metadata); catalog.setMetadata(metadataStream); document.save(args[1]); } finally { if (document != null) { document.close(); } } } }
From source file:org.xstudiosys.pdfxmp.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 w w . j a va 2s. 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.xstudiosys.pdfxmp.XMPUtil.java
License:Open Source License
/** * Try to write the given BibTexEntry in the XMP-stream of the given * PDF-file.//from w ww . ja v a 2 s . c om * * Throws an IOException if the file cannot be read or written, so the user * can remove a lock or cancel the operation. * * The method will overwrite existing BibTeX-XMP-data, but keep other * existing metadata. * * @param file * The file to write the entries to. * @param bibtexEntries * The entries to write to the file. * * @param database * maybenull An optional database which the given bibtex entries * belong to, which will be used to resolve strings. If the * database is null the strings will not be resolved. * @param writePDFInfo * Write information also in PDF document properties * @throws TransformerException * If the entry was malformed or unsupported. * @throws IOException * If the file could not be written to or could not be found. */ @SuppressWarnings("unchecked") public static void writeXMP(File file, Collection<BibtexEntry> bibtexEntries, BibtexDatabase database, boolean writePDFInfo) throws IOException, TransformerException { if (database != null) bibtexEntries = database.resolveForStrings(bibtexEntries, false); PDDocument document = null; try { document = PDDocument.load(file.getAbsoluteFile()); if (document.isEncrypted()) { throw new EncryptionNotSupportedException("Error: Cannot add metadata to encrypted document."); } if (writePDFInfo && bibtexEntries.size() == 1) { writeDocumentInformation(document, bibtexEntries.iterator().next(), null); writeDublinCore(document, bibtexEntries, null); } PDDocumentCatalog catalog = document.getDocumentCatalog(); PDMetadata metaRaw = catalog.getMetadata(); XMPMetadata meta; if (metaRaw != null) { meta = new XMPMetadata(XMLUtil.parse(metaRaw.createInputStream())); } else { meta = new XMPMetadata(); } meta.addXMLNSMapping(XMPSchemaBibtex.NAMESPACE, XMPSchemaBibtex.class); // Remove all current Bibtex-schemas List<XMPSchema> schemas = meta.getSchemasByNamespaceURI(XMPSchemaBibtex.NAMESPACE); for (XMPSchema schema : schemas) { XMPSchemaBibtex bib = (XMPSchemaBibtex) schema; bib.getElement().getParentNode().removeChild(bib.getElement()); } for (BibtexEntry e : bibtexEntries) { XMPSchemaBibtex bibtex = new XMPSchemaBibtex(meta); meta.addSchema(bibtex); bibtex.setBibtexEntry(e, null); } // Save to stream and then input that stream to the PDF ByteArrayOutputStream os = new ByteArrayOutputStream(); meta.save(os); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); PDMetadata metadataStream = new PDMetadata(document, is, false); catalog.setMetadata(metadataStream); // Save try { document.save(file.getAbsolutePath()); } catch (COSVisitorException e) { throw new TransformerException("Could not write XMP-metadata: " + e.getLocalizedMessage()); } } finally { if (document != null) { document.close(); } } }
From source file:paper2ebook.Transformer.java
License:Apache License
public static void main(String[] args) throws IOException, COSVisitorException { String original_pdf;//from w w w . j a va 2 s . c om if (args.length < 1 || args.length > 2) { System.err.println("Usage: java -jar paper2ebook-*.jar input.pdf [output.pdf]"); return; } else { original_pdf = args[0]; } Transformer transformer = new Transformer(PDDocument.load(original_pdf)); PDDocument output = transformer.extract(); if (args.length == 1) { String orig_no_pdf = original_pdf.substring(0, original_pdf.length() - 4); output.save(orig_no_pdf + "_ebook.pdf"); } else { output.save(args[1]); } }
From source file:patient_records_mng_sys.balamu.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String latta = "Lotta"; System.out.println("Dagakara" + latta + " Balla"); // String var="Testing"; // jLabel1.setText("HelloMto! "+var+""); String bloody = "1227"; try {//from w w w . j a v a 2 s. c o m System.out.println("Create Simple PDF file with Text"); String fileName = "patientReport.pdf"; // name of our file PDDocument doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream content = new PDPageContentStream(doc, page); content.beginText(); content.setFont(PDType1Font.HELVETICA, 20); content.moveTextPositionByAmount(220, 750); content.drawString("Patient Report Form"); content.endText(); int x = 80; int y = 700; String spac = " "; String documen = "PatientID" + spac + "PatientName" + spac + "Clinic" + spac + "Diagnose"; content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.moveTextPositionByAmount(x, 710); content.drawString(documen); content.endText(); //To add from database// Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/itp?" + "user=root&password=sparksndl"); Statement sqlState = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String selectStuff = "Select `ID`,`patient_id`,`clinicName`,`diagnosis`,`dateOfEntry`,`allergiesIdentified`,`Remarks`,`nextClinicDate`,`ward` FROM `medical_records` WHERE `patient_id` LIKE " + bloody + " "; rows = sqlState.executeQuery(selectStuff); Object[] tempRow; String[] records; while (rows.next()) { //tempRow=new Object[]{rows.getString(1),rows.getString(2),rows.getString(3),rows.getString(4),rows.getDate(5),rows.getString(6),rows.getString(7),rows.getString(8)}; //dTableModel.addRow(tempRow); String id = rows.getString(1); String name = "Classified"; String clinic = rows.getString(3); String diagnose = rows.getString(4); String aller = rows.getString(6); String remark = rows.getString(7); String space = " "; String document = id + space + space + space + name + space + space + clinic + space + diagnose; content.beginText(); content.setFont(PDType1Font.HELVETICA, 8); content.moveTextPositionByAmount(x, y); content.drawString(document); content.endText(); y = y - 12; } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } //Over// content.close(); doc.save(fileName); doc.close(); System.out.println("your file created in : " + System.getProperty("user.dir")); } catch (IOException | COSVisitorException e) { System.out.println(e.getMessage()); } // TODO add your handling code here: }