List of usage examples for org.apache.pdfbox.pdmodel PDDocument save
public void save(OutputStream output) throws IOException
From source file:domain.mediator.PDFGeneration.java
public static void printRecapPDF(List<Recap> recapList, Driver driver, Load load, GPSLocation currentLocation) throws IOException { Table recapTable = RecapList.drawRecapTable(recapList); File saveFile = new File("recapTable.pdf"); PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page);//from ww w .ja v a 2s .co m PDPageContentStream pageContentStream = new PDPageContentStream(document, page); float contentPositionX = 40; float contentPositionY = page.getMediaBox().getHeight() - 50; PDFGeneration.printHeaderAndDataTable(pageContentStream, contentPositionX, contentPositionY, driver, load, currentLocation, recapTable); pageContentStream.close(); document.save(saveFile); document.close(); PDFGeneration.openFile(saveFile); }
From source file:dtlgenerator.myDataReader.java
public void PdfGenerator(String pdfFileNameBase, List<String> cycles) throws IOException, COSVisitorException { GlobalVar.dirMake(new File(pdfFileNameBase)); //create a folder with the same name int rowCount = 0; int pageCount = 1; PDPage page; //default size PAGE_SIZE_A4 PDPageContentStream stream;//from w ww . ja v a2s .c o m //page.setRotation(90); //counterclock wise rotate 90 degree ////left hand rule // stream.setFont(PDType1Font.COURIER, FONT_SIZE); String lastUpdate = null; String lastCycle = null; System.out.println("DTL_DATA keyset:" + DTL_DATA.keySet()); System.out.println("Cycles empty? " + cycles.isEmpty()); System.out.println(cycles); for (String updateDate : DTL_DATA.keySet()) { Map<String, List<String>> thisDTData = DTL_DATA.get(updateDate); lastUpdate = updateDate; System.out.println("thisDT_DATA keyset:" + thisDTData.keySet()); for (String cycle : thisDTData.keySet()) { if (cycles.isEmpty() || cycles.contains(cycle)) { PDDocument pdf = new PDDocument(); lastCycle = cycle; List<String> thisCycle = thisDTData.get(cycle); pageCount = 1; // new cycle, restart page num page = new PDPage(); //page break stream = new PDPageContentStream(pdf, page, true, false); stream.beginText(); page.setRotation(PAGE_ROT_DEGREE); //stream.setFont(PDType1Font.COURIER, FONT_SIZE); addBigFontUpdateNumberAndCycle(updateDate, cycle, stream); stream.setFont(PDType1Font.COURIER, FONT_SIZE); // stream.setFont(PDType1Font. int thisCycleRowCount = 0; for (String row : thisCycle) { if (thisCycleRowCount > MAX_NUM_TRANS) { //close the current page setupFootNote(stream, pageCount, cycle, updateDate); pageCount++; stream.endText(); stream.close(); pdf.addPage(page); // start a new page page = new PDPage(); stream = new PDPageContentStream(pdf, page, true, false); page.setRotation(PAGE_ROT_DEGREE); stream.beginText(); stream.setFont(PDType1Font.COURIER, FONT_SIZE); thisCycleRowCount = 0; } stream.setTextRotation(TEXT_ROT_RAD, TRANS_X + thisCycleRowCount * INVERVAL_X, TRANS_Y); stream.drawString(row); thisCycleRowCount++; //System.out.println("Update:" + updateDate + " Cycle: " + cycle + " " + row); } setupFootNote(stream, pageCount, lastCycle, lastUpdate); stream.endText(); stream.close(); pdf.addPage(page); String pdfFileName = pdfFileNameBase + "\\DTL UPDT " + updateDate + " " + cycle + ".pdf"; pdf.save(pdfFileName); pdf.close(); } } } // pdf.save(pdfFileName); // pdf.close(); }
From source file:es.ucm.pdfmeta.Main.java
License:Open Source License
public static void main(String[] args) { PDDocument doc = null; try {/* w w w . jav a 2s . c o m*/ if (args.length > 0) { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); for (String arg : args) { File f = new File(arg); doc = PDDocument.load(f); MetadataModel<String> m = buildModelFromDocument(doc); Controller c = new Controller(m); MainDialog md = new MainDialog(arg, m, c); if (md.runDialog()) { modifyDocFromModel(doc, m); doc.save(arg); } } } else { System.err.println("error: no input file(s) specified"); } } catch (IOException ex) { JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } finally { if (doc != null) try { doc.close(); } catch (IOException ex) { } } }
From source file:es.udc.fic.medregatas.util.PDFUtils.java
public static void printPDF(String docName) throws IOException, COSVisitorException { createPdfDirectoryIfNotExists();/*from w ww . j a v a 2 s . c o m*/ // Create a document and add a page to it PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page); // Create a new font object selecting one of the PDF base fonts PDFont font = PDType1Font.HELVETICA_BOLD; // Start a new content stream which will "hold" the to be created content PDPageContentStream contentStream = new PDPageContentStream(document, page); // Define a text content stream using the selected font, moving the // cursor and drawing the text "Hello World" contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 700); contentStream.drawString("Hello World"); contentStream.endText(); // Make sure that the content stream is closed: contentStream.close(); // Save the results and ensure that the document is properly closed: document.save(PDFS_FOLDER + "/" + docName); document.close(); }
From source file:eu.europa.ec.markt.dss.signature.pdf.pdfbox.PdfBoxWriter.java
License:Open Source License
public PdfBoxWriter(PDDocument document, OutputStream output) throws IOException { this.document = document; try {/*from w ww . ja v a 2 s .co m*/ this.output = output; File tempDocumentIn = new File("target/copyoffile.pdf"); tempOutput = new FileOutputStream(tempDocumentIn); document.save(tempOutput); tempOutput.close(); tempInput = new FileInputStream(tempDocumentIn); tempDocumentOut = new File("target/copyoffileout.pdf"); tempOutput = new FileOutputStream(tempDocumentOut); DSSUtils.copy(tempInput, tempOutput); tempInput.close(); tempInput = new FileInputStream(tempDocumentIn); } catch (COSVisitorException e) { throw new IOException(e); } }
From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java
License:EUPL
/** * Save {@link PDDocument} to bytes array * /*from w ww . j av a 2 s .c om*/ * @param doc the doc to save * @return the byte array * @throws COSVisitorException * @throws IOException */ private static byte[] toByteArray(PDDocument doc) throws COSVisitorException, IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); doc.save(os); closeQuietly(doc); return os.toByteArray(); }
From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtilsTest.java
License:EUPL
/** * Test PDF seal/* w w w .j a v a2 s. c o m*/ * @throws COSVisitorException * @throws IOException * @throws KeyStoreException * @throws NoSuchAlgorithmException */ @Test public void testSeal() throws COSVisitorException, IOException, KeyStoreException, NoSuchAlgorithmException { //load our test document - an iText PDF as generated by the Portal report service InputStream is = PdfUtils.class.getClassLoader().getResourceAsStream("dss/testseal.pdf"); byte[] pdf = IOUtils.toByteArray(is); is.close(); //Attach the form XML String attachment = "<xmldata></xmldata>"; byte[] doc = PdfUtils.appendAttachment(pdf, attachment.getBytes(), "form.xml"); //Seal the document InputStream isP12 = PdfUtilsTest.class.getClassLoader().getResourceAsStream("dss/test.p12"); Pkcs12SignatureToken token = new Pkcs12SignatureToken("password", isP12); byte[] sealed = PdfUtils.sealPDFCustom(doc, token, "This file allows us to check that the form is authentic"); InputStream isse = new ByteArrayInputStream(sealed); PDDocument sealedPDD = PDDocument.load(isse); ByteArrayOutputStream baos = new ByteArrayOutputStream(); sealedPDD.save(baos); sealed = baos.toByteArray(); //Sign the document (like a portal user should) CertificateVerifier cv = new CommonCertificateVerifier(); PAdESService p = new PAdESService(cv); DSSDocument dssDoc = new InMemoryDocument(sealed); SignatureParameters params = new SignatureParameters(); params.setPrivateKeyEntry(token.getKeys().get(0)); params.setSignatureLevel(SignatureLevel.PAdES_BASELINE_B); params.setSigningToken(token); params.setDigestAlgorithm(DigestAlgorithm.SHA512); Calendar c = GregorianCalendar.getInstance(); c.set(Calendar.YEAR, 2011); params.bLevel().setSigningDate(c.getTime()); DSSDocument sDoc = p.signDocument(dssDoc, params); //Test that the seal is OK. assertTrue(TestUtils.isSealed(null, sDoc.getBytes(), token, SealMethod.SEAL_CUSTOM)); }
From source file:evadoc_splitter.pdfsplitter.java
private void split_report(Rectangle2D programa_area, Rectangle2D periodo_area, Rectangle2D id_area, Rectangle2D nombre_area, String type, int numberOfPages) { // pages = this.doc //crear hash id=>nombre que se guarda en la variable global del programa principal try {/* ww w. j a v a 2s . co m*/ //iteracion n - 1 // Create a new empty document PDDocument document_to = new PDDocument(); //aadir la primera pagina PDPage page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(0); document_to.addPage(page_from); //obtener datos de la primera pagina String programa = get_text_by_area(programa_area, page_from, 1); String id = get_text_by_area(id_area, page_from, 0); String periodo = get_text_by_area(periodo_area, page_from, 2); String nombre = get_text_by_area(nombre_area, page_from, 0); String path = ""; String id_to_name; File folder; //si solo hay una pagina. if (numberOfPages == 1) { //document_to.save(type+"_"+programa+"_"+id+"_.pdf"); } //TODO: verificar que ninguno es vacio //iteracion n, se comprara n con n-1 //desde la segunda pagina verificar si el id es el mismo y terminar cuando cambie for (int i = 1; i < numberOfPages; i++) { page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(i); String id_next = get_text_by_area(id_area, page_from, i); //verificar si es hoja vacia //verificar que id_next sea igual que id if (id_next.equals(id)) { //si es igual al anterior aadir la pagina al documento document_to.addPage(page_from); } else { //momento para crear un hash, que relacione id con nombre, //con el fin de referenciar por id y no por nombre. set_id_name_hash(id, nombre); //actualizar relacion id => nombre // Save the newly created document //obtener nombre del id en cuestion: id_to_name = this.local_id_to_name.get(id); //verificar si esta disponible la informacion sobre la division if (this.has_division) { String division = this.local_programa_to_division.get(programa); // path = this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+periodo+"\\"+programa+"\\"+id_to_name; path = this.root + "RES_" + periodo + "\\" + division + "\\" + programa + "\\" + id_to_name; } else { // path = this.root+"Resultados_"+this.current_time + "\\" +programa+"\\"+periodo+"\\"+id_to_name; path = this.root + "RES_" + periodo + "\\" + programa + "\\" + id_to_name; } //create directory if not exist: folder = new File(path); if (!folder.exists()) { folder.mkdirs(); } document_to.save(path + "\\" + type + ".pdf"); //Preparacion para la siguiente iteracion //crear un nuevo documento document_to = new PDDocument(); //aadir la pagina encontrada que es diferente a la anterior page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(i); document_to.addPage(page_from); //obtener datos de la pagina id = get_text_by_area(id_area, page_from, i); while (id == null) { i++; page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(i); } id = get_text_by_area(id_area, page_from, i); programa = get_text_by_area(programa_area, page_from, i); periodo = get_text_by_area(periodo_area, page_from, i); nombre = get_text_by_area(nombre_area, page_from, i); set_id_name_hash(id, nombre); } //aadir el profesor de la ultima pagina } //:::::::ultima iteracion::::: //momento para crear un hash, que relacione id con nombre, //con el fin de referenciar por id y no por nombre. id_to_name = this.local_id_to_name.get(id); if (this.has_division) { String division = this.local_programa_to_division.get(programa); // path = this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+periodo+"\\"+programa+"\\"+id_to_name; path = this.root + "RES_" + periodo + "\\" + division + "\\" + programa + "\\" + id_to_name; } else { // path = this.root+"Resultados_"+this.current_time + "\\" +programa+"\\"+periodo+"\\"+id_to_name; path = this.root + "RES_" + periodo + "\\" + programa + "\\" + id_to_name; } folder = new File(path); //obtener nombre del id en cuestion: if (!folder.exists()) { folder.mkdirs(); } document_to.save(path + "\\" + type + ".pdf"); } catch (IOException ex) { Logger.getLogger(pdfsplitter.class.getName()).log(Level.SEVERE, null, ex); } catch (COSVisitorException ex) { Logger.getLogger(pdfsplitter.class.getName()).log(Level.SEVERE, null, ex); } //get periodo //get programa }
From source file:evadoc_splitter.pdfsplitter.java
private void split_report_consolidado_division(Rectangle2D region_div, Rectangle2D region_periodo, Rectangle2D region_programa, String type, int numberOfPages) { // pages = this.doc //crear hash id=>nombre que se guarda en la variable global del programa principal Rectangle2D next_region_programa = region_programa; try {/* w w w . java 2 s. c o m*/ //iteracion n - 1 // Create a new empty document PDDocument document_to = new PDDocument(); //aadir la primera pagina PDPage page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(0); document_to.addPage(page_from); //obtener datos de la primera pagina String division = get_text_by_area(region_div, page_from, 1); String periodo = get_text_by_area(region_periodo, page_from, 2); hash_programs(region_programa, page_from, division); //si solo hay una pagina. if (numberOfPages == 1) { //document_to.save(type+"_"+programa+"_"+id+"_.pdf"); } //TODO: verificar que ninguno es vacio //iteracion n, se comprara n con n-1 //desde la segunda pagina verificar si division es vacio o diferente y terminar cuando cambie for (int i = 1; i < numberOfPages; i++) { page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(i); String division_next = get_text_by_area(region_div, page_from, i); //verificar que div_next sea igual que div, o vacio, por que la hoja vacia hace parte de div if (division_next.equals(division) || division_next.equals("")) { //si es igual al anterior aadir la pagina al documento document_to.addPage(page_from); //obtener programas de las siguientes hojasn if (!division_next.equals("")) { //si es la hoja vacia no buscar programas. hash_programs(region_programa, page_from, division); } } else { //crear una estructura de resultados, division, periodo consolidado div. //File folder = new File(this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+"\\"+periodo+"\\"); File folder = new File("RES_" + periodo + "\\" + division + "\\"); if (!folder.exists()) { folder.mkdirs(); } // document_to.save(this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+"\\"+periodo+"\\"+type+".pdf"); document_to.save("RES_" + periodo + "\\" + division + "\\" + type + ".pdf"); //Preparacion para la siguiente iteracion //crear un nuevo documento document_to = new PDDocument(); //aadir la pagina encontrada que es diferente a la anterior page_from = (PDPage) this.document.getDocumentCatalog().getAllPages().get(i); document_to.addPage(page_from); //obtener datos de la pagina division = get_text_by_area(region_div, page_from, i); periodo = get_text_by_area(region_periodo, page_from, i); hash_programs(region_programa, page_from, division); } } //ultima iteracion //create directory if not exist: // File folder = new File(this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+periodo+"\\"); File folder = new File("RES_" + periodo + "\\" + division + "\\"); if (!folder.exists()) { folder.mkdirs(); } // document_to.save(this.root+"Resultados_"+this.current_time + "\\" +division+"\\"+periodo+"\\"+"\\"+type+".pdf"); document_to.save("RES_" + periodo + "\\" + division + "\\" + type + ".pdf"); } catch (IOException ex) { Logger.getLogger(pdfsplitter.class.getName()).log(Level.SEVERE, null, ex); } catch (COSVisitorException ex) { Logger.getLogger(pdfsplitter.class.getName()).log(Level.SEVERE, null, ex); } //get periodo //get programa }
From source file:fi.nls.oskari.printout.printing.pdfbox.UsingTextMatrix.java
License:Apache License
/** * creates a sample document with some text using a text matrix. * /* w ww. j a v a 2 s .c om*/ * @param message * The message to write in the file. * @param outfile * The resulting PDF. * * @throws IOException * If there is an error writing the data. * @throws COSVisitorException * If there is an error writing the PDF. */ public void doIt(String message, String outfile) throws IOException, COSVisitorException { // the document PDDocument doc = null; try { doc = new PDDocument(); // Page 1 PDFont font = PDType1Font.HELVETICA; PDPage page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); float fontSize = 12.0f; PDRectangle pageSize = page.findMediaBox(); System.err.println("pageSize " + pageSize); System.err.println( "pageSize cm " + pageSize.getWidth() / 72 * 2.54 + "," + pageSize.getHeight() / 72 * 2.54); float centeredXPosition = (pageSize.getWidth() - fontSize / 1000f) / 2f; float stringWidth = font.getStringWidth(message); float centeredYPosition = (pageSize.getHeight() - (stringWidth * fontSize) / 1000f) / 3f; PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); // counterclockwise rotation for (int i = 0; i < 8; i++) { contentStream.setTextRotation(i * Math.PI * 0.25, centeredXPosition, pageSize.getHeight() - centeredYPosition); contentStream.drawString(message + " " + i); } // clockwise rotation for (int i = 0; i < 8; i++) { contentStream.setTextRotation(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition); contentStream.drawString(message + " " + i); } contentStream.endText(); contentStream.close(); // Page 2 page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); // text scaling for (int i = 0; i < 10; i++) { contentStream.setTextScaling(12 + (i * 6), 12 + (i * 6), 100, 100 + i * 50); contentStream.drawString(message + " " + i); } contentStream.endText(); contentStream.close(); // Page 3 page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); int i = 0; // text scaling combined with rotation contentStream.setTextMatrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.setTextMatrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.setTextMatrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.setTextMatrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.endText(); contentStream.close(); // Page 4 { page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); AffineTransform root = new AffineTransform(); root.scale(72.0 / 2.54, 72.0 / 2.54); for (i = 0; i < pageSize.getHeight() / 72 * 2.54; i++) { // text scaling combined with rotation { AffineTransform rowMatrix = new AffineTransform(root); rowMatrix.translate(1, i); contentStream.setTextMatrix(rowMatrix); contentStream.drawString(message + " " + i); } } contentStream.endText(); contentStream.close(); } doc.save(outfile); } finally { if (doc != null) { doc.close(); } } }