This tutorial will guide filling a PDF form using the PDF.co Form Filler Web API for Python programming language. The tutorial also explains the method by providing the sample source code for demonstration. The users can benefit from PDF.co Web API for automating the form filling process for efficient working.

  1. Benefits of using PDF.co Web API
  2. Features of the Web API
  3. Python Example
  4. Sample Code Snippet
  5. Step-by-Step Guide to Use From Filler Web API in Python
  6. Video Demonstration for Form Filling
  7. Filled Form Output

Benefits of using PDF.co Web API

For process automation and providing a quick solution to the users, the PDF.co Form Filler Web API accepts various input modes like process automation and provides a quick solution to the user input, CRMs, spreadsheets, and many more. The Form Filler Web API can increase the speed of form filling exponentially, at an exponential rate giving users the advantage by saving them from the hassle of filling forms manually.

Various fields can be present in a PDF document, such as text input fields, checkboxes, radio buttons, combo boxes, and list buttons. Moreover, there is also an option to flatten the filled-out objects and convert all editable objects into read-only objects. Furthermore, there is also an option to put a signature in the PDF by embedding it in the form using an image object.

Another issue while filling out forms automatically and uploading them on a website is the risk of a security breach and leaking valuable information. However, the PDF.co Web API ensures high security. The Web API ensures the transmission of documents via encrypted connections to prevent any data breach. Users can visit this link to ensure they are uploading their precious data on a secure website https://pdf.co/security.

Features of the Web API

Following are some main features the Web API provides its users with:

  • Interactive Form Filling by working with editable PDF Form and exporting the filled PDF Form. Moreover, the users can convert the editable forms into non-editable forms.
  • The Web API proves beneficial in affixing signatures in the form. There is an option to either embed the signature using an image object or draw the signature and then add it to the document.
  • Form Filler Web API supports easy field names mapping. The Web API accepts the document to analyze and provide relevant field names and information to help identify each object using advanced configuration.
  • It provides an on-premise API server that offers businesses and enterprises the benefit of hosting the REST API on their premises to avoid security breaches.

Python Example

The following source code explains how to fill a sample PDF form using PDF.co Form Filler Web API. The sample code in python explains how to fill a sample form like IRS Form 1099. There are various text fields, checkboxes, edit boxes, and signature fields in the form. The users can also use Get PDF Info Tool from the Helpers Tool menu after logging in to the PDF.co Website. Users can upload their documents and obtain information regarding field names and locations for filling efficiently.

The source code contains IRS Form 1099 as an example in this tutorial. Also, the users must provide their Web API key and PDF file URL in the Web API POST request. The resultant file will contain a filled PDF form with relevant provided data.

Sample Code Snippet

import os
import requests # pip install requests

# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
API_KEY = "********"

# Base URL for PDF.co Web API requests
BASE_URL = "https://api.pdf.co/v1"

# Direct URL of source PDF file.
# You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/bytescout/pdf-co-api-samples/tree/master/File%20Upload/   

SourceFileUrl = "https://www.irs.gov/pub/irs-pdf/f1099msc.pdf"
# PDF document password. Leave empty for unprotected documents.
Password = ""

# Destination PDF file name
DestinationFile = ".result.pdf"

# Runs processing asynchronously. Returns Use JobId that you may use with /job/check to check state of the processing (possible states: working, failed, aborted and success). Must be one of: true, false.
Async = "False"

# Values to fill out pdf fields with built-in pdf form filler.
# To fill fields in PDF form, use the following format page;fieldName;value for example: 0;editbox1;text is here. To fill checkbox, use true, for example: 0;checkbox1;true. To separate multiple objects, use | separator. To get the list of all fillable fields in PDF form please use /pdf/info/fields endpoint.

FieldsStrings = "1;topmostSubform[0].CopyA[0].CopyAHeader[0].c1_1[0];true|1;topmostSubform[0].CopyA[0].LeftColumn[0].f1_1[0];Iris|1;topmostSubform[0].CopyA[0].LeftColumn[0].f1_3[0];123456789|1;topmostSubform[0].CopyA[0].LeftColumn[0].f1_5[0];HelloWorld"

def main(args = None):
   fillPDFForm(SourceFileUrl, DestinationFile)

def fillPDFForm(uploadedFileUrl, destinationFile):
   """Converts HTML to PDF using PDF.co Web API"""

   # Prepare requests params as JSON
   # See documentation: https://apidocs.pdf.co
   parameters = {}
   parameters["name"] = os.path.basename(destinationFile)
   parameters["url"] = uploadedFileUrl
   parameters["fieldsString"] = FieldsStrings
   parameters["async"] = Async

   # Prepare URL for 'Fill PDF' API request
   url = "{}/pdf/edit/add".format(BASE_URL)

   # Execute request and get response as JSON
   response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
   if (response.status_code == 200):
       json = response.json()
       if json["error"] == False:
           #  Get URL of result file
           resultFileUrl = json["url"]
           print(resultFileUrl)
           # Download result file
           r = requests.get(resultFileUrl, stream=True)
           if (r.status_code == 200):
               with open(destinationFile, 'wb') as file:
                   for chunk in r:
                       file.write(chunk)
               print(f"Result file saved as "{destinationFile}" file.")
           else:
               print(f"Request error: {response.status_code} {response.reason}")
       else:

           # Show service reported error
           print(json["message"])
   else:
       print(f"Request error: {response.status_code} {response.reason}")

if __name__ == '__main__':
   main()

Step-by-Step Guide to Use From Filler Web API in Python

Following are the steps to fill a PDF form using PDF.co Web API in python:

  1. Firstly, import the required modules at the start of the python file. In this scenario, the user must import os and request modules. The users might need to install these packages before importing them.
  2. Log into the PDF.co website and get the Web API key from the dashboard, which the users need to add in the Web API authentication headers.
  3. Declare and initialize the variables with the Web API key, source file URL, Web API endpoint URL, and the request payload. This step is optional, but it is easier to modify the variables than edit the whole request later. Moreover, the users must provide the source file password if it is a locked file.
  4. The users can get the field names and page numbers for the field parameter by going to the pdf info tab inside the helper tools on the main menu. In the pdf info tab, the users can upload their file manually, dropbox, or provide the file URL. Once the user has uploaded the file and has pressed the proceed button, he gets the given file’s properties, file information, and the pdf fields.
  5. The users can copy the pdf field names and the page numbers of the required fields from this given information and use it in the fields’ parameter. Moreover, the users can see the length and width of the fields to make sure that the values are of the same length or are less than the field’s space.
  6. Insert the page number, field name, and the value in the fields parameter to edit the particular field and add the given value.
  7. The above code snippet adds the “async” parameter to the request body, which is “false” by default. The users can make its value “true” and “false” to make the process asynchronous and synchronous, respectively.
  8. Create a “POST” to the given endpoint and provide the parameters and the Web API key in the request body and authentication header, respectively.
  9. Store the request’s response in a variable and check its status code. If the status code is “200”, it means that the request was successful; otherwise, the user needs to debug the code depending on the status code number and re-run the program.
  10. If the request was successful, extract the JSON object from the response and get the output URL field.
  11. The users can find the edited form by going to the provided link and downloading the form directly. As the output link is temporary, the users must download and save the form on their local storage or upload it on the cloud.
  12. Additionally, the users can download the file by writing the simple code snippet that makes the “GET” request to the output URL and gets the form data. They can then store that data in the destination or output file on their local storage.

Video Demonstration for Form Filling

Below is the video demonstration of the working code:

Fill a PDF Form using PDF.co API in Python GIF

Filled Form Output

Below is the screenshot of the form edited using the above code:

Form Filling Python