Fill Flatten Forms With Appearance

This guide will show you how to fill and or flatten PDF forms with appearance using UniPDF.

Before you begin

You should get your API key from your UniCloud account.

If you are using the UniPDF SDK for the first time, follow this guide to set up a local development environment.

Clone the project repository

In your terminal, clone the examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unipdf-examples.git

Navigate to the forms folder in the unipdf-examples directory.

cd unipdf-examples/forms

How it works

In the example code, the necessary libraries are imported in lines 9-17, in the import section. The init function, which is used to set the metered license key, is defined following this.

In lines 28-60, the main function is defined. Line 29-31 define the input pdf file, the input data for fields and the output path for final PDF. Line 53 fills the Form by calling fillFieldsWithAppearance(inputPath, jsonDataPath, outputPath).

The fillFieldsWithAppearance function which is defined in lines 65-113, does the actual filling and flattening of the fields. This function starts by loading the jason data which holds the field values. Line 71-78, creates a new PDF reader from the input PDF file.

A annotator.FieldAppearance object is created in line 82. Then, the appearance style is set in lines 86-92 using:

	fieldAppearance.SetStyle(annotator.AppearanceStyle{
		AutoFontSizeFraction: 0.70,
		FillColor:            model.NewPdfColorDeviceRGB(1, 1, 1),
		BorderColor:          model.NewPdfColorDeviceRGB(0, 0, 0),
		BorderSize:           2.0,
		AllowMK:              false,
		TextColor:            model.NewPdfColorDeviceRGB(0.5, 0.8, 0.8),
	})

Then the form is filled in line 96 as follows:

// Populate the form data.
// pdfReader.AcroForm.FillWithAppearance(fdata, fieldAppearance) // uncomment this line to fill with appearance
pdfReader.AcroForm.Fill(fdata)

Here if we want to fill the forms with appearances, we can uncomment the code pdfReader.AcroForm.FillWithAppearance(fdata, fieldAppearance) and keep the appearance in the filled data.

Next in line 90, the fields are flattened using pdfReader.FlattenFields(true, fieldAppearance). Here the first boolean argument is for specifying wether to flatten all annotation. And the second argument holds the annotator.FieldAppearance object. Line 105 converts the PDf reader to writer object. And finally, the document is written to file in line 111.

The getFont function in line in line 115, is used to load font from file path and return a font object.

Run the code

To run the code, use the following command.

go run pdf_fill_and_flatten_with_apearance.go

Sample Output

Sample Output

Got any Questions?

We're here to help you.