org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm Java Examples
The following examples show how to use
org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FillAndFlatten.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/60964782/pdfbox-inconsistent-pdtextfield-behaviour-after-setvalue"> * PDFBox Inconsistent PDTextField Behaviour after setValue * </a> * </br/> * <a href="https://s3-us-west-2.amazonaws.com/kx-filing-docs/b3-3.pdf"> * b3-3.pdf * </a> * <p> * Indeed, PDFBox assumes in some fields that it should not create * field appearances which a formatting additional action would do * differently anyways in a viewer. In a flattening use case this is * obviously incorrect. * </p> * @see #testLikeAbubakarRemoveAction() */ @Test public void testLikeAbubakar() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("b3-3.pdf"); PDDocument pdDocument = Loader.loadPDF(resource) ) { PDDocumentCatalog catalog = pdDocument.getDocumentCatalog(); PDAcroForm acroForm = catalog.getAcroForm(); int i = 0; for (PDField field : acroForm.getFields()) { i=i+1; if (field instanceof PDTextField) { PDTextField textField = (PDTextField) field; textField.setValue(Integer.toString(i)); } } pdDocument.getDocumentCatalog().getAcroForm().flatten(); pdDocument.save(new File(RESULT_FOLDER, "b3-3-filled-and-flattened.pdf")); } }
Example #2
Source File: FillInForm.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/52059931/pdfbox-setvalue-for-multiple-pdtextfield"> * PDFBox setValue for multiple PDTextField * </a> * <br/> * <a href="https://ufile.io/z8jzj"> * testform.pdf * </a> * <p> * Cannot reproduce the issue. * </p> */ @Test public void testFillLikeJuvi() throws IOException { try ( InputStream originalStream = getClass().getResourceAsStream("testform.pdf") ) { PDDocument document = Loader.loadPDF(originalStream); PDDocumentCatalog docCatalog = document.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); PDTextField field = (PDTextField) acroForm.getField("Check1"); field.setValue("1111"); PDTextField field2 = (PDTextField) acroForm.getField("Check2"); field2.setValue("2222"); PDTextField field3 = (PDTextField) acroForm.getField("HelloWorld"); field3.setValue("HelloWorld"); document.save(new File(RESULT_FOLDER, "testform-filled.pdf")); document.close(); } }
Example #3
Source File: FillInForm.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/49048556/pdfbox-set-field-value-doesnt-work"> * PDFBox set field value doesn't work * </a> * <br/> * <a href="https://www.inps.it/Nuovoportaleinps/image.aspx?iIDModulo=7712&tipomodulo=1"> * SR16_ANF_DIP.pdf * </a> * <p> * Indeed, the form field in question is hidden. Thus, one has to un-hide it * to make it visible. * </p> */ @Test public void testFillLikeBarbara() throws IOException { try ( InputStream originalStream = getClass().getResourceAsStream("SR16_ANF_DIP.pdf") ) { PDDocument pdfDocument = Loader.loadPDF(originalStream); PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm(); if (acroForm != null) { PDTextField pdfField = (PDTextField) acroForm.getField("info_15a"); pdfField.getWidgets().get(0).setHidden(false);// <=== pdfField.setValue("xxxxxx"); } pdfDocument.setAllSecurityToBeRemoved(true); COSDictionary dictionary = pdfDocument.getDocumentCatalog().getCOSObject(); dictionary.removeItem(COSName.PERMS); pdfDocument.save(new File(RESULT_FOLDER, "SR16_ANF_DIP-filled.pdf")); pdfDocument.close(); } }
Example #4
Source File: FillInForm.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/54820224/why-is-pdfbox-overwriting-multiple-fields-even-when-they-dont-match-the-fullyq"> * Why is PDFBox overwriting multiple Fields, even when they don't match the fullyQualifiedName? (Kotlin Android) * </a> * <br/> * <a href="http://www.kylevp.com/csOnePage.pdf"> * csOnePage.pdf * </a> * <p> * The problem is due to some fields of the form sharing empty * appearance XObjects and PDFBox assuming in case of existing * appearance XObjects that it can simply update this existing * appearance instead of having to create a new one from scratch. * </p> * <p> * A work-around is to remove existing appearances from a field * before setting its value, see below. * </p> */ @Test public void testLikeKyle() throws IOException { try ( InputStream originalStream = getClass().getResourceAsStream("csOnePage.pdf") ) { PDDocument doc = Loader.loadPDF(originalStream); PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm(); List<String> skillList = Arrays.asList("Athletics","Acrobatics","Sleight of Hand", "Stealth","Acrana", "History","Investigation","Nature", "Religion", "Animal Handling", "Insight", "Medicine", "Perception", "Survival", "Deception", "Intimidation", "Performance", "Persuasion"); int temp = 0; for (String skill : skillList) { PDField field = acroForm.getField(skill); temp += 1; if (field == null) { System.err.printf("(%d) field '%s' is null.\n", temp, skill); } else { field.getCOSObject().removeItem(COSName.AP); field.setValue(String.valueOf(temp)); } } doc.save(new File(RESULT_FOLDER, "csOnePage-filled.pdf")); doc.close(); } }
Example #5
Source File: FillInForm.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/56938135/pdfbox-inconsistent-pdtextfield-autosize-behavior-after-setvalue"> * PDFBox Inconsistent PDTextField Autosize Behavior after setValue * </a> * <br/> * <a href="http://www.filedropper.com/0postfontload"> * 0.pdf * </a> * <p> * Indeed, some fields look weird after fill-in; for some fields * this is due to weird pre-existing appearance streams. These can * be fixed as in {@link #testFill0DropOldAppearance()}. * </p> * @see #testFill0DropOldAppearance() * @see #testFill0DropOldAppearanceNoCombNoMax() * @see #testFill0DropOldAppearanceNoCombNoMaxNoMultiLine() */ @Test public void testFill0LikeXenyal() throws IOException { try ( InputStream originalStream = getClass().getResourceAsStream("0.pdf"); InputStream fontStream = getClass().getResourceAsStream("Lato-Regular.ttf")) { PDDocument doc = Loader.loadPDF(originalStream); PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm(); PDType0Font font = PDType0Font.load(doc, fontStream, false); String font_name = acroForm.getDefaultResources().add(font).getName(); for (PDField field : acroForm.getFieldTree()) { if (field instanceof PDTextField) { PDTextField textField = (PDTextField) field; textField.setDefaultAppearance(String.format("/%s 0 Tf 0 g", font_name)); textField.setValue("Test"); } } doc.save(new File(RESULT_FOLDER, "0-filledLikeXenyal.pdf")); doc.close(); } }
Example #6
Source File: ReadForm.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/36964496/pdfbox-2-0-overcoming-dictionary-key-encoding"> * PDFBox 2.0: Overcoming dictionary key encoding * </a> * <br/> * <a href="http://www.stockholm.se/PageFiles/85478/KYF%20211%20Best%C3%A4llning%202014.pdf"> * KYF 211 Beställning 2014.pdf * </a> * * <p> * Indeed, the special characters in the names are replaced by the Unicode replacement * character. PDFBox, when parsing a PDF name, immediately interprets its bytes as UTF-8 * encoded which fails in the document at hand. * </p> */ @Test public void testReadFormOptions() throws IOException { try ( InputStream originalStream = getClass().getResourceAsStream("KYF 211 Best\u00e4llning 2014.pdf") ) { PDDocument pdfDocument = Loader.loadPDF(originalStream); PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm(); PDField field = acroForm.getField("Krematorier"); List<PDAnnotationWidget> widgets = field.getWidgets(); System.out.println("Field Name: " + field.getPartialName() + " (" + widgets.size() + ")"); for (PDAnnotationWidget annot : widgets) { PDAppearanceDictionary ap = annot.getAppearance(); Set<COSName> keys = ((COSDictionary)(ap.getCOSObject().getDictionaryObject("N"))).keySet(); ArrayList<String> keyList = new ArrayList<>(keys.size()); for (COSName cosKey : keys) {keyList.add(cosKey.getName());} System.out.println(String.join("|", keyList)); } } }
Example #7
Source File: FillInForm.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/56938135/pdfbox-inconsistent-pdtextfield-autosize-behavior-after-setvalue"> * PDFBox Inconsistent PDTextField Autosize Behavior after setValue * </a> * <br/> * <a href="http://www.filedropper.com/0postfontload"> * 0.pdf * </a> * <p> * Removing the old appearance streams before setting the new field * values removes the compression of the Resident Name and Care * Providers Address fields. In the latter case, though, the lower * part of the field value now is cut off. * </p> * <p> * For some fields only the first two letters are visible. This is * due to them being two character comb fields. These can changed * as in {@link #testFill0DropOldAppearanceNoCombNoMax()}. * </p> * @see #testFill0LikeXenyal() * @see #testFill0DropOldAppearanceNoCombNoMax() * @see #testFill0DropOldAppearanceNoCombNoMaxNoMultiLine() */ @Test public void testFill0DropOldAppearance() throws IOException { try ( InputStream originalStream = getClass().getResourceAsStream("0.pdf"); InputStream fontStream = getClass().getResourceAsStream("Lato-Regular.ttf")) { PDDocument doc = Loader.loadPDF(originalStream); PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm(); PDType0Font font = PDType0Font.load(doc, fontStream, false); String font_name = acroForm.getDefaultResources().add(font).getName(); for (PDField field : acroForm.getFieldTree()) { if (field instanceof PDTextField) { PDTextField textField = (PDTextField) field; textField.setDefaultAppearance(String.format("/%s 0 Tf 0 g", font_name)); textField.getWidgets().forEach(w -> w.getAppearance().setNormalAppearance((PDAppearanceEntry)null)); textField.setValue("Test"); } } doc.save(new File(RESULT_FOLDER, "0-filledDropOldAppearance.pdf")); doc.close(); } }
Example #8
Source File: ShowFormFieldNames.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="http://stackoverflow.com/questions/39574021/how-can-the-internal-labels-of-the-editable-fields-in-an-acroform-pdf-be-found"> * How can the internal labels of the editable fields in an acroform .pdf be found and listed? * </a> * <p> * This method retrieves the form field names from the given {@link PDDocument}. * </p> */ List<String> getFormFieldNames(PDDocument pdDocument) { PDAcroForm pdAcroForm = pdDocument.getDocumentCatalog().getAcroForm(); if (pdAcroForm == null) return Collections.emptyList(); List<String> result = new ArrayList<>(); for (PDField pdField : pdAcroForm.getFieldTree()) { if (pdField instanceof PDTerminalField) { result.add(pdField.getFullyQualifiedName()); } } return result; }
Example #9
Source File: DetermineWidgetPage.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/22074449/how-to-know-if-a-field-is-on-a-particular-page"> * how to know if a field is on a particular page? * </a> * <p> * This sample document contains the optional page entry in its annotations. * Thus, the fast method returns the same result as the safe one. * </p> */ @Test public void testTestDuplicateField2() throws IOException { System.out.println("test_duplicate_field2.pdf\n================="); try ( InputStream resource = getClass().getResourceAsStream("test_duplicate_field2.pdf") ) { PDDocument document = Loader.loadPDF(resource); PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); if (acroForm != null) { for (PDField field : acroForm.getFieldTree()) { System.out.println(field.getFullyQualifiedName()); for (PDAnnotationWidget widget : field.getWidgets()) { System.out.print(widget.getAnnotationName() != null ? widget.getAnnotationName() : "(NN)"); System.out.printf(" - fast: %s", determineFast(document, widget)); System.out.printf(" - safe: %s\n", determineSafe(document, widget)); } } } } System.out.println(); }
Example #10
Source File: DetermineWidgetPage.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/22074449/how-to-know-if-a-field-is-on-a-particular-page"> * how to know if a field is on a particular page? * </a> * <p> * This sample document does not contain the optional page entry in its annotations. * Thus, the fast method fails in contrast to the safe one. * </p> */ @Test public void testAFieldTwice() throws IOException { System.out.println("aFieldTwice.pdf\n================="); try ( InputStream resource = getClass().getResourceAsStream("aFieldTwice.pdf") ) { PDDocument document = Loader.loadPDF(resource); PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); if (acroForm != null) { for (PDField field : acroForm.getFieldTree()) { System.out.println(field.getFullyQualifiedName()); for (PDAnnotationWidget widget : field.getWidgets()) { System.out.print(widget.getAnnotationName() != null ? widget.getAnnotationName() : "(NN)"); System.out.printf(" - fast: %s", determineFast(document, widget)); System.out.printf(" - safe: %s\n", determineSafe(document, widget)); } } } } System.out.println(); }
Example #11
Source File: FillAndFlatten.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/60964782/pdfbox-inconsistent-pdtextfield-behaviour-after-setvalue"> * PDFBox Inconsistent PDTextField Behaviour after setValue * </a> * </br/> * <a href="https://s3-us-west-2.amazonaws.com/kx-filing-docs/b3-3.pdf"> * b3-3.pdf * </a> * <p> * After removing the actions, PDFBox again sets appearances in * all fields. * </p> * @see #testLikeAbubakar() */ @Test public void testLikeAbubakarRemoveAction() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("b3-3.pdf"); PDDocument pdDocument = Loader.loadPDF(resource) ) { PDDocumentCatalog catalog = pdDocument.getDocumentCatalog(); PDAcroForm acroForm = catalog.getAcroForm(); int i = 0; for (PDField field : acroForm.getFields()) { i=i+1; if (field instanceof PDTextField) { PDTextField textField = (PDTextField) field; textField.setActions(null); textField.setValue(Integer.toString(i)); } } pdDocument.getDocumentCatalog().getAcroForm().flatten(); pdDocument.save(new File(RESULT_FOLDER, "b3-3-remove-action-filled-and-flattened.pdf")); } }
Example #12
Source File: CheckImageFieldFilled.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/56959790/how-do-i-find-which-image-field-in-pdf-has-image-inserted-and-which-one-has-no-i"> * How do I find which image field in PDF has image inserted and which one has no images attached using PDFbox 1.8.11? * </a> * <br/> * <a href="https://www.dropbox.com/s/g2wqm8ipsp8t8l5/GSA%20500%20PDF_v4.pdf?dl=0"> * GSA 500 PDF_v4.pdf * </a> * <p> * This test shows how to check in the XFA XML whether a given image * field is set. * </p> * @see #isFieldFilledXfa(Document, String) */ @Test public void testCheckXfaGsa500Pdf_v4() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("GSA 500 PDF_v4.pdf"); PDDocument document = Loader.loadPDF(resource); ) { PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); Document xfaDom = acroForm.getXFA().getDocument(); System.out.println("Filled image fields from ImageField1..ImageField105:"); for (int i=1; i < 106; i++) { if (isFieldFilledXfa(xfaDom, "ImageField" + i)) { System.out.printf("* ImageField%d\n", i); } } } }
Example #13
Source File: CreateMultipleVisualizations.java From testarea-pdfbox2 with Apache License 2.0 | 6 votes |
/** * <a href="https://stackoverflow.com/questions/52829507/multiple-esign-using-pdfbox-2-0-12-java"> * Multiple esign using pdfbox 2.0.12 java? * </a> * <p> * This test demonstrates how to create a single signature in multiple signature * fields with one widget annotation each only referenced from a single page each * only. (Actually there is an extra invisible signature; it is possible to get * rid of it with some more code.) * </p> */ @Test public void testCreateSignatureWithMultipleVisualizations() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/analyze/test-rivu.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "testSignedMultipleVisualizations.pdf")); PDDocument pdDocument = Loader.loadPDF(resource) ) { PDAcroForm acroForm = pdDocument.getDocumentCatalog().getAcroForm(); if (acroForm == null) { pdDocument.getDocumentCatalog().setAcroForm(acroForm = new PDAcroForm(pdDocument)); } acroForm.setSignaturesExist(true); acroForm.setAppendOnly(true); acroForm.getCOSObject().setDirect(true); PDRectangle rectangle = new PDRectangle(100, 600, 300, 100); PDSignature signature = new PDSignature(); signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED); signature.setName("Example User"); signature.setLocation("Los Angeles, CA"); signature.setReason("Testing"); signature.setSignDate(Calendar.getInstance()); pdDocument.addSignature(signature, this); for (PDPage pdPage : pdDocument.getPages()) { addSignatureField(pdDocument, pdPage, rectangle, signature); } pdDocument.saveIncremental(result); } }
Example #14
Source File: PDFParser.java From document-management-software with GNU Lesser General Public License v3.0 | 6 votes |
/** * Extract the text from the form fields */ private void parseForm(PDDocument pdfDocument, StringBuffer content) throws IOException { PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); if (acroForm == null) return; content.append("\n"); List<PDField> fields = acroForm.getFields(); log.debug("{} top-level fields were found on the form", fields.size()); for (PDField field : fields) { content.append(field.getPartialName()); content.append(" = "); content.append(field.getValueAsString()); content.append(" \n "); } }
Example #15
Source File: PDDocument.java From gcs with Mozilla Public License 2.0 | 6 votes |
/** * Retrieve all signature fields from the document. * * @return a <code>List</code> of <code>PDSignatureField</code>s * @throws IOException if no document catalog can be found. */ public List<PDSignatureField> getSignatureFields() throws IOException { List<PDSignatureField> fields = new ArrayList<PDSignatureField>(); PDAcroForm acroForm = getDocumentCatalog().getAcroForm(); if (acroForm != null) { for (PDField field : acroForm.getFieldTree()) { if (field instanceof PDSignatureField) { fields.add((PDSignatureField)field); } } } return fields; }
Example #16
Source File: PDVisibleSigBuilder.java From gcs with Mozilla Public License 2.0 | 6 votes |
@Override public void createAcroFormDictionary(PDAcroForm acroForm, PDSignatureField signatureField) throws IOException { @SuppressWarnings("unchecked") List<PDField> acroFormFields = acroForm.getFields(); COSDictionary acroFormDict = acroForm.getCOSObject(); acroForm.setSignaturesExist(true); acroForm.setAppendOnly(true); acroFormDict.setDirect(true); acroFormFields.add(signatureField); acroForm.setDefaultAppearance("/sylfaen 0 Tf 0 g"); pdfStructure.setAcroFormFields(acroFormFields); pdfStructure.setAcroFormDictionary(acroFormDict); LOG.info("AcroForm dictionary has been created"); }
Example #17
Source File: ShowFormFieldNames.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/39574021/how-can-the-internal-labels-of-the-editable-fields-in-an-acroform-pdf-be-found"> * How can the internal labels of the editable fields in an acroform .pdf be found and listed? * </a> * <p> * This method retrieves the form field names from the given {@link PDDocument} * using a bit more fancy streaming methods. * </p> */ List<String> getFormFieldNamesFancy(PDDocument pdDocument) { PDAcroForm pdAcroForm = pdDocument.getDocumentCatalog().getAcroForm(); if (pdAcroForm == null) return Collections.emptyList(); return StreamSupport.stream(pdAcroForm.getFieldTree().spliterator(), false) .filter(field -> (field instanceof PDTerminalField)) .map(field -> field.getFullyQualifiedName()) .collect(Collectors.toList()); }
Example #18
Source File: PDDocumentCatalogBleach.java From DocBleach with MIT License | 5 votes |
private void sanitizeAcroFormActions(PDAcroForm acroForm) { if (acroForm == null) { LOGGER.debug("No AcroForms found"); return; } LOGGER.trace("Checking AcroForm Actions"); Iterator<PDField> fields = acroForm.getFieldIterator(); fields.forEachRemaining(this::sanitizeField); }
Example #19
Source File: FillInForm.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="http://stackoverflow.com/questions/39720305/ufffd-is-not-available-in-this-fonts-encoding-winansiencoding"> * U+FFFD is not available in this font's encoding: WinAnsiEncoding * </a> * <p> * The issue cannot be reproduced. * </p> */ @Test public void testFillLikeStDdt() throws IOException { try ( InputStream originalStream = getClass().getResourceAsStream("FillFormField.pdf") ) { PDDocument pdfDocument = Loader.loadPDF(originalStream); PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm(); if (acroForm != null) { List<PDField> fields = acroForm.getFields(); for (PDField field : fields) { switch (field.getPartialName()) { case "Title" /*"devices"*/: field.setValue("Ger�t"); field.setReadOnly(true); break; } } acroForm.flatten(fields, true); } pdfDocument.save(new File(RESULT_FOLDER, "FillFormFieldStDdt.pdf")); pdfDocument.close(); } }
Example #20
Source File: RightAlignField.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="https://stackoverflow.com/questions/55355800/acroform-text-field-not-align-to-right"> * acroform text field not align to right * </a> * <br/> * <a href="https://drive.google.com/uc?id=1jFbsYGFOnx8EMiHgDsE8LQtfwJHSa5Gh&export=download"> * form.pdf * </a> as "formBee2.pdf" * <p> * Indeed, in {@link #testAlignLikeBee()} quadding does not apply. * But by changing the order of field value setting and quadding * value setting it suddenly does apply. * </p> */ @Test public void testAlignLikeBeeImproved() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("formBee2.pdf") ) { PDDocument document = Loader.loadPDF(resource); PDDocumentCatalog documentCatalog = document.getDocumentCatalog(); PDAcroForm acroForm = documentCatalog.getAcroForm(); ((PDTextField) acroForm.getField("NewRentWithoutChargesChf")).setQ(PDVariableText.QUADDING_RIGHT); acroForm.getField("NewRentWithoutChargesChf").setValue("1.00"); document.save(new File(RESULT_FOLDER, "formBee2-AlignLikeBeeImproved.pdf")); document.close(); } }
Example #21
Source File: RightAlignField.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="https://stackoverflow.com/questions/55355800/acroform-text-field-not-align-to-right"> * acroform text field not align to right * </a> * <br/> * <a href="https://drive.google.com/uc?id=1jFbsYGFOnx8EMiHgDsE8LQtfwJHSa5Gh&export=download"> * form.pdf * </a> as "formBee2.pdf" * <p> * Indeed, the way the OP does this, quadding does not apply. * But see {@link #testAlignLikeBeeImproved()}. * </p> */ @Test public void testAlignLikeBee() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("formBee2.pdf") ) { PDDocument document = Loader.loadPDF(resource); PDDocumentCatalog documentCatalog = document.getDocumentCatalog(); PDAcroForm acroForm = documentCatalog.getAcroForm(); acroForm.getField("NewRentWithoutChargesChf").setValue("1.00"); ((PDTextField) acroForm.getField("NewRentWithoutChargesChf")).setQ(PDVariableText.QUADDING_RIGHT); document.save(new File(RESULT_FOLDER, "formBee2-AlignLikeBee.pdf")); document.close(); } }
Example #22
Source File: AddFormField.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="https://stackoverflow.com/questions/46433388/pdfbox-could-not-find-font-helv"> * PDFbox Could not find font: /Helv * </a> * <br/> * <a href="https://drive.google.com/file/d/0B2--NSDOiujoR3hOZFYteUl2UE0/view?usp=sharing"> * 4.pdf * </a> * <p> * The cause is a combination of the OP and the source PDF not providing * a default appearance for the text field and PDFBox providing defaults * inconsequentially. * </p> * <p> * This is fixed here by setting the default appearance explicitly. * </p> */ @Test public void testAddFieldLikeEugenePodoliako() throws IOException { try ( InputStream originalStream = getClass().getResourceAsStream("4.pdf") ) { PDDocument pdf = Loader.loadPDF(originalStream); PDDocumentCatalog docCatalog = pdf.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); PDPage page = pdf.getPage(0); PDTextField textBox = new PDTextField(acroForm); textBox.setPartialName("SampleField"); acroForm.getFields().add(textBox); PDAnnotationWidget widget = textBox.getWidgets().get(0); PDRectangle rect = new PDRectangle(0, 0, 0, 0); widget.setRectangle(rect); widget.setPage(page); // Unnecessary code from OP // widget.setAppearance(acroForm.getFields().get(0).getWidgets().get(0).getAppearance()); // Fix added to set default appearance accordingly textBox.setDefaultAppearance(acroForm.getFields().get(0).getCOSObject().getString("DA")); widget.setPrinted(false); page.getAnnotations().add(widget); acroForm.refreshAppearances(); acroForm.flatten(); pdf.save(new File(RESULT_FOLDER, "4-add-field.pdf")); pdf.close(); } }
Example #23
Source File: PDDocument.java From gcs with Mozilla Public License 2.0 | 5 votes |
private void assignAcroFormDefaultResource(PDAcroForm acroForm, COSDictionary newDict) { // read and set/update AcroForm default resource dictionary /DR if available COSBase newBase = newDict.getDictionaryObject(COSName.DR); if (newBase instanceof COSDictionary) { COSDictionary newDR = (COSDictionary) newBase; PDResources defaultResources = acroForm.getDefaultResources(); if (defaultResources == null) { acroForm.getCOSObject().setItem(COSName.DR, newDR); newDR.setDirect(true); newDR.setNeedToBeUpdated(true); } else { COSDictionary oldDR = defaultResources.getCOSObject(); COSBase newXObjectBase = newDR.getItem(COSName.XOBJECT); COSBase oldXObjectBase = oldDR.getItem(COSName.XOBJECT); if (newXObjectBase instanceof COSDictionary && oldXObjectBase instanceof COSDictionary) { ((COSDictionary) oldXObjectBase).addAll((COSDictionary) newXObjectBase); oldDR.setNeedToBeUpdated(true); } } } }
Example #24
Source File: PDDocumentCatalog.java From gcs with Mozilla Public License 2.0 | 5 votes |
/** * Get the documents AcroForm. This will return null if no AcroForm is part of the document. * * @return The document's AcroForm. */ public PDAcroForm getAcroForm() { if (cachedAcroForm == null) { COSDictionary dict = (COSDictionary)root.getDictionaryObject(COSName.ACRO_FORM); cachedAcroForm = dict == null ? null : new PDAcroForm(document, dict); } return cachedAcroForm; }
Example #25
Source File: ListFormFields.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="https://stackoverflow.com/questions/44817793/the-method-getkids-is-undefined-for-the-type-pdfield"> * The method getKids() is undefined for the type PDField * </a> * <br/> * <a href="https://issues.apache.org/jira/secure/attachment/12651245/field%20name%20test.pdf"> * field name test.pdf * </a> * <p> * The problems referred to don't exist anymore. * </p> */ @Test public void testListFieldsInFieldNameTest() throws InvalidPasswordException, IOException { PDDocument doc = Loader.loadPDF(getClass().getResourceAsStream("field name test.pdf")); PDAcroForm form = doc.getDocumentCatalog().getAcroForm(); List<PDField> fields = form.getFields(); for (int i=0; i<fields.size(); i++) { PDField f = fields.get(i); if (f instanceof PDTerminalField) { System.out.printf("%s, %s widgets\n", f.getFullyQualifiedName(), f.getWidgets().size()); for (PDAnnotationWidget widget : f.getWidgets()) System.out.printf(" %s\n", widget.getAnnotationName()); } else if (f instanceof PDNonTerminalField) { List<PDField> kids = ((PDNonTerminalField)f).getChildren(); for (int j=0; j<kids.size(); j++) { if (kids.get(j) instanceof PDField) { PDField kidField = (PDField) kids.get(j); System.out.println(kidField.getFullyQualifiedName()); } } } } }
Example #26
Source File: FillInForm.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="https://stackoverflow.com/questions/56938135/pdfbox-inconsistent-pdtextfield-autosize-behavior-after-setvalue"> * PDFBox Inconsistent PDTextField Autosize Behavior after setValue * </a> * <br/> * <a href="http://www.filedropper.com/0postfontload"> * 0.pdf * </a> * <p> * Resetting the comb flags and removing maximum lengths fixes the * appearance of the fields in which only the first two letters were * visible. * </p> * <p> * The problem of the lower part of the field value being cut off in * the Care Providers Address fields is due to PDFBox in case of * multi line text fields using a fixed font height and not fine * tuning the vertical position of the field contents. In the case * at hand this can be fixed as in {@link #testFill0DropOldAppearanceNoCombNoMaxNoMultiLine()}. * </p> * @see #testFill0LikeXenyal() * @see #testFill0DropOldAppearance() * @see #testFill0DropOldAppearanceNoCombNoMaxNoMultiLine() */ @Test public void testFill0DropOldAppearanceNoCombNoMax() throws IOException { final int FLAG_COMB = 1 << 24; try ( InputStream originalStream = getClass().getResourceAsStream("0.pdf"); InputStream fontStream = getClass().getResourceAsStream("Lato-Regular.ttf")) { PDDocument doc = Loader.loadPDF(originalStream); PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm(); PDType0Font font = PDType0Font.load(doc, fontStream, false); String font_name = acroForm.getDefaultResources().add(font).getName(); for (PDField field : acroForm.getFieldTree()) { if (field instanceof PDTextField) { PDTextField textField = (PDTextField) field; textField.getCOSObject().removeItem(COSName.MAX_LEN); textField.getCOSObject().setFlag(COSName.FF, FLAG_COMB, false);; textField.setDefaultAppearance(String.format("/%s 0 Tf 0 g", font_name)); textField.getWidgets().forEach(w -> w.getAppearance().setNormalAppearance((PDAppearanceEntry)null)); textField.setValue("Test"); } } doc.save(new File(RESULT_FOLDER, "0-filledDropOldAppearanceNoCombNoMax.pdf")); doc.close(); } }
Example #27
Source File: ExtractAppearanceText.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="https://stackoverflow.com/questions/49427615/how-to-extract-label-text-from-push-button-using-apache-pdfbox"> * How to extract label text from Push button using Apache PDFBox? * </a> * <p> * This method extracts the text from the normal appearance streams * of the form fields in the given PDF document. * </p> * @see #testBtn() * @see #testKYF211Beställning2014() */ public void showNormalFieldAppearanceTexts(PDDocument document) throws IOException { PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); if (acroForm != null) { SimpleXObjectTextStripper stripper = new SimpleXObjectTextStripper(); for (PDField field : acroForm.getFieldTree()) { if (field instanceof PDTerminalField) { PDTerminalField terminalField = (PDTerminalField) field; System.out.println(); System.out.println("* " + terminalField.getFullyQualifiedName()); for (PDAnnotationWidget widget : terminalField.getWidgets()) { PDAppearanceDictionary appearance = widget.getAppearance(); if (appearance != null) { PDAppearanceEntry normal = appearance.getNormalAppearance(); if (normal != null) { Map<COSName, PDAppearanceStream> streams = normal.isSubDictionary() ? normal.getSubDictionary() : Collections.singletonMap(COSName.DEFAULT, normal.getAppearanceStream()); for (Map.Entry<COSName, PDAppearanceStream> entry : streams.entrySet()) { String text = stripper.getText(entry.getValue()); System.out.printf(" * %s: %s\n", entry.getKey().getName(), text); } } } } } } } }
Example #28
Source File: SetRichText.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="https://stackoverflow.com/questions/54988511/acroform-field-setrichtextvalue-is-not-working"> * acroform field.setRichTextValue is not working * </a> * <br/> * <a href="https://drive.google.com/open?id=1jFbsYGFOnx8EMiHgDsE8LQtfwJHSa5Gh"> * form.pdf * </a> as "formBee.pdf" * <p> * After correction of a few details, the code kinda runs. In * particular it is necessary to use PDF style rich text (and * not LaTeX richtext package instructions), to set the flag * NeedAppearances to <code>true</code>, and to provide a V * value equal to the RV value without markup. * </p> * <p> * It only "kinda" runs because the OP also wants to flatten * the form which doesn't work as PDFBox does not create * appearance streams based on the rich text value. * </p> */ @Test public void testFormBee() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("formBee.pdf")) { PDDocument pdfDocument = Loader.loadPDF(resource); pdfDocument.getDocument().setIsXRefStream(true); PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm(); acroForm.setNeedAppearances(true); acroForm.getField("tenantDataValue").setValue("Deuxième texte"); acroForm.getField("tradingAddressValue").setValue("Text replacé"); acroForm.getField("buildingDataValue").setValue("Deuxième texte"); acroForm.getField("oldRentValue").setValue("750"); acroForm.getField("oldChargesValue").setValue("655"); acroForm.getField("newRentValue").setValue("415"); acroForm.getField("newChargesValue").setValue("358"); acroForm.getField("increaseEffectiveDateValue").setValue("Texte 3eme contenu"); PDTextField field = (PDTextField) acroForm.getField("tableData"); field.setRichText(true); //String val = "\\rtpara[size=12]{para1}{This is 12pt font, while \\span{size=8}{this is 8pt font.} OK?}"; String val1 = "<?xml version=\"1.0\"?>" + "<body xfa:APIVersion=\"Acroform:2.7.0.0\" xfa:spec=\"2.1\" xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\">" + "<p dir=\"ltr\" style=\"margin-top:0pt;margin-bottom:0pt;font-family:Helvetica;font-size:12pt\">" + "This is 12pt font, while " + "<span style=\"font-size:8pt\">this is 8pt font.</span>" + " OK?" + "</p>" + "</body>"; String val1Clean = "This is 12pt font, while this is 8pt font. OK?"; //String val2 = "<body xmlns=\"http://www.w3.org/1999/xhtml\"><p style=\"color:#FF0000;\">Red </p><p style=\"color:#1E487C;\">Blue </p></body>"; //String val2Clean = "Red\rBlue\r"; field.setValue(val1Clean); field.setRichTextValue(val1); pdfDocument.save(new File(RESULT_FOLDER, "formBee-filled.pdf")); } }
Example #29
Source File: CreateMultipleVisualizations.java From testarea-pdfbox2 with Apache License 2.0 | 5 votes |
/** * <a href="https://stackoverflow.com/questions/52829507/multiple-esign-using-pdfbox-2-0-12-java"> * Multiple esign using pdfbox 2.0.12 java? * </a> * <br/> * <a href="https://drive.google.com/open?id=1DKSApmjrT424wT92yBdynKUkvR00x9i2"> * C10000000713071804294534.pdf * </a> * <p> * This test demonstrates how to create a single signature in multiple signature * fields with one widget annotation each only referenced from a single page each * only. (Actually there is an extra invisible signature; it is possible to get * rid of it with some more code.) It uses the test file provided by the OP. * </p> */ @Test public void testCreateSignatureWithMultipleVisualizationsC10000000713071804294534() throws IOException { try ( InputStream resource = getClass().getResourceAsStream("C10000000713071804294534.pdf"); OutputStream result = new FileOutputStream(new File(RESULT_FOLDER, "C10000000713071804294534-SignedMultipleVisualizations.pdf")); PDDocument pdDocument = Loader.loadPDF(resource) ) { PDAcroForm acroForm = pdDocument.getDocumentCatalog().getAcroForm(); if (acroForm == null) { pdDocument.getDocumentCatalog().setAcroForm(acroForm = new PDAcroForm(pdDocument)); } acroForm.setSignaturesExist(true); acroForm.setAppendOnly(true); acroForm.getCOSObject().setDirect(true); PDRectangle rectangle = new PDRectangle(100, 600, 300, 100); PDSignature signature = new PDSignature(); signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED); signature.setName("Example User"); signature.setLocation("Los Angeles, CA"); signature.setReason("Testing"); signature.setSignDate(Calendar.getInstance()); pdDocument.addSignature(signature, this); for (PDPage pdPage : pdDocument.getPages()) { addSignatureField(pdDocument, pdPage, rectangle, signature); } pdDocument.saveIncremental(result); } }
Example #30
Source File: PDVisibleSigBuilder.java From gcs with Mozilla Public License 2.0 | 5 votes |
@Override public void createAcroForm(PDDocument template) { PDAcroForm theAcroForm = new PDAcroForm(template); template.getDocumentCatalog().setAcroForm(theAcroForm); pdfStructure.setAcroForm(theAcroForm); LOG.info("AcroForm has been created"); }