DEV Community


Posted on

Fill PDF Form Fields using Java

PDF form fields are mainly used to collect user information and I've introduced how to create form fields in PDF by using Free Spire.PDF for Java. In this article I will share how to fill each form field with value with this 3rd party free library.

Method 1: Download the Free Spire.PDF for Java and unzip it.Then add the Spire.Pdf.jar file to your project as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

Enter fullscreen mode Exit fullscreen mode

Relevant Code Snippet

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

import java.awt.geom.Point2D;

public class AddLayers {
    public static void main(String[] args){
        //Instantiate a PdfDocument object
        PdfDocument pdf = new PdfDocument();
        //Add a page
        PdfPageBase page = pdf.getPages().add();

        //Add 3 layers to the page
        PdfLayer layer = pdf.getLayers().addLayer("red line1");
        PdfCanvas canvas1 = layer.createGraphics(pdf.getPages().get(0).getCanvas());
        canvas1.drawLine(new PdfPen(PdfBrushes.getRed(), 1), new Point2D.Float(50, 350), new Point2D.Float(200, 350));
        layer = pdf.getLayers().addLayer("blue line1");
        PdfCanvas canvas2 = layer.createGraphics(pdf.getPages().get(0).getCanvas());
        canvas2.drawLine(new PdfPen(PdfBrushes.getBlue(), 1), new Point2D.Float(50, 450), new Point2D.Float(200, 450));
        layer = pdf.getLayers().addLayer("green line1");
        PdfCanvas canvas3 = layer.createGraphics(pdf.getPages().get(0).getCanvas());
        canvas3.drawLine(new PdfPen(PdfBrushes.getGreen(), 1), new Point2D.Float(50,550), new Point2D.Float(200, 550));

        //Save the resultant document
Enter fullscreen mode Exit fullscreen mode

Alt Text

Discussion (0)