List of usage examples for org.apache.pdfbox.pdmodel PDDocument close
@Override public void close() throws IOException
From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java
License:Apache License
@Override public Pair<FormJSON, List<WorkflowOutputFormField>> getOutputFormFields(final String filename, final byte[] data) throws IOException { List<WorkflowOutputFormField> wofields = new ArrayList<>(); PDDocument doc = loadPDF(data); try {//from w w w .ja v a 2 s.c o m Map<COSDictionary, Integer> obMap = getCOSDictionaryToPageNumberMap(doc); Map<Integer, List<PDField>> pdMap = getPDFields(doc, obMap); Map<Integer, List<PdfTextField>> textsMap = getTextMap(doc); PDPageTree pages = doc.getDocumentCatalog().getPages(); FormJSON form = buildFormJSON(doc, textsMap.get(Integer.valueOf(0))); for (int i = 0; i < pages.getCount(); i++) { PDPage page = pages.get(i); Integer pageNum = Integer.valueOf(i); List<PDField> fields = pdMap.getOrDefault(pageNum, emptyList()); List<PdfTextField> texts = getTextForPage(textsMap, pageNum); List<PDRectangle> lineRects = getPageLinePaths(pages.get(i)); Map<PDField, FormJSONField> fieldMap = buildFormSection(form, page, fields, texts, lineRects); List<WorkflowOutputFormField> outfields = createFieldOutputs(form, fields, fieldMap); wofields.addAll(outfields); } return Pair.of(form, wofields); } finally { doc.close(); } }
From source file:com.formkiq.web.WorkflowAddControllerIntegrationTest.java
License:Apache License
/** * testCreateWorkflow11()./* w w w. j ava 2 s . com*/ * fillout and generate and sign fillable PDF * @throws Exception Exception */ @Test public void testCreateWorkflow11() throws Exception { // given String pdfname = "sample-form2.pdf"; byte[] data = Resources.getResourceAsBytes("/" + pdfname); ArchiveDTO archive = buildArchiveDTO(pdfname); this.pdfEditorService.generate(archive, pdfname, data); String token = login(); String folder = createFolder(token, getDefaultEmail()); addFileToFolder(token, folder, archive); // when login(getDefaultEmail()); getDriver().navigate().to(getDefaultHostAndPort() + "/user/dashboard"); waitForJSandJQueryToLoad(); assertEquals("FormKiQ Server - Dashboard", getTitle()); findElementBy(By.className("add_0")).click(); // then (verify on correct page) assertEquals(getDefaultHostAndPort() + "/flow/workflow?execution=s1e1", getDriver().getCurrentUrl()); assertEquals(SAMPLE_FORM_2_HTML_TITLE, getTitle()); fillSampleForm2(); // when (submit) submitByName("_eventId_next", "Next"); // then verify summary assertEquals(getDefaultHostAndPort() + "/flow/workflow?execution=s1e2", getDriver().getCurrentUrl()); assertEquals("FormKiQ Server - Signature", getTitle()); assertEquals(1, findElements(getBy("button", "data-fieldid", "55")).size()); assertEquals(0, getDriver().findElements(getBy("img", "data-fieldid", "55")).size()); // when (go back submitByName("_eventId_prev", "Previous"); // then assertEquals(getDefaultHostAndPort() + "/flow/workflow?execution=s1e1", getDriver().getCurrentUrl()); assertEquals(SAMPLE_FORM_2_HTML_TITLE, getTitle()); // when findElementBy(By.name("1")).sendKeys("Smith123"); submitByName("_eventId_next", "Next"); // then assertEquals(getDefaultHostAndPort() + "/flow/workflow?execution=s1e2", getDriver().getCurrentUrl()); assertEquals("FormKiQ Server - Signature", getTitle()); // when (signature) click(By.className("button-sig")); JavascriptExecutor jsExecutor = (JavascriptExecutor) getDriver(); jsExecutor.executeScript("signaturemetadata('555','999');"); // then getWait().until(ExpectedConditions.visibilityOfElementLocated(By.id("form-modal"))); // when click(By.className("form-modal-close-button")); // then getWait().until(ExpectedConditions.invisibilityOfElementLocated(By.id("form-modal"))); // when (signature) click(By.className("button-sig")); // then fillSignature("55"); // when click(By.className("form-modal-update-button")); // then getWait().until(ExpectedConditions.invisibilityOfElementLocated(By.id("form-modal"))); assertEquals(0, getDriver().findElements(getBy("button", "data-fieldid", "55")).size()); assertEquals(1, findElements(getBy("img", "data-fieldid", "55")).size()); // when submitByName("_eventId_next", " Submit", TIMEOUT * 2); // then complete page assertEquals(getDefaultHostAndPort() + "/flow/workflow?execution=s1e3", getDriver().getCurrentUrl()); assertEquals("FormKiQ Server - sample-form2.pdf Complete", getTitle()); Workflow workflow = archive.getWorkflow(); Pair<Workflow, Map<String, byte[]>> pwf = verifyFolderFileList(token, folder, workflow, "ACTIVE", "sample-form2.pdf"); workflow = pwf.getLeft(); Map<String, byte[]> map = pwf.getRight(); assertEquals(getDefaultHostAndPort() + "/api/folders/files/" + folder + "/" + workflow.getUUID() + ".pdf", findElementBy(By.id("pdflink")).getAttribute("href")); assertEquals(SAMPLE_FORM2 + ".pdf", map.keySet().stream().filter(s -> s.endsWith(".pdf")).collect(Collectors.joining(", "))); assertEquals(1, map.keySet().stream().filter(s -> s.endsWith(".pdf")).count()); assertEquals(1, map.keySet().stream().filter(s -> s.endsWith(".signature")).count()); FormJSON f1 = this.jsonService.readValue(map.get(workflow.getSteps().get(1) + ".form"), FormJSON.class); assertTrue(f1.getAssetData().containsKey(f1.getSections().get(0).getFields().get(0).getValue())); assertEquals("555", findValueByKey(f1, "latitude").get().getValue()); assertEquals("999", findValueByKey(f1, "longitude").get().getValue()); assertEquals("0:0:0:0:0:0:0:1", findValueByKey(f1, "ipaddress").get().getValue()); assertEquals("", findValueByKey(f1, "xforwardedfor").get().getValue()); assertNotNull(this.jsonService.stringToDate(findValueByKey(f1, "inserteddate").get().getValue())); byte[] pdf = map.get(SAMPLE_FORM2 + ".pdf"); PDDocument document = PDDocument.load(pdf); try { PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); assertEquals("SmithSmith123", acroForm.getField("lastName").getValueAsString()); assertEquals("John", acroForm.getField("firstName").getValueAsString()); assertEquals(1, document.getSignatureDictionaries().size()); } finally { document.close(); } // TODO verify audit }
From source file:com.github.joemcintyre.pdffinish.PDFFinish.java
License:Open Source License
/** * Process the PDF input file, producing the output file. * /*from w w w.ja v a 2 s .c om*/ * @param fileInput PDF input file. * @param fileOutput PDF output file. */ private void processPDF(File fileInput, File fileOutput) { PDDocument document = null; try { document = PDDocument.load(fileInput); } catch (IOException e) { System.out.println("Error reading PDF: " + e); } if (document != null) { boolean save = true; try { updateMetadata(document); if (fontList != null) { updateTOC(document); } } catch (IOException e) { System.out.println("Error processing PDF: " + e); save = false; } if (save) { try { document.save(fileOutput); System.out.println("Write complete"); } catch (Exception e) { System.out.println("Error writing PDF: " + e); } } try { document.close(); } catch (Exception e) { System.out.println("Error closing document: " + e); } } }
From source file:com.helger.pdflayout.PageLayoutPDF.java
License:Apache License
/** * Render this layout to an OutputStream. * * @param aCustomizer/*w ww . j av a 2s.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:com.hostandguest.services.FXML_BookingListController.java
private boolean saveToPDF(Booking booking) { try {// w w w.j ava 2 s . co m // get the user to provide save directory DirectoryChooser directoryChooser = new DirectoryChooser(); directoryChooser.setTitle("Choose Save Location"); File selectedDir = directoryChooser.showDialog(new Stage()); String fileName = booking.getGuest().getLast_name() + " " + booking.getGuest().getFirst_name() + " " + booking.getBookingDate().toString() + ".pdf"; PDDocument doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream content = new PDPageContentStream(doc, page); // setting content content.beginText(); content.setFont(PDType1Font.HELVETICA, 26); content.newLineAtOffset(220, 750); content.showText("Reservation Form"); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.newLineAtOffset(80, 700); content.showText("Name : "); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 14); content.newLineAtOffset(250, 700); content.showText(booking.getGuest().getLast_name() + " " + booking.getGuest().getFirst_name()); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.newLineAtOffset(80, 650); content.showText("Reservation Date : "); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 14); content.newLineAtOffset(250, 650); content.showText(booking.getBookingDate().toString()); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.newLineAtOffset(80, 600); content.showText("Term : "); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 14); content.newLineAtOffset(250, 600); content.showText(String.valueOf(booking.getTerm())); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.newLineAtOffset(80, 550); content.showText("Number of Rooms : "); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 14); content.newLineAtOffset(250, 550); content.showText(String.valueOf(booking.getNbr_rooms_reserved())); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 16); content.newLineAtOffset(80, 500); content.showText("Total Amount : "); content.endText(); content.beginText(); content.setFont(PDType1Font.HELVETICA, 14); content.newLineAtOffset(250, 500); content.showText(String.valueOf(booking.getTotal_amount())); content.endText(); // content.close(); doc.save(selectedDir.getAbsolutePath() + "\\" + fileName); doc.close(); return true; } catch (IOException ex) { Logger.getLogger(FXML_BookingListController.class.getName()).log(Level.SEVERE, null, ex); } return false; }
From source file:com.itdhq.poc.ocrsign.CreateVisibleSignature.java
License:Apache License
/** * Sign pdf file and create new file that ends with "_signed.pdf". * * @param inputFile The source pdf document file. * @param signedFile The file to be signed. * @throws IOException/*w w w . j av a 2s . com*/ */ public void signPDF(File inputFile, File signedFile) throws IOException { if (inputFile == null || !inputFile.exists()) { throw new IOException("Document for signing does not exist"); } // creating output document and prepare the IO streams. FileOutputStream fos = new FileOutputStream(signedFile); // load document PDDocument doc = PDDocument.load(inputFile); // create signature dictionary PDSignature signature = new PDSignature(); signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); // default filter // subfilter for basic and PAdES Part 2 signatures signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED); signature.setName("signer name"); signature.setLocation("signer location"); signature.setReason("reason for signature"); // the signing date, needed for valid signature signature.setSignDate(Calendar.getInstance()); // register signature dictionary and sign interface if (visibleSignatureProperties != null && visibleSignatureProperties.isVisualSignEnabled()) { options = new SignatureOptions(); options.setVisualSignature(visibleSignatureProperties); options.setPage(visibleSignatureProperties.getPage() - 1); // FIXME //doc.addSignature(signature, this, options); } else { // FIXME //doc.addSignature(signature, this); } // write incremental (only for signing purpose) // FIXME //doc.saveIncremental(fos); doc.close(); // do not close options before saving, because some COSStream objects within options // are transferred to the signed document. // FIXME //IOUtils.closeQuietly(options); }
From source file:com.itdhq.poc.ocrsign.ShowSignature.java
License:Apache License
private void showSignature(String[] args) throws IOException, CertificateException { if (args.length != 2) { usage();/* w w w . j ava2 s. com*/ } else { String password = args[0]; String infile = args[1]; PDDocument document = null; try { document = PDDocument.load(new File(infile)); if (!document.isEncrypted()) { System.err.println("Warning: Document is not encrypted."); } COSDictionary trailer = document.getDocument().getTrailer(); COSDictionary root = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT); COSDictionary acroForm = (COSDictionary) root.getDictionaryObject(COSName.ACRO_FORM); COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS); for (int i = 0; i < fields.size(); i++) { COSDictionary field = (COSDictionary) fields.getObject(i); // FIXME /* COSName type = field.getCOSName( COSName.FT ); if( COSName.SIG.equals( type ) ) { COSDictionary cert = (COSDictionary)field.getDictionaryObject( COSName.V ); if( cert != null ) { System.out.println( "Certificate found" ); System.out.println( "Name=" + cert.getDictionaryObject( COSName.NAME ) ); System.out.println( "Modified=" + cert.getDictionaryObject( COSName.M ) ); COSName subFilter = (COSName)cert.getDictionaryObject( COSName.SUB_FILTER ); if( subFilter != null ) { if( subFilter.getName().equals( "adbe.x509.rsa_sha1" ) ) { COSString certString = (COSString)cert.getDictionaryObject( COSName.getPDFName( "Cert" ) ); byte[] certData = certString.getBytes(); CertificateFactory factory = CertificateFactory.getInstance( "X.509" ); ByteArrayInputStream certStream = new ByteArrayInputStream( certData ); Collection<? extends Certificate> certs = factory.generateCertificates( certStream ); System.out.println( "certs=" + certs ); } else if( subFilter.getName().equals( "adbe.pkcs7.sha1" ) ) { COSString certString = (COSString)cert.getDictionaryObject( COSName.CONTENTS ); byte[] certData = certString.getBytes(); CertificateFactory factory = CertificateFactory.getInstance( "X.509" ); ByteArrayInputStream certStream = new ByteArrayInputStream( certData ); Collection<? extends Certificate> certs = factory.generateCertificates( certStream ); System.out.println( "certs=" + certs ); } else { System.err.println( "Unknown certificate type:" + subFilter ); } } else { throw new IOException( "Missing subfilter for cert dictionary" ); } } else { System.out.println( "Signature found, but no certificate" ); } } */ } } finally { if (document != null) { document.close(); } } } }
From source file:com.iwinner.app.pdf.DbProject.java
/** * @param args/*from w w w . j a v a2 s . c om*/ * the command line arguments */ public static void main(String[] args) { // TODO code application logic here PDDocument pd; ArrayList<Student> database = new ArrayList<Student>(); try { File input = new File("E:\\Tech_Learn\\ImpApplications_Source\\student-InfoSystem-master\\fe2012.pdf"); pd = PDDocument.load(input); PDFTextStripper stripper = new PDFTextStripper(); StringBuilder sb = new StringBuilder(); stripper.setStartPage(1); stripper.setEndPage(4); sb.append(stripper.getText(pd)); Pattern p = Pattern.compile("(\\w)(\\d{9})(.*?)((\\d+)/(\\d{4}))", Pattern.DOTALL); Matcher m = p.matcher(sb); while (m.find()) { //System.out.println(m.group()); //System.out.println("\n----\n"); Student s = new Student(); String student_block, tmp_name; student_block = m.group(); // Regex for roll number Pattern p2 = Pattern.compile("\\w\\d{9}", Pattern.DOTALL); Matcher m2 = p2.matcher(student_block); m2.find(); s.roll = m2.group().trim(); //System.out.println(s.roll); // Regex for finding name p2 = Pattern.compile("\\s{3}(.*?)\\s{2}", Pattern.DOTALL); m2 = p2.matcher(student_block); m2.find(); tmp_name = m2.group(); // Strip leading and trailing whitespace s.name = tmp_name.trim(); // Regex for iterating over individual subjects p2 = Pattern.compile("\\d{6}\\s\\w(.*?)\\s[P|F]\\s", Pattern.DOTALL); m2 = p2.matcher(student_block); while (m2.find()) { String tmp; tmp = m2.group().trim(); //System.out.println(tmp); // Get subject name Pattern p3 = Pattern.compile("[A-Z](.*?)(PP|PR|TW)\\s{2}"); Matcher m3 = p3.matcher(tmp); m3.find(); String sub_name = m3.group().trim(); //System.out.println("---" + sub_name); // Remove PP/PR/TW from sub_name StringBuilder sb_tmp; sb_tmp = new StringBuilder(sub_name); sb_tmp.deleteCharAt(sub_name.length() - 1); sb_tmp.deleteCharAt(sub_name.length() - 2); sub_name = sb_tmp.toString().trim(); // Final subject name //System.out.println("---" + sub_name); s.subjects.add(sub_name); } // Add to student db database.add(s); //System.out.println("\n-------\n"); } for (Student s : database) { System.out.println("Name : " + s.name + "\n" + s.roll); for (Iterator it = s.subjects.iterator(); it.hasNext();) { Object a = it.next(); System.out.println("--> " + a); } System.out.println("\n"); } pd.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.jgaap.generics.DocumentHelper.java
License:Open Source License
/** * Extracts text from a PDF and stores it in the document. Takes an input * stream rather than a file name.//from w w w . jav a 2 s . c o m * * @param filesInputStream * An input stream pointing to a PDF file. * @throws IOException */ static private char[] loadPDF(InputStream filesInputStream) throws IOException { PDDocument doc; doc = PDDocument.load(filesInputStream); PDFTextStripper pdfStripper = new PDFTextStripper(); pdfStripper.setSortByPosition(false); char[] origText = pdfStripper.getText(doc).toCharArray(); doc.close(); return origText; }
From source file:com.jnd.sonar.analysisreport.AnalysisReportHelper.java
License:Open Source License
/** * create the second sample document from the PDF file format specification. * @param reportDataMap //w w w . ja v a2 s . c o m * * @param file The file to write the PDF to. * @param message The message to write in the file. * * @throws IOException If there is an error writing the data. * @throws COSVisitorException If there is an error writing the PDF. */ public String createMetricReport(Map<String, String> reportDataMap) throws IOException, COSVisitorException { // the document PDDocument doc = null; StringBuilder strRow = new StringBuilder(); String reportname = null; java.util.Random R = new java.util.Random(); try { doc = new PDDocument(); System.out.println("Creating PDF Line 264"); PDPage page = new PDPage(); doc.addPage(page); PDFont font = PDType1Font.HELVETICA_BOLD; PDPageContentStream contentStream = new PDPageContentStream(doc, page); contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 700 - 0); contentStream.drawString(" Sonar Analysis Report "); contentStream.endText(); contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 700 - 20); contentStream.drawString("==================================================== "); contentStream.endText(); System.out.println("Print Entries from Analysis Data Map."); int i = 2; for (Map.Entry<String, String> entry : reportDataMap.entrySet()) { contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 700 - (i * 20)); contentStream.drawString(i + ") " + entry.getKey() + " = " + entry.getValue()); contentStream.endText(); //strRow.append(i + ") " + entry.getKey() + " = " + entry.getValue() + "\n "); i++; } //System.out.println(strRow); contentStream.close(); System.out.println("Done Writing Text.Save Doc."); reportname = "sonarreport" + java.util.Calendar.getInstance().getTimeInMillis() + "_" + R.nextInt() + ".pdf"; doc.save(reportname); System.out.println("Report Created.Exit to email sending. name=>" + reportname); } finally { if (doc != null) { doc.close(); } } return reportname; }