Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 3, 2019 10:23 pm GMT

How to create and fill out your own PDF form with Java

Introduction

In this tutorial, you will learn how to populate a PDF document with Java using the PDFBox library. In addition you will see how to create your own forms or add editable fields to an existing PDF document.

Creating a simple form

To create a form, let's use LibreOffice Draw.

Display the form toolbar. View Menu > Toolbars > Form Controls.

In a blank document, enter two text fields:

Display the properties of the text field:

Rename the fields to 'txt_1' and 'txt_2' respectively. Also leave the 'Read-only' property as 'Yes'.

Export the document as PDF. Mine is like '/tmp/pdf-java.pdf'

My template looked like this:

Populating the PDF through Java

Create a new maven Java project and add the dependency below:

<dependency>  <groupId>org.apache.pdfbox</groupId>  <artifactId>pdfbox</artifactId>  <version>2.0.16</version></dependency>

Create a Java class with the code below:

    public static void main(String[] args) {        try {            PDDocument pDDocument = PDDocument.load(new File("/tmp/pdf-java.pdf"));            PDAcroForm pDAcroForm = pDDocument.getDocumentCatalog().getAcroForm();            PDField field = pDAcroForm.getField("txt_1");            field.setValue("This is a first field printed by Java");            field = pDAcroForm.getField("txt_2");            field.setValue("This is a second field printed by Java");            pDDocument.save("/tmp/pdf-java-output.pdf");            pDDocument.close();        } catch (IOException e) {            e.printStackTrace();        }    }

Run the program and see the result:

Remember, the ending file was saved to: "/tmp/pdf-java-output.pdf".

The complete source code it's on github:

https://github.com/sandrogiacom/pdf-java

Conclusion

In this short tutorial, we learned how to populate a PDF from a PDF template created with LibreOffice Draw. Use your creativity to create beautiful templates, do automation, create batch files and more.

Leave in the comments what your use case would be.

See you soon!


Original Link: https://dev.to/sandrogiacom/how-to-create-and-fill-out-your-own-pdf-form-with-java-87b

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To