List of usage examples for org.apache.pdfbox.pdmodel.interactive.form PDAcroForm getField
public PDField getField(String fullyQualifiedName)
From source file:FormFiller.java
private static void fillPdf(HashMap dealerTrackData, String inputFileName, String outputDir, String outputFormType) {// w ww.j ava 2 s . c o m try { PDDocument pdfTemplate = PDDocument.load(new File(inputFileName)); PDDocumentCatalog docCatalog = pdfTemplate.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); List<PDField> fieldList = acroForm.getFields(); String[] fieldArray = new String[fieldList.size()]; int i = 0; for (PDField sField : fieldList) { fieldArray[i] = sField.getFullyQualifiedName(); i++; } for (String f : fieldArray) { PDField field = acroForm.getField(f); String value = (String) dealerTrackData.get(f); if (value != null) { try { field.setValue(value); } catch (IllegalArgumentException e) { System.err.println("Could not insert: " + f + "."); } } } pdfTemplate.save(outputDir + "/" + dealerTrackData.get("fullName") + " " + outputFormType + ".pdf"); // printing - need to look into the long form stuff! if (print && !inputFileName.contains("Title Guarantee")) printPdf(pdfTemplate, dealerTrackData, inputFileName, inputFileName.contains("Purchase Contract") ? 2 : 1); pdfTemplate.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:SetField.java
License:Apache License
/** * This will set a single field in the document. * * @param pdfDocument The PDF to set the field in. * @param name The name of the field to set. * @param value The new value of the field. * * @throws IOException If there is an error setting the field. *///from ww w . j av a 2s .c om public void setField(PDDocument pdfDocument, String[] args) throws IOException { PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); for (int i = 0; i < args.length - 1; i = i + 2) { PDField field = acroForm.getField(args[i]); if (field != null) { field.setValue(args[i + 1]); } else { System.err.println("No field found with name:" + args[i]); } } }
From source file:ch.vaudoise.vaapi.dctm.resource.root.LoadAndSetPDF.java
public static void setPDF(String nom, String prenom, String adresse, String telephone, String commentaire, String description) throws IOException { String adressePart1 = null;/*from www . j a va 2 s . c o m*/ String adressePart2 = null; String[] adresseTab = adressParser(adresse); if (adresseTab.length > 0) { adressePart1 = (adresseTab[0] + " " + adresseTab[1]); adressePart2 = (adresseTab[2] + " " + adresseTab[3]); } //Loading an existing document File file = new File("C:\\Temp\\declaration.pdf"); try (PDDocument document = PDDocument.load(file)) { PDDocumentCatalog docCatalog = document.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); // Get field names List<PDField> fieldList = acroForm.getFields(); // String the object array String[] fieldArray = new String[fieldList.size()]; int i = 0; for (PDField sField : fieldList) { fieldArray[i] = sField.getFullyQualifiedName(); i++; } // Loop through each field in the array and fill the blanks for (String f : fieldArray) { PDField field = acroForm.getField(f); // System.out.println(f); switch (f) { case "Nom prnom ou raison sociale": { if (nom != null && nom != null) { field.setValue(nom + " " + prenom); break; } else { field.setValue("Faten"); break; } } case "Adresse": { if (adressePart1 != null) { field.setValue(adressePart1); break; } else { field.setValue("Rue des moulins 12"); break; } } case "NPA et localit": { if (adressePart2 != null) { field.setValue(adressePart2); break; } else { field.setValue("1006 lausanne"); break; } } case "Tlphone et et fax": { if (telephone != null) { field.setValue(telephone); break; } else { field.setValue(""); break; } } case "Email": { field.setValue(""); break; } case "Nom de la personne de contact": { field.setValue(nom + " " + prenom); break; } case "CCP ou compte bancaire": { field.setValue(""); break; } case "Si oui N TVA": { field.setValue(""); break; } case "Si oui compagnie": { field.setValue(""); break; } case "Numro de contrat dassurance ex1234562200": { field.setValue("1234564100"); break; } case "Remarques": { if (commentaire != null) { field.setValue(commentaire); break; } else { field.setValue("Rien signaler ..."); break; } } case "Description de": { if (description != null) { field.setValue(description); break; } else { field.setValue("Rien signaler ..."); break; } } } } //Saving the document document.save("C:/temp/declarationRemplie.pdf"); //Closing the document document.close(); } }
From source file:com.fangxin365.core.utils.PDFMerger.java
License:Apache License
/** * Merge the contents of the source form into the destination form for the * destination file.//from w ww .j ava2s. com * * @param cloner * the object cloner for the destination document * @param destAcroForm * the destination form * @param srcAcroForm * the source form * @throws IOException * If an error occurs while adding the field. */ @SuppressWarnings({ "rawtypes", "unchecked" }) private void mergeAcroForm(PDFCloneUtility cloner, PDAcroForm destAcroForm, PDAcroForm srcAcroForm) throws IOException { List destFields = destAcroForm.getFields(); List srcFields = srcAcroForm.getFields(); if (srcFields != null) { if (destFields == null) { destFields = new COSArrayList(); destAcroForm.setFields(destFields); } Iterator srcFieldsIterator = srcFields.iterator(); while (srcFieldsIterator.hasNext()) { PDField srcField = (PDField) srcFieldsIterator.next(); PDField destField = PDFieldFactory.createField(destAcroForm, (COSDictionary) cloner.cloneForNewDocument(srcField.getDictionary())); // if the form already has a field with this name then we need // to rename this field // to prevent merge conflicts. if (destAcroForm.getField(destField.getFullyQualifiedName()) != null) { destField.setPartialName("dummyFieldName" + (nextFieldNum++)); } destFields.add(destField); } } }
From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java
License:Apache License
/** * Do Partial PDF Save. This save works when updating Signature fields. * @param docBytes byte[]/*from w w w. ja va 2 s.co m*/ * @param archive {@link ArchiveDTO} * @param output {@link WorkflowOutputPdfForm} * @throws IOException IOException */ private void doSignaturePdfSave(final byte[] docBytes, final ArchiveDTO archive, final WorkflowOutputPdfForm output) throws IOException { boolean signed = false; List<SignatureOptions> signatureOptions = new ArrayList<>(); PDDocument doc = loadPDF(docBytes); try { PDDocumentCatalog docCatalog = doc.getDocumentCatalog(); PDAcroForm pdform = docCatalog.getAcroForm(); for (WorkflowOutputFormField ofield : output.getFields()) { Optional<FormJSON> form = findForm(archive, ofield); Optional<FormJSONField> field = findFormField(form, ofield); if (form.isPresent() && field.isPresent()) { String value = field.get().getValue(); PDField pfield = pdform.getField(ofield.getDocumentfieldname()); if (pfield != null && pfield instanceof PDSignatureField) { byte[] bs = form.get().getAssetData().get(value); if (bs != null) { try { InputStream is = new ByteArrayInputStream(bs); signatureOptions.add(setValue(doc, (PDSignatureField) pfield, is)); signed = true; } catch (IllegalStateException e) { LOG.log(Level.WARNING, "unable to set signature", e); } } } } } if (signed) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); doc.saveIncremental(bs); bs.close(); String pdfname = output.getName(); archive.addPDF(pdfname + ".pdf", bs.toByteArray()); } for (SignatureOptions sigOption : signatureOptions) { IOUtils.closeQuietly(sigOption); } } finally { doc.close(); } }
From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java
License:Apache License
/** * Do Full PDF Save. This save works when updating the values of fields. * @param docBytes byte[]/*from w w w.j av a 2s . c om*/ * @param archive {@link ArchiveDTO} * @param output {@link WorkflowOutputPdfForm} * @return boolean - whether signature fields are found * @throws IOException IOException */ private boolean dofullPDFSave(final byte[] docBytes, final ArchiveDTO archive, final WorkflowOutputPdfForm output) throws IOException { boolean hasSignatures = false; PDDocument doc = loadPDF(docBytes); try { PDDocumentCatalog docCatalog = doc.getDocumentCatalog(); PDAcroForm pdform = docCatalog.getAcroForm(); for (WorkflowOutputFormField ofield : output.getFields()) { Optional<FormJSON> form = findForm(archive, ofield); Optional<FormJSONField> field = findFormField(form, ofield); if (form.isPresent() && field.isPresent()) { PDField pdfield = pdform.getField(ofield.getDocumentfieldname()); if (pdfield != null) { if (pdfield instanceof PDSignatureField) { hasSignatures = true; } else { String value = field.get().getValue(); List<String> values = field.get().getValues(); if (!isEmpty(values)) { for (String val : values) { pdfield.setValue(extractLabelAndValue(val).getRight()); } } else if (!isEmpty(value)) { value = extractLabelAndValue(value).getRight(); pdfield.setValue(value); } } } } } ByteArrayOutputStream bs = new ByteArrayOutputStream(); doc.save(bs); bs.close(); String pdfname = output.getName(); archive.addPDF(pdfname + ".pdf", bs.toByteArray()); return hasSignatures; } finally { doc.close(); } }
From source file:com.formkiq.web.WorkflowAddControllerIntegrationTest.java
License:Apache License
/** * testCreateWorkflow11()./* www . j a va 2 s . c o m*/ * 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:cr.ac.siua.tec.utils.impl.AssistancePDFGenerator.java
License:Open Source License
/** * Fills the PDF file (asistente.pdf) with the ticket values and returns base64 encoded string. *//*from www. j a va 2 s. c om*/ @Override public String generate(HashMap<String, String> formValues) { String originalPdf = PDFGenerator.RESOURCES_PATH + "asistente.pdf"; try { PDDocument _pdfDocument = PDDocument.load(originalPdf); PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); //Set some fields manually. Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; if (month > 10 || month < 5) acroForm.getField("Semestre").setValue("PRIMER"); else acroForm.getField("Semestre").setValue("SEGUNDO"); if (month > 10 && acroForm.getField("Semestre").getValue().equals("PRIMER")) year++; acroForm.getField("Ao").setValue(String.valueOf(year)); formValues.remove("Queue"); acroForm.getField(formValues.get("Banco")).setValue("x"); formValues.remove("Banco"); acroForm.getField(formValues.get("Tipo de asistencia")).setValue("x"); formValues.remove("Tipo de asistencia"); //Iterates through remaining custom fields. for (Map.Entry<String, String> entry : formValues.entrySet()) { acroForm.getField(entry.getKey()).setValue(entry.getValue()); } return encodePDF(_pdfDocument); } catch (IOException e) { e.printStackTrace(); System.out.println("Excepcin al llenar el PDF."); return null; } }
From source file:cr.ac.siua.tec.utils.impl.CEInclusionPDFGenerator.java
License:Open Source License
/** * Fills the PDF file (inclusion.pdf) with the ticket values and returns base64 encoded string. *///from ww w. j a va 2 s.c o m @Override public String generate(HashMap<String, String> formValues) { String originalPdf = PDFGenerator.RESOURCES_PATH + "inclusion.pdf"; try { PDDocument _pdfDocument = PDDocument.load(originalPdf); PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); formValues.remove("Queue"); formValues.remove("Justificacin"); //Set some fields manually. Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; if (month > 10 || month < 5) acroForm.getField("Semestre").setValue("I"); else acroForm.getField("Semestre").setValue("II"); if (month > 10 && acroForm.getField("Semestre").getValue().equals("I")) year++; acroForm.getField("Ao").setValue(String.valueOf(year)); //Fills enrolled courses table. String enrolledCourses[] = formValues.get("Cursos matriculados").split("\n"); for (int i = 0; i < enrolledCourses.length; i++) { String courseRow[] = enrolledCourses[i].split("-"); acroForm.getField("Cdigo" + Integer.toString(i)).setValue(courseRow[0]); acroForm.getField("Curso" + Integer.toString(i)).setValue(courseRow[1]); acroForm.getField("Grupo" + Integer.toString(i)).setValue(courseRow[2]); } formValues.remove("Cursos matriculados"); //Iterates through remaining custom fields. for (Map.Entry<String, String> entry : formValues.entrySet()) { acroForm.getField(entry.getKey()).setValue(entry.getValue()); } return encodePDF(_pdfDocument); } catch (IOException e) { e.printStackTrace(); System.out.println("Excepcin al llenar el PDF."); return null; } }
From source file:cr.ac.siua.tec.utils.impl.ConstancyPDFGenerator.java
License:Open Source License
/** * Fills the PDF file (constancia.pdf) with the ticket values and returns base64 encoded string. *//* w w w. j a va 2 s . co m*/ @Override public String generate(HashMap<String, String> formValues) { String originalPdf = PDFGenerator.RESOURCES_PATH + "constancia.pdf"; try { PDDocument _pdfDocument = PDDocument.load(originalPdf); PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); //Set some fields manually. Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DAY_OF_MONTH); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); String date = String.valueOf(day) + " de " + monthsMap.get(month) + " del ao " + String.valueOf(year) + "."; acroForm.getField("Fecha").setValue(date); formValues.remove("Queue"); formValues.remove("Motivo"); formValues.remove("Requestors"); //Iterates through remaining custom fields. for (Map.Entry<String, String> entry : formValues.entrySet()) { acroForm.getField(entry.getKey()).setValue(entry.getValue()); } return encodePDF(_pdfDocument); } catch (IOException e) { e.printStackTrace(); System.out.println("Excepcin al llenar el PDF."); return null; } }