Building Agentic Document Workflows: How LLM Agents Use PDF APIs to Convert, Extract, and Sign at Scale

This guide walks through building agentic document workflows by exposing Foxit’s PDF and eSign APIs as callable MCP tools, so any compatible agent host can run the full document lifecycle in one automated pipeline.
Agentic document workflows go beyond retrieval, since they convert, transform, merge, and sign documents without human intervention. This guide shows how to expose Foxit’s production PDF API as callable MCP tools so any LLM agent can execute the full document lifecycle (OCR, extraction, generation, and legally binding signatures) in a single automated pipeline.
Most LLM-powered applications have solved the retrieval problem. The harder part of agentic document workflows is action, the moment your agent needs to convert a scanned invoice to searchable text, merge a dozen contract pages into a package, and route it for a legally binding signature without a human in the loop.
RAG gets text into a context window, which is useful for reading. Once you need to produce, transform, or sign a document, you’ve moved into document operations territory. A plain text API won’t close that delta, and bolting together a dozen bespoke REST wrappers every time you need a new pipeline quickly becomes the bottleneck.
The Model Context Protocol (MCP) gives agents a standard way to discover and call tools. Document workflows have been missing a tool surface that exposes real PDF operations as callable MCP tools, backed by a production-ready API. This guide walks through exactly how to build that.
What You Need Before You Start
Five prerequisites are required to follow this guide. You need a Foxit developer account, the open-source MCP server, an MCP-compatible host, three environment variables, and a Python workspace for the signing example.
A Foxit developer account. Sign up at account.foxit.com/site/sign-up (no credit card required for the free Developer plan). The Foxit Developer Portal issues your Client ID and Client Secret, gives you access to the API Playground, and tracks usage in real time.
The open-source MCP server. Clone github.com/foxitsoftware/foxit-pdf-api-mcp-server. The repo ships two active implementations, a Python build (using FastMCP, Python 3.11+, and the uv package manager) and a TypeScript build (Node.js 18+, pnpm). The original stdio-python variant is deprecated, so use the current Python or TypeScript implementation.
An MCP-compatible host. You need somewhere to run the agent. Claude Desktop, Cursor, or VS Code with GitHub Copilot all work, and any MCP-compliant custom agent framework will also connect to the server.
A Python workspace for the signing example. The eSign walkthrough later in this guide runs a short Python script, so you need Python 3.8+ and the requests library. That walkthrough also uses a separate set of eSign credentials, which you set up in its own section rather than here. Scaffold an isolated workspace in one shot:
mkdir agentic-docs && cd agentic-docs
python3 -m venv .venv && source .venv/bin/activate
pip install requests Three environment variables. Before launching your MCP host process, export these:
export FOXIT_CLOUD_API_HOST="https://na1.fusion.foxit.com/pdf-services"
export FOXIT_CLOUD_API_CLIENT_ID="your_client_id"
export FOXIT_CLOUD_API_CLIENT_SECRET="your_client_secret" Never hardcode credentials in config files. The MCP server reads these at startup and uses them to authenticate every request to the PDF Services API.
What “Agentic” Actually Means for Document Workflows
An agentic document workflow executes operations on documents (converting formats, applying OCR, merging pages, routing for signature) rather than simply retrieving text from them. The tool surface required is fundamentally different from a RAG setup.
Retrieval-augmented generation pulls text from a document and injects it into a prompt. An agentic document workflow does something to a document, whether it converts a format, applies OCR to make a scanned image searchable, merges pages from multiple sources, or routes the result for signature.
In a tool-use architecture, the LLM doesn’t call the API directly. It picks the right operation from a catalog of tools based on the task, calls it with structured inputs, processes the result, and decides whether to continue the chain or hand off to the next step. If you’ve worked with web-search or code-execution tools in LangChain or AutoGen, the pattern is identical. The model reasons about which tool to invoke, not about how the underlying HTTP request works.
A REST API is an HTTP surface. An MCP tool is a named, typed function with an input schema, an output contract, and a description the model uses to decide when and whether to call it. MCP standardizes that interface so any compliant host can discover the full tool catalog, call individual operations, and chain results without custom adapter code.
A well-designed MCP server eliminates the bespoke integration layer. Without one, every document-heavy agent pipeline requires someone to write and maintain that plumbing from scratch.
Architecture Overview: Two Modes for Agent-Driven PDF Processing
The Foxit PDF API MCP Server wraps Foxit’s cloud PDF Services API as 30+ callable MCP tools, covering every stage of a document lifecycle. Foxit PDF Editor is the first PDF editor in the industry to act as an MCP Host, connecting outward to external MCP Servers and acting on open documents.
Those two facts define two distinct architectural modes.
Mode 1: Programmatic pipeline. Your MCP host (Claude Desktop, Cursor, VS Code with GitHub Copilot, or a custom agent) registers the Foxit PDF API MCP Server. The agent calls PDF tools directly, the server translates those calls into Foxit PDF Services REST requests, and structured results return to the agent. The agent never writes REST plumbing. This is the right model for automated pipelines running without a human in the loop.
Mode 2: In-app orchestration. Foxit PDF Editor acts as the MCP Host. Its embedded AI Assistant connects to external MCP Servers (Jira, Salesforce, Gmail, Notion, GitHub, Google Workspace) and acts on the open document. You could extract fields from a contract PDF and open a Jira ticket without leaving the editor. This is the right model when a knowledge worker needs AI assistance during document review.
Mode 1 is what the rest of this guide builds. Its data flow runs like this:

The agent calls tools, the MCP server handles the REST layer against PDF Services, and a prepared document hands off to eSign at the end of the chain.
One detail to understand before you build is that each successful Foxit PDF Services API call consumes one credit from your plan. Failed requests (4xx or 5xx) do not consume credits. The Developer Dashboard shows real-time usage, so you can see exactly what a pipeline costs per document before scaling it up.
Setting Up the Foxit MCP Server
The server exposes tools across six categories (document lifecycle, creation, conversion, manipulation, security, and forms) plus OCR and document compare.
The full tool catalog breaks down as follows:
- Document lifecycle : upload, download, delete
- Creation : Word, Excel, PowerPoint, HTML, URL, plain text, and image to PDF
- Conversion : PDF to Word, Excel, PowerPoint, HTML, plain text, and image
- Manipulation : merge, split, extract pages, compress, flatten, linearize, watermark, and page operations
- Security : add and remove passwords, set permissions
- Forms : export and import form data as JSON
OCR and document compare are also in the catalog. Signing lives in the eSign API covered in Section 6.
Mode 1: Programmatic Pipeline Setup
Clone the repo and pick your implementation. For the Python version with VS Code and GitHub Copilot, create or update your .vscode/mcp.json with the following:
{
"servers": {
"foxit-pdf": {
"command": "uv",
"args": [
"--directory",
"/absolute/path/to/foxit-pdf-api-mcp-server",
"run",
"foxit-pdf-api-mcp-server"
],
"env": {
"FOXIT_CLOUD_API_HOST": "${env:FOXIT_CLOUD_API_HOST}",
"FOXIT_CLOUD_API_CLIENT_ID": "${env:FOXIT_CLOUD_API_CLIENT_ID}",
"FOXIT_CLOUD_API_CLIENT_SECRET": "${env:FOXIT_CLOUD_API_CLIENT_SECRET}"
}
}
}
} VS Code launches the MCP server as a subprocess through uv, which runs the cloned Python build from its directory. The three ${env:...} references pull credentials from the shell environment instead of hardcoding them in the file, so replace /absolute/path/to/foxit-pdf-api-mcp-server with the path where you cloned the repo and restart VS Code to load the server. Claude Desktop uses the same shape under an mcpServers key and can run the published npm package directly with "command": "npx" and "args": ["-y", "@foxitsoftware/foxit-pdf-api-mcp-server"], so you do not have to clone anything for that host.
Mode 2: In-App Orchestration Setup
Open Foxit PDF Editor, click the AI Assistant tab in the Ribbon, and launch AI Chat to open the right-hand panel. In the bottom left of that panel, click MCP Tools, then click Add MCP Server to configure a new MCP service. Fill in the required fields and save. Once configured, the server appears in the MCP Tools list and its tools activate inside AI Chat.
In both modes, the server reads your Client ID and Client Secret from the environment variables set at startup. No additional gateway configuration is required.
Core Document Operations Agents Can Execute
With the server running, your agent has 30+ callable PDF operations available. Five categories do the heaviest lifting in production pipelines, namely conversion, OCR, structural extraction, merge/split, and document generation via DocGen.
Conversion. An agent receiving an uploaded DOCX triggers the Word-to-PDF creation tool before any downstream step. The output is a standards-compliant PDF that every subsequent operation (OCR, extraction, merge) can work with consistently, eliminating manual conversion and format ambiguity downstream.
OCR. When an agent ingests a scanned or image-only PDF, an OCR call should precede any extraction step. Calling the OCR tool makes the document searchable and text-extractable, which is required for invoice and contract pipelines where key fields sit inside scanned images. The agent calls OCR, waits for the result, and proceeds.
Structural extraction. After OCR, an agent extracts text, tables, and form-field data as structured JSON. Foxit’s structural extraction returns per-page content plus images, giving you a payload that routes cleanly into a BI tool or a second LLM step for analysis or classification. For the full response schema, refer to the Foxit MCP Server developer blog.
Merge and split. An agent assembling a contract package from multiple source documents calls the merge tool with an ordered list of PDFs. An agent pre-processing a large compliance document for parallel LLM analysis calls the split tool to divide it into per-section chunks. Both operations are synchronous and safe to retry on failure.
Document generation via DocGen. For dynamically generated contracts, invoices, or reports, the Foxit Document Generation API accepts a DOCX template with {{dynamic_tags}} and a JSON data payload from a CRM, database, or form response. It returns a finished PDF via POST /document-generation/api/GenerateDocumentBase64. A ready-to-use template lives in the Foxit demos repo if you want to test the call without authoring one. When you upload a DOCX template directly, the 4 MB post-base64 encoding cap applies, so slim templates down by stripping embedded fonts and large images before encoding. The agent supplies the JSON payload at runtime, so a single template can produce thousands of unique documents.
A representative end-to-end pipeline runs like this. An agent ingests a purchase order scan, calls OCR to make it searchable, extracts the structured fields as JSON, merges that data into a contract template via DocGen, and hands the finished PDF off to eSign. Every step is a tool call. The agent reasons about sequencing while the MCP server handles the REST layer.
Agent-Triggered Signing Workflows via the eSign API
Document signing uses a separate REST service, the Foxit eSign API, which has its own credentials and completes the pipeline in three calls. The agent exchanges its credentials for a token, creates a signing folder from the prepared PDF, and dispatches it to the signer.
The eSign API runs on its own host and issues its own Client ID and Client Secret from the eSign portal, separate from the PDF Services credentials the MCP server uses. Export the three eSign variables the script reads before running it:
export FOXIT_ESIGN_BASE_URL="https://na1.foxitesign.foxit.com"
export FOXIT_ESIGN_CLIENT_ID="your_esign_client_id"
export FOXIT_ESIGN_CLIENT_SECRET="your_esign_client_secret" The folder can only be sent if the signer has a signature field, and the simplest way to place one is with Foxit eSign text tags embedded in the document. Download the ready-to-sign sample, agent_agreement.pdf, into your workspace as agreement.pdf. It already carries the tag that maps a signature field to the first party, so the folder is sendable as is. Then run:
import base64
import os
import requests
BASE_URL = os.environ["FOXIT_ESIGN_BASE_URL"] # https://na1.foxitesign.foxit.com
CLIENT_ID = os.environ["FOXIT_ESIGN_CLIENT_ID"]
CLIENT_SECRET = os.environ["FOXIT_ESIGN_CLIENT_SECRET"]
def get_access_token():
resp = requests.post(
f"{BASE_URL}/api/oauth2/access_token",
data={
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"grant_type": "client_credentials",
"scope": "read-write",
},
timeout=30,
)
resp.raise_for_status()
return resp.json()["access_token"]
def route_for_signature(pdf_path, signer):
token = get_access_token()
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
with open(pdf_path, "rb") as fh:
encoded = base64.b64encode(fh.read()).decode()
folder = requests.post(
f"{BASE_URL}/api/folders/createfolder",
headers=headers,
json={
"folderName": "Agent Service Agreement",
"inputType": "base64",
"base64FileString": [encoded],
"fileNames": ["agreement.pdf"],
"processTextTags": True,
"sendNow": False,
"parties": [
{
"permission": "FILL_FIELDS_AND_SIGN",
"firstName": signer["first_name"],
"lastName": signer["last_name"],
"emailId": signer["email"],
"sequence": 1,
}
],
},
timeout=60,
)
folder.raise_for_status()
folder_id = folder.json()["folder"]["folderId"]
sent = requests.post(
f"{BASE_URL}/api/folders/sendDraftFolder",
headers=headers,
json={"folderId": folder_id},
timeout=60,
)
sent.raise_for_status()
return folder_id
if __name__ == "__main__":
fid = route_for_signature(
"agreement.pdf",
{"first_name": "Jordan", "last_name": "Lee", "email": "[email protected]"},
)
print(f"Folder {fid} sent for signature") In this code, you read the eSign credentials from the environment and exchange them for a bearer token at the access_token endpoint, where the request is form-encoded rather than JSON (sending JSON returns a 415). You then base64-encode the local PDF and post it to createfolder with inputType set to base64 so the API reads the base64FileString array, with processTextTags set to True so the document’s text tags become a real signature field, and with sendNow set to False so the folder is created as a draft instead of emailing anyone immediately. The parties array names the signer with FILL_FIELDS_AND_SIGN permission, you read the new id at folder.folderId, and you pass it to sendDraftFolder, which dispatches the draft to the signer. To confirm the result, call GET /api/folders/viewActivityHistory?folderId={id}, which returns the activity log once the folder has been shared (a draft returns logs of a non-shared folder can not be viewed). Foxit uses “folder” throughout the eSign API, never “envelope.”
Compliance is built into the API layer. The Foxit eSign API supports eIDAS, the ESIGN Act, UETA, HIPAA, and GDPR, covering the requirements for agents operating in legal, healthcare, and finance contexts. No separate compliance infrastructure is required.
Production Considerations: Compliance, Cost, and Error Handling
The Foxit PDF Services and eSign APIs are SOC 2 Type II certified, with HIPAA BAA support, GDPR compliance, and CCPA coverage built in. Three additional concerns (credit consumption, idempotency, and async polling) determine whether a pipeline runs reliably at scale.
Credit consumption. The free Developer plan includes 500 credits per year (annual reset, no rollover). The Startup plan is $1,750/year for 3,500 credits. The Business plan is $4,500/year for 150,000 credits. Each successful API call consumes one credit; 4xx and 5xx responses do not. A pipeline processing 50 documents per day burns through those allocations quickly. Monitor real-time usage in the Developer Dashboard before moving to production and size your plan accordingly.
Idempotency. Merge, flatten, and convert calls are safe to retry on failure. Signing-folder creation is not, so gate createfolder behind a state check so the agent doesn’t create duplicate folders and dispatch duplicate signing requests to the same signers.
Async operations. Translation and batch conversion operations are asynchronous, so they return a job ID immediately, and your agent should poll the job status endpoint roughly every three seconds until the status is COMPLETED or FAILED before proceeding to the next step in the chain. Handling these concerns at build time separates a working pipeline from one that generates support tickets.
Common Mistakes
- Dropping the
/api/prefix on eSign calls : Every eSign path lives under/api/, as in/api/folders/createfolder. Omitting it returns a 404 against a docs-style path that does not exist. - Sending the token request as JSON : The
access_tokenendpoint is form-encoded. A JSON body returns415 Unsupported Media Type, so pass the credentials as form data. - Forgetting
inputType: base64: When you send a base64 PDF without it,createfolderrejects the request withfileUrls or base64FileString cannot be empty. URL mode usesfileUrlsandfileNamesinstead. - Sending a signer with no signature field : A
FILL_FIELDS_AND_SIGNparty needs a field. If the document has no text tag like${s:1:______}and you skipprocessTextTags,sendDraftFolderreturnsPlease assign a signature field. Use underscores in the tag placeholder, since an empty placeholder does not create a field. - Expecting a signing tool in the MCP server : The 30+ MCP tools cover PDF operations, not signatures. Signing is the eSign API, a separate service with separate credentials.
Agentic Document Workflows FAQ
What is an agentic document workflow?
An agentic document workflow is an automated pipeline in which an LLM agent executes operations on documents (conversion, OCR, extraction, merging, generation, and signing) without human intervention. Unlike retrieval-augmented generation, which only reads documents, an agentic workflow produces and transforms them using callable tools exposed through a protocol like MCP.
How does the Model Context Protocol (MCP) work with PDF APIs?
MCP defines a standard interface for exposing named, typed functions, called tools, that an LLM agent can discover and invoke. A PDF API MCP server wraps REST endpoints as MCP tools with input schemas and output contracts. The agent selects the right tool based on task context, calls it with structured parameters, and processes the result, without writing any HTTP request logic.
What PDF operations does the Foxit MCP server expose?
The Foxit PDF API MCP Server exposes 30+ tools covering document lifecycle (upload, download, delete), creation (Word, Excel, PowerPoint, HTML, image to PDF), conversion (PDF to multiple formats), manipulation (merge, split, compress, OCR, watermark), security (password management), and forms (JSON import/export).
Does every API call consume a credit even if it fails?
No. Only successful Foxit PDF Services API calls consume credits. Requests that return 4xx or 5xx status codes do not count against your plan. The Developer Dashboard provides real-time usage tracking so you can measure pipeline cost per document before scaling.
How do I trigger document signing from an agent without human intervention?
After preparing a document, your agent calls the Foxit eSign API directly. It authenticates with client_credentials, POSTs to /api/folders/createfolder with the base64 PDF and a parties entry for the signer, then POSTs to /api/folders/sendDraftFolder with the returned folderId. The signing email workflow triggers automatically, and the agent can poll /api/folders/viewActivityHistory for the audit trail.
What compliance standards does the Foxit eSign API meet?
The Foxit eSign API supports eIDAS, the U.S. ESIGN Act, UETA, HIPAA, GDPR, and CCPA. The PDF Services API is SOC 2 Type II certified with HIPAA BAA support. No separate compliance wrappers are required for agents operating in legal, healthcare, or financial contexts.
What is the difference between Mode 1 and Mode 2 in the Foxit MCP architecture?
Mode 1 is a programmatic pipeline where an external LLM agent (Claude Desktop, Cursor, VS Code with GitHub Copilot, or a custom framework) registers the Foxit MCP Server and calls PDF tools automatically. Mode 2 is in-app orchestration where Foxit PDF Editor acts as the MCP Host, connecting to external services like Jira or Salesforce while a knowledge worker reviews the open document.
Why should signing-folder creation be gated behind a state check?
The /api/folders/createfolder endpoint is not idempotent. If an agent retries on failure without a state check, it will create duplicate folders and send duplicate signing requests to the same signers. Merge, flatten, and convert operations are safe to retry; folder creation requires the agent to verify no existing folder was created before calling the endpoint again.
Start Building: Free Developer Access in Minutes
The full pipeline in this guide is available to test today. Activate a free Foxit Developer plan to get your Client ID, Client Secret, access to the API Playground, and 500 credits for real requests. No credit card required.
Clone the open-source MCP server, export the three environment variables, and register the server in Claude Desktop, Cursor, or VS Code with GitHub Copilot. At that point, 30+ PDF tools are callable from your agent with no local SDK to install and no REST plumbing to write.
Once a document is prepared, extend the pipeline into legally binding signatures with the eSign API. The architecture in this guide covers the full document lifecycle from conversion and OCR through extraction, generation, merging, and signing, all in a single agentic document workflow.
Create your free developer account to clone the open-source MCP server and make 30+ PDF tools callable from your agent in minutes, no credit card required.
Create Custom Invoices with Word Templates and Foxit Document Generation

This tutorial shows how to design a Word invoice template with dynamic tokens and use Foxit’s Document Generation API and a short Python script to turn JSON data into polished, ready-to-send PDF invoices.
Manual invoice processing costs between $18 and $26 per invoice, while automated workflows bring that down to $2.50 to $4, according to industry accounts-payable benchmarks. Foxit’s Document Generation API generates well-formatted, dynamic PDF invoices from your existing data, which eliminates manual data entry, formatting errors, and the overhead of per-invoice handling. This tutorial shows you how to build that workflow end to end.
Before You Start
To follow along, grab your free credentials on the developer portal and read the introductory guide to automated document pipelines, which covers the basics of working with the API.
The API works with Microsoft Word templates containing tokens wrapped in double brackets. You pass the template and your data to the API, it replaces those tokens with your data values, and returns a PDF (or Word file, if you prefer).
Prerequisites
This tutorial runs a short Python script, so set up the following before you start:
-
Python 3.12 or newer. The script uses an f-string syntax introduced in Python 3.12.
-
pip for installing packages, plus the built-in venv module for an isolated environment.
-
The requests library for the HTTP call.
-
A code editor such as VS Code with the Python extension. PyCharm, WebStorm, or Sublime Text work too.
-
curl if you want to hit the endpoint from the command line first.
-
A Foxit developer account. Sign up for free to get your Client ID and Client Secret.
Scaffold the workspace in one shot:
mkdir foxit-invoices && cd foxit-invoices
python3 -m venv .venv
source .venv/bin/activate
pip install requests Then export your credentials and host so the script can read them from the environment:
export CLIENT_ID="your_client_id"
export CLIENT_SECRET="your_client_secret"
export HOST="https://na1.fusion.foxit.com" Designing Your Invoice Word Template
Template design in Word is your starting point. An invoice typically includes:
-
The customer receiving the invoice
-
The invoice number and issue date
-
The payment due date
-
A line-item table with product name, quantity, price, and a running total
The Document Generation API places no constraints on template design. Size, alignment, and styling can match your corporate standards, whether that means a simple layout or a polished, branded one. Consider the template below (download link at the end of this article):
The Word template with double-bracket tokens that the Document Generation API replaces at runtime.
Working from the top of the template:
-
{{ invoiceNum }}is the invoice number for the customer. -
{{ today \@ MM/dd/yyyy }}combines a built-in value (today, which represents the current date at API call time) with a date mask that controls the display format. The API docs list all available masks. -
{{ accountName }}is a standard token mapped directly from your data. -
{{ paymentDueDate \@ MM/dd/yyyy }}demonstrates date masks applied to dates from your own data, not just built-ins. -
The line-item table uses one header row and one data row. The dynamic row opens with
{{TableStart:lineItems}}(wherelineItemsis the name of an array in your JSON) and closes with{{TableEnd:lineItems}}. Between those markers sitproduct,qty,price,totalPrice, andROW_NUMBER(a built-in that auto-increments from 1). The\# Currencyformat applied tototalPricerenders it as a formatted currency value. -
A final table row uses
SUM(ABOVE)with currency formatting to total the column.
Structuring Your Invoice Data as JSON
In a production system, invoice data typically comes from a database or e-commerce API. For this demo, it comes from a JSON file:
[
{
"invoiceNum": 100,
"accountName": "Customer Alpha",
"accountNumber": 1,
"paymentDueDate": "August 15, 2025",
"lineItems": [
{ "product": "Product 1", "qty": 5, "price": 2, "totalPrice": 10 },
{ "product": "Product 5", "qty": 3, "price": 9, "totalPrice": 18 },
{ "product": "Product 4", "qty": 1, "price": 50, "totalPrice": 50 },
{ "product": "Product X", "qty": 2, "price": 15, "totalPrice": 30 }
]
},
{
"invoiceNum": 25,
"accountName": "Customer Beta",
"accountNumber": 2,
"paymentDueDate": "August 15, 2025",
"lineItems": [
{ "product": "Product 2", "qty": 9, "price": 2, "totalPrice": 18 },
{ "product": "Product 4", "qty": 1, "price": 8, "totalPrice": 8 },
{ "product": "Product 3", "qty": 10, "price": 25, "totalPrice": 250 },
{ "product": "Product YY", "qty": 3, "price": 15, "totalPrice": 45 },
{ "product": "Product AA", "qty": 2, "price": 100, "totalPrice": 200 }
]
},
{
"invoiceNum": 51,
"accountName": "Customer Gamma",
"accountNumber": 3,
"paymentDueDate": "August 15, 2025",
"lineItems": [
{ "product": "Product 9", "qty": 1, "price": 2, "totalPrice": 2 },
{ "product": "Product 23", "qty": 30, "price": 9, "totalPrice": 270 },
{ "product": "Product ZZ", "qty": 6, "price": 15, "totalPrice": 90 }
]
}
]
The array holds three invoice objects, each matching the structure of the Word template. The accountNumber field has no matching template token, and that’s intentional. Your data can contain fields the template doesn’t use, and accountNumber is used in the Python script to build unique output filenames.
Calling the Document Generation API with Python
The Generate Document endpoint requires your credentials, a base64-encoded version of the template, and your data. The complete demo runs in just over 50 lines of Python:
import os
import requests
import sys
from time import sleep
import base64
import json
from datetime import datetime
CLIENT_ID = os.environ.get('CLIENT_ID')
CLIENT_SECRET = os.environ.get('CLIENT_SECRET')
HOST = os.environ.get('HOST')
def docGen(doc, data, id, secret):
headers = {
"client_id":id,
"client_secret":secret
}
body = {
"outputFormat":"pdf",
"documentValues": data,
"base64FileString":doc
}
request = requests.post(f"{HOST}/document-generation/api/GenerateDocumentBase64", json=body, headers=headers)
return request.json()
with open('invoice.docx', 'rb') as file:
bd = file.read()
b64 = base64.b64encode(bd).decode('utf-8')
with open('invoicedata.json', 'r') as file:
data = json.load(file)
for invoiceData in data:
result = docGen(b64, invoiceData, CLIENT_ID, CLIENT_SECRET)
if result["base64FileString"] == None:
print("Something went wrong.")
print(result)
sys.exit()
b64_bytes = result["base64FileString"].encode('ascii')
binary_data = base64.b64decode(b64_bytes)
filename = f"invoice_account_{invoiceData["accountNumber"]}.pdf"
with open(filename, 'wb') as file:
file.write(binary_data)
print(f"Done and stored to {filename}")
After importing modules and loading credentials from environment variables, the docGen function takes the template, data, and credentials, then posts to the API endpoint. The API returns the rendered PDF as a base64 string.
The main loop reads and base64-encodes the template, loads the JSON file, iterates over each invoice object, calls the API, and writes the result to a uniquely named file using accountNumber. You don’t have to write results to disk at all, since the raw binary data can go straight to an email attachment or a document storage system.
Keep one limit in mind, since the GenerateDocumentBase64 endpoint rejects a .docx payload larger than 4 MB after base64 encoding. If your template approaches that ceiling, compress its images through Word’s Picture Format tools, drop embedded fonts and OLE objects, and split oversized templates into smaller ones.
The rendered PDF invoice the script produces, with all tokens replaced by values from the JSON payload.
Generate Invoice PDF API FAQ
What output formats does the Document Generation API support?
The API returns either a PDF or a DOCX file. You specify the format in the outputFormat field of the request body, as shown in the Python example above.
Can I use live data from a CRM or database instead of a JSON file?
Yes. The documentValues parameter accepts any JSON-serializable object, so you can pull data from Salesforce, a SQL database, a REST endpoint, or any other source and pass it directly to the API. The JSON file in this tutorial is a stand-in for whatever data source you use in production.
Do I need special Foxit software to design the Word template?
No. You design templates in standard Microsoft Word. The API reads the token syntax ({{ }}) from any valid .docx file, with no Foxit desktop software or proprietary editor required.
Is the API compliant with data security requirements?
Foxit’s API platform is SOC 2 Type II certified and supports GDPR and HIPAA compliance, which makes it suitable for invoices that include customer personally identifiable information or regulated financial data. See Foxit’s API security and compliance page for the full list of frameworks.
How do I get started without paying upfront?
The free Developer plan gives you instant access. It covers this tutorial and experimentation with your own templates before committing to a paid tier.
Next Steps
Get free credentials and download the template, Python script, and sample output from the GitHub repository to run this demo yourself.
Two natural extensions follow from here. Foxit Connectors provides 40+ pre-built integrations with platforms like Salesforce, SharePoint, and Google Drive, so you can pull invoice data directly from your CRM or ERP rather than a local JSON file. You can also chain document generation with an eSign step, sending the invoice for client acknowledgment immediately after creation, by passing the generated PDF to the Foxit eSign API.
Programmatic PDF Editing with Foxit PDF Services API: Pages, Merges, Splits, and Flattening at Scale

Manually editing PDFs doesn’t scale when you’re processing hundreds of documents a day. This guide uses working Python and cURL examples to walk through the Foxit PDF Editor API’s core operations, covering page manipulation, merging, splitting, and flattening.
If you’re building document workflows at scale, you already know that manual PDF editing doesn’t cut it. Whether you’re generating contracts, processing invoices, or packaging reports, you need an API that handles page manipulation, merging, splitting, and flattening without breaking under load. Foxit PDF Services API gives you exactly that.
This guide covers the operations you’ll use most: adding and removing pages, merging documents, splitting by page range, and flattening annotations and form fields. Code examples are in Python, but the API is REST-based, so the patterns translate to any stack.
What Is the Foxit PDF Services API?
Foxit PDF Services API is a cloud-based REST API for programmatic PDF manipulation. You send documents and parameters; it returns processed PDFs. No local dependencies, no rendering engine to maintain.
The API handles:
Page insertion, deletion, and reordering
Document merging (combining multiple PDFs into one)
Document splitting (breaking one PDF into multiple outputs)
Flattening (converting annotations, form fields, and overlays into static page content)
Authentication uses API keys. Every request requires client_id and client_secret as separate HTTP request headers.
Why Backend PDF Editing Is an Infrastructure Decision
Teams processing hundreds of PDFs a day have an architecture problem, not a tooling problem.
When your CRM spits out contracts, your ERP generates invoices, and your intake forms produce patient records, the question is how you process these at scale without standing up a server farm or babysitting a library version matrix. At 500+ documents per day, manual desktop tooling is off the table. Per-file scripts that depend on a locally installed library become a liability the moment the library version shifts or a new language target appears.
Two architectural approaches dominate this space: SDK-based libraries and cloud REST APIs. SDK libraries require local installation, version pinning, language-specific bindings, and ongoing maintenance every time a dependency shifts. A cloud REST API requires none of that. Any language that can send an HTTP request can call it, with no package to install, no runtime to configure, and no compatibility matrix to manage.
This guide covers four operations in full: page manipulation (move, rotate, delete, add), merging multiple PDFs into one output, splitting a large document by page count, and flattening annotations into permanently static content. All of it runs via REST calls against the Foxit PDF Services API, authenticated with two request headers and structured around a single four-step loop that applies to every endpoint in the suite.
Prerequisites
Get your environment in order before any code runs. Each tool links to its canonical install page.
venv for project isolation
Node.js 18+ and npm
axiosfor Node examplesA code editor such as VS Code with the Python extension; alternatives include PyCharm, WebStorm, and Sublime Text
Postman (optional, for API exploration alongside the Foxit API Playground)
A Foxit developer account, available at account.foxit.com/site/sign-up with no credit card required and free credits included
Set up your workspace:
mkdir foxit-pdf-tutorial && cd foxit-pdf-tutorial
python3 -m venv .venv
source .venv/bin/activate
pip install requests
Authentication and the Upload → Task → Poll → Download Loop
Authentication
Foxit PDF Services API authenticates via headers. Every request must include client_id and client_secret as separate HTTP request headers, exactly as named: lowercase, underscored. They’re passed individually, as plain strings. Concatenating them, Base64-encoding them, or prefixing them with Bearer are all auth mistakes that look like they should work and don’t.
The base host for the North America environment is https://na1.fusion.foxit.com. Set it once as an environment variable and reuse it:
export BASE_URL="https://na1.fusion.foxit.com"
export CLIENT_ID="your_client_id"
export CLIENT_SECRET="your_client_secret" Every cURL request in this guide uses that pattern:
--header "client_id: $CLIENT_ID"
--header "client_secret: $CLIENT_SECRET"
In Python, read credentials from os.environ and never hardcode them:
import os
import time
import requests
BASE_URL = os.environ["BASE_URL"]
CLIENT_ID = os.environ["CLIENT_ID"]
CLIENT_SECRET = os.environ["CLIENT_SECRET"]
headers = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
} In Node.js:
const axios = require("axios");
const BASE_URL = process.env.BASE_URL;
const headers = {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
}; The Four-Step Loop
Every operation in this API follows the same four steps, regardless of endpoint.
POST /pdf-services/api/documents/uploadwith the file asmultipart/form-data. The response returns an uploaddocumentId.POSTto the relevant endpoint (manipulate, combine, split, or flatten) with the uploaddocumentIdin the request body. The response is HTTP 202 with ataskId.GET /pdf-services/api/tasks/{task-id}until thestatusfield readsCOMPLETED. The completed task response also carries aresultDocumentIdand aprogresspercentage. Task statuses are always uppercase:PENDING,PROCESSING,COMPLETED,FAILED.GET /pdf-services/api/documents/{resultDocumentId}/downloadto retrieve your result. The uploaddocumentIdfrom step one and theresultDocumentIdfrom step three are different identifiers. You download using theresultDocumentId. Swapping these is the most common 4xx error.
Use a-midsummer-nights-dream.pdf to follow along with a known-good file:
curl --location "$BASE_URL/pdf-services/api/documents/upload" \
--header "client_id: $CLIENT_ID" \
--header "client_secret: $CLIENT_SECRET" \
--form 'file=@"a-midsummer-nights-dream.pdf"' Response:
{
"documentId": "abc123-upload-id"
}
A reusable Python polling function with exponential backoff:
def poll_task(task_id: str) -> str:
url = f"{BASE_URL}/pdf-services/api/tasks/{task_id}"
delay = 2
while True:
response = requests.get(url, headers=headers)
response.raise_for_status()
data = response.json()
status = data["status"]
if status == "COMPLETED":
return data["resultDocumentId"]
elif status == "FAILED":
raise RuntimeError(f"Task {task_id} failed: {data}")
time.sleep(delay)
delay = min(delay * 2, 30) Branch on "COMPLETED" and "FAILED" in uppercase. Lowercase strings will silently never match.
The async model is what makes this scalable. A 50-page merge or a batch of 200 splits doesn’t block your thread while it runs. You dispatch the operation call, collect the taskId, and poll on a sensible backoff schedule. At 500+ PDFs per day, that non-blocking pattern keeps your worker pool from saturating.
Page Manipulation: Move, Rotate, Delete, and Add Pages
All page operations go through a single endpoint: POST /pdf-services/api/documents/modify/pdf-manipulate.
{
"documentId": "<upload-document-id>",
"password": "optional",
"config": {
"operations": [{ "type": "OPERATION_TYPE" }]
}
} The config.operations array runs in order. Page indexing is 1-based and adjusts after each step. If you delete page 3 and then reference page 4 in the next operation, that reference points to what was originally page 5 before the delete. Keep that in mind when chaining operations in a single request.
MOVE_PAGES
MOVE_PAGES reorders pages within the document:
{
"type": "MOVE_PAGES",
"pages": [5, 6, 7],
"targetPosition": 1
} targetPosition is 1-based and must not exceed the document’s total page count.
ROTATE_PAGES
ROTATE_PAGES changes page orientation:
{
"type": "ROTATE_PAGES",
"pages": [1, 2, 3],
"rotation": "ROTATE_CLOCKWISE_90"
} Valid rotation values are ROTATE_0, ROTATE_CLOCKWISE_90, ROTATE_180, and ROTATE_COUNTERCLOCKWISE_90.
DELETE_PAGES
DELETE_PAGES removes specific pages:
{
"type": "DELETE_PAGES",
"pages": [8, 9]
} ADD_PAGES
ADD_PAGES appends blank pages to the end of the document:
{
"type": "ADD_PAGES",
"pageCount": 2
}
ADD_PAGES has no insert-at-position parameter; blank pages always go to the end. There’s also no REPLACE_PAGES operation in the current API. Page replacement requires a DELETE_PAGES call on the target pages followed by a separate merge step to bring in the replacement content.
A document intake pipeline for scanned medical records often receives pages in landscape orientation when the archive standard is portrait. The Python call below normalizes pages 1 through 3 of the uploaded file:
def rotate_pages(document_id: str) -> str:
url = f"{BASE_URL}/pdf-services/api/documents/modify/pdf-manipulate"
payload = {
"documentId": document_id,
"config": {
"operations": [
{
"type": "ROTATE_PAGES",
"pages": [1, 2, 3],
"rotation": "ROTATE_CLOCKWISE_90"
}
]
}
}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.json()["taskId"] A legal document workflow that assembles exhibits and needs to move pages 5, 6, and 7 to the front before archiving uses this request body:
{
"documentId": "<upload-document-id>",
"config": {
"operations": [
{
"type": "MOVE_PAGES",
"pages": [5, 6, 7],
"targetPosition": 1
}
]
}
}
All four operation types return HTTP 202 with a taskId. Pass that ID to poll_task, wait for COMPLETED, then download the resultDocumentId.
Merging and Splitting PDFs
Merging Multiple PDFs with pdf-combine
The merge endpoint is POST /pdf-services/api/documents/enhance/pdf-combine.
The request body takes a required documentInfos array. Each entry is a source document object:
{
"documentInfos": [
{ "documentId": "<doc-id-1>" },
{ "documentId": "<doc-id-2>" },
{ "documentId": "<doc-id-3>" }
],
"config": {
"addBookmark": true,
"continueMergeOnError": false,
"retainPageNumbers": false
}
} The config object supports three keys:
addBookmarkgenerates one bookmark per source file in the merged output, useful when the reader needs to navigate by source.retainPageNumberspreserves original page-number labels from each source.continueMergeOnErroris the one that matters most in production. Set it tofalsefor any job where a single bad source must fail the entire batch. Set it totrueonly for best-effort pipelines where partial output is acceptable. Always set it explicitly rather than relying on defaults.
The following code assembles a monthly client report from three sources. Download input.pdf, second.pdf, and input_for_compare.pdf to run this end-to-end:
def upload_file(path: str) -> str:
url = f"{BASE_URL}/pdf-services/api/documents/upload"
with open(path, "rb") as f:
response = requests.post(url, headers=headers, files={"file": f})
response.raise_for_status()
return response.json()["documentId"]
def merge_pdfs(document_ids: list) -> str:
url = f"{BASE_URL}/pdf-services/api/documents/enhance/pdf-combine"
payload = {
"documentInfos": [{"documentId": doc_id} for doc_id in document_ids],
"config": {
"addBookmark": True,
"continueMergeOnError": False,
"retainPageNumbers": False
}
}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.json()["taskId"]
# Upload all three source files, collect their documentIds
doc_ids = [
upload_file("input.pdf"),
upload_file("second.pdf"),
upload_file("input_for_compare.pdf")
]
# Merge and download
merge_task_id = merge_pdfs(doc_ids) # POST combine → taskId
merge_result_id = poll_task(merge_task_id) # poll → resultDocumentId
Once poll_task returns a resultDocumentId, pass it to your download function.
Splitting a PDF by Page Count with pdf-split
The split endpoint is POST /pdf-services/api/documents/modify/pdf-split. The pdf- prefix is required and matches the naming convention used by pdf-combine, pdf-manipulate, and pdf-flatten.
The request body is minimal:
{
"documentId": "<upload-document-id>",
"pageCount": 10
} pageCount specifies how many pages go into each output file. The last file gets whatever pages remain. The current API exposes only this page-count split mode. File-size-based and bookmark-based splitting are not in the published reference.
curl --location "$BASE_URL/pdf-services/api/documents/modify/pdf-split" \
--header "client_id: $CLIENT_ID" \
--header "client_secret: $CLIENT_SECRET" \
--header 'Content-Type: application/json' \
--data '{
"documentId": "<upload-document-id>",
"pageCount": 10
}' The response returns a taskId. When polling reaches COMPLETED, the result contains multiple output files, one per split chunk.
Flattening Annotations: Making PDF Changes Permanent
Flattening merges annotations, form fields, and layers into the page content itself. The output is a single static PDF where no markup can be toggled, filled, or removed. This is a one-way transformation with no undo.
The endpoint is POST /pdf-services/api/documents/modify/pdf-flatten.
The request body is intentionally minimal:
{
"documentId": "<upload-document-id>"
} No flags for selective annotation or form-field handling are exposed in the current API reference. The operation flattens both annotations and form fields together in a single pass.
When to Flatten a PDF
Flattening is required in three situations:
Archiving a signed form. Without flattening, a technically capable recipient can still manipulate form fields in most PDF viewers, even after signature. Flattening removes that possibility entirely.
Print production. Annotation layers render differently across print drivers and produce visible artifacts in the final output. Flattening eliminates the variable.
Compliance workflows under HIPAA or legal hold. Documents at rest must be immutable. A live form field fails that requirement.
curl --location "$BASE_URL/pdf-services/api/documents/modify/pdf-flatten" \
--header "client_id: $CLIENT_ID" \
--header "client_secret: $CLIENT_SECRET" \
--header 'Content-Type: application/json' \
--data '{ "documentId": "<upload-document-id>" }' Flattening does not encrypt the document or apply password protection. If your workflow requires both, chain a pdf-protect call after flattening using POST /pdf-services/api/documents/security/pdf-protect, passing the resultDocumentId from the completed flatten task as the documentId input for the protect call and the password under config.userPassword. The result of one operation becomes the input of the next.
{
"documentId": "<flatten-result-document-id>",
"config": {
"userPassword": "<password>"
}
} In this body, you point documentId at the flatten task’s resultDocumentId and set the open password under config.userPassword. The password lives inside the config object, not at the top level. A top-level password key is accepted by the request but the task then fails with a parameter error, so nest it under config.
Building a Multi-Step PDF Editing Pipeline for High Volume
Chaining Operations with resultDocumentId
Every completed task returns a resultDocumentId. That ID becomes the documentId for the next operation. The full chain: upload, then operation A, then poll until A reaches COMPLETED, then operation B using A’s resultDocumentId, then poll until B reaches COMPLETED, then download B’s resultDocumentId.
A complete flatten-then-protect pipeline, with inline comments showing which ID type is active at each step:
import os
import time
import requests
BASE_URL = os.environ["BASE_URL"]
CLIENT_ID = os.environ["CLIENT_ID"]
CLIENT_SECRET = os.environ["CLIENT_SECRET"]
headers = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
}
def upload_file(path: str) -> str:
url = f"{BASE_URL}/pdf-services/api/documents/upload"
with open(path, "rb") as f:
response = requests.post(url, headers=headers, files={"file": f})
response.raise_for_status()
return response.json()["documentId"]
def poll_task(task_id: str) -> str:
url = f"{BASE_URL}/pdf-services/api/tasks/{task_id}"
delay = 2
while True:
response = requests.get(url, headers=headers)
response.raise_for_status()
data = response.json()
status = data["status"]
if status == "COMPLETED":
return data["resultDocumentId"]
elif status == "FAILED":
raise RuntimeError(f"Task failed: {data}")
time.sleep(delay)
delay = min(delay * 2, 30)
def flatten(document_id: str) -> str:
url = f"{BASE_URL}/pdf-services/api/documents/modify/pdf-flatten"
response = requests.post(url, json={"documentId": document_id}, headers=headers)
response.raise_for_status()
return response.json()["taskId"]
def protect(document_id: str, password: str) -> str:
url = f"{BASE_URL}/pdf-services/api/documents/security/pdf-protect"
payload = {"documentId": document_id, "config": {"userPassword": password}}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.json()["taskId"]
def download(document_id: str, output_path: str):
url = f"{BASE_URL}/pdf-services/api/documents/{document_id}/download"
response = requests.get(url, headers=headers)
response.raise_for_status()
with open(output_path, "wb") as f:
f.write(response.content)
# Pipeline: upload → flatten → protect → download
upload_doc_id = upload_file("signed-form.pdf") # documentId
flatten_task_id = flatten(upload_doc_id) # taskId
flatten_result_id = poll_task(flatten_task_id) # resultDocumentId
protect_task_id = protect(flatten_result_id, os.environ["PDF_PASSWORD"]) # taskId
protect_result_id = poll_task(protect_task_id) # resultDocumentId
download(protect_result_id, "final-protected.pdf") Three distinct IDs flow through this pipeline: the upload documentId, the taskId returned by each operation call, and the resultDocumentId returned by each completed task. Confusing any two of these produces a 4xx.
Batch Polling for High-Volume Jobs
For a single document, sequential polling works fine. For a batch of thousands, polling each task one at a time becomes the bottleneck. The pattern that scales is to dispatch first, then consolidate.
Upload all source files in parallel and collect their documentIds. Dispatch all operation calls in parallel and collect their taskIds. Then run a single consolidated polling loop that iterates over all taskIds, checks each status, and branches on COMPLETED or FAILED per task. Your thread never blocks waiting for one document while others are already done, and it processes results as they arrive.
The multi.py sample in the foxitsoftware/developerapidemos repository demonstrates this exact dispatch-then-consolidate shape, including the resultDocumentId handoff across operations.
Common Mistakes and Troubleshooting
These are the integration errors that come up most often.
Polling too aggressively. Start at a two-second interval and double it up to a ceiling of around 30 seconds. Tight-looping the /tasks/{task-id} endpoint burns rate-limit budget and produces 429s that slow the whole pipeline down.
Treating FAILED as transient. A FAILED status means the job encountered a specific error. Read the task response body, surface the reason, and branch on it. Retrying indefinitely on FAILED produces the same failure indefinitely.
Downloading before COMPLETED. Some integrations skip the status check and call the download endpoint immediately after the operation response. The result is a partial or empty file. Always confirm status == "COMPLETED" before hitting the download endpoint.
Mixing up the three IDs. All three appear in the same code block so they can’t be confused:
upload_doc_id = upload_file("input.pdf") # documentId → input to operation endpoints
task_id = flatten(upload_doc_id) # taskId → input to the polling endpoint
result_doc_id = poll_task(task_id) # resultDocumentId → input to the download endpoint
download(result_doc_id, "output.pdf") The download endpoint takes the resultDocumentId, not the upload documentId or the taskId.
Task status casing. The polling endpoint returns PENDING, PROCESSING, COMPLETED, and FAILED in uppercase. Branching on lowercase "completed" will silently never match and your loop will run forever.
continueMergeOnError semantics. Setting this to true lets the merge skip a failing source and continue. Setting it to false aborts the entire batch if any source fails. In production, always set this explicitly.
Retrying 4xx responses. Retry on 5xx errors and timeouts. A 400 or 401 will return the same 4xx until you fix the request, so don’t retry them.
Auth header format. client_id and client_secret are separate headers, lowercase with underscores, passed individually. They’re not concatenated, Base64-encoded, or Bearer-prefixed.
pdf-flatten does not encrypt. Flattening makes a document’s content static but doesn’t restrict access to the file. If your compliance workflow requires both, chain a pdf-protect call after the flatten step using the flatten task’s resultDocumentId as the next documentId input.
PDF Editor API FAQ
What is the Foxit PDF Services API used for?
The Foxit PDF Services API is a cloud-based REST API for programmatic PDF manipulation at scale, covering page manipulation, document merging, splitting, and annotation flattening. Any language that can send HTTP requests can use it without installing local dependencies.
How do you merge multiple PDFs using the Foxit API?
Upload each source file to get a documentId, then POST all documentIds in a documentInfos array to POST /pdf-services/api/documents/enhance/pdf-combine. Poll the returned taskId until status is COMPLETED, then download the resultDocumentId.
What is PDF flattening and when should you use it?
PDF flattening converts interactive elements (form fields, annotations, and overlays) into static page content that cannot be edited. Use it when archiving signed forms, preparing documents for print production, or meeting compliance requirements such as HIPAA that mandate immutable records at rest.
What is the difference between documentId and resultDocumentId in the Foxit API?
documentId is returned after uploading a file and is used as input to operation endpoints. resultDocumentId is returned when a task reaches COMPLETED status and is used to download the processed file. They are different identifiers; using one where the other is expected produces a 4xx error.
Does the Foxit PDF Services API support splitting PDFs by custom page ranges?
The current pdf-split endpoint splits by a fixed pageCount value, producing equal-sized chunks with the last file containing remaining pages. File-size-based and bookmark-based splitting are not available in the published API reference.
How should you handle errors in the Foxit PDF Services API?
Retry on 5xx errors and timeouts using exponential backoff. Do not retry 400 or 401 responses, since those indicate a problem with the request itself. Read the response body on FAILED task status and branch on the specific error rather than retrying blindly.
Getting Started with Foxit PDF Services API
Create a free developer account. No credit card required, and free credits are included.
Once you have your credentials, open the Foxit API Playground. Start with pdf-combine. Download input.pdf and second.pdf, upload both to get two documentIds, POST the merge request with the JSON body from the Merging section, and poll for the result. The full cycle, authentication through download, takes under ten minutes on a first attempt.
If you’re evaluating this for production volume, check the current plan options and credit pools. Plans range from the free developer tier up through Startup and Business options with larger shared-credit allocations.
For the authoritative reference on every endpoint and parameter covered in this guide, the Foxit PDF Services API documentation is your starting point. The GitHub samples repository has complete Python and Node.js examples you can clone and run immediately, including the multi-step pipeline pattern this guide covers.
Embedded Signing with the Foxit eSign API: From Envelope Creation to In-App iFrame in One Session

This guide walks through the Foxit eSign API end to end: authenticate, create a folder, generate an embedded session URL, and render the signing experience in an iFrame your users never leave.
Most embedded signing tutorials hand you a three-step abstraction: get a token, create an envelope, open a recipient view. The implementation details live somewhere else, usually mapped to a different API’s object model that doesn’t quite match what you’re working with.
This tutorial covers the Foxit eSign API embedded signing mechanics from start to finish. Authenticate once, create a “folder” (Foxit’s term for what other platforms call an envelope), receive an embedded session URL in that same response, and render it in an iFrame your users never leave. No separate field-placement API call, no client-side SDK to install.
What You’ll Build
By the end of this guide, you’ll have a working embedded signing session: a PDF loaded into your app via iFrame, signature fields defined by Text Tags, a webhook handler that verifies completion events, and a post-signing redirect that keeps users inside your product. Every step runs against the Foxit eSign sandbox with credentials you can generate in under five minutes.
1. Prerequisites and Auth Setup
Before any code runs, make sure you have the following installed and configured:
venv for project isolation
The requests library
A code editor: VS Code with the Python extension is a solid choice. PyCharm, Sublime Text, and JetBrains Fleet work equally well.
A Foxit eSign developer account, available at account.foxit.com/site/sign-up with no credit card required
Set up your workspace:
mkdir foxit-esign-tutorial && cd foxit-esign-tutorial
python3 -m venv .venv && source .venv/bin/activate
pip install requests The Foxit eSign API Is a Separate Portal from PDF Services
Developers who already use Foxit tools hit this wall first: the Foxit eSign API runs at its own base host, with its own API Key and API Secret. These credentials don’t work with the client_id and client_secret from the PDF Services developer portal at developer-api.foxit.com. The eSign documentation lives at developersguide.foxitesign.foxit.com, separate from docs.developer-api.foxit.com. The API Playground handles PDF Services sandbox testing; eSign sandbox calls go to the eSign portal directly.
The NA environment base host is https://na1.foxitesign.foxit.com. All subsequent code samples reference this as {HOST_NAME}.
Generating an OAuth 2.0 Access Token
Set your credentials as environment variables before running anything:
export FOXIT_ESIGN_CLIENT_ID="your_api_key"
export FOXIT_ESIGN_CLIENT_SECRET="your_api_secret"
Then generate a Bearer token via the OAuth 2.0 client credentials flow:
curl -X POST "https://na1.foxitesign.foxit.com/api/oauth2/access_token" \
-d "client_id=$FOXIT_ESIGN_CLIENT_ID" \
-d "client_secret=$FOXIT_ESIGN_CLIENT_SECRET" \
-d "grant_type=client_credentials" \
-d "scope=read-write" The response carries an access_token field. Pass it as Authorization: Bearer {token} on every subsequent call, and store it server-side so your credentials never travel to the browser.
2. Creating an Envelope Programmatically with /api/folders/createfolder
Foxit eSign calls what other platforms call an “envelope” a folder. If you’re coming from DocuSign or PandaDoc, that naming difference will catch you on the first read of the docs. The endpoint is POST {HOST_NAME}/api/folders/createfolder. A template-based variant also exists at POST {HOST_NAME}/api/templates/createFolder (note the camelCase) for assembling envelopes from saved templates. This tutorial focuses on the direct document-upload flow.
Defining Signature Fields with Text Tags
Foxit eSign reads signature field definitions from the PDF itself at upload time. You embed them as Text Tags directly in the document, and the API parses the tags on ingest and converts them to interactive fields. The tag syntax follows this structure: ${fieldtype:party_number:required:field_name:width}. Here, y marks a field as required and n marks it as optional. The party number maps to the signing sequence for that recipient. Width is expressed as underscores.
A minimal set covering the four field types required for a real signing flow:
${s:1: } # signature field, party 1
${i:1:______} # initials field, party 1
${d:1:n::____} # optional date field, party 1
${t:1:y:Full_Name:__________} # required text field, party 1, named "Full_Name" The full set of supported tag types includes signfield (or s), initialfield (or i), datefield (or d), textfield (or t), textboxfield (or tb), checkboxfield (or c), radiobuttonfield (or rb), securedfield (or sc), attachmentfield (or a), imagefield (or img), accept (or ab), decline (or db), payfield (or pf), and formulafield (or ff).
To hide tags in production, set the tag font color to match the page background color. Foxit eSign converts the tags to fields but does not strip them from the rendered document.
Use this sample PDF with Text Tags pre-embedded to follow along. It includes a signature field, initials, a date field, and a text input, all mapped to party 1.
Submitting the createfolder Request
You can supply the PDF two ways against the same endpoint. In URL mode you pass a fileUrls array of publicly reachable PDF links alongside a matching fileNames array. In base64 mode you set "inputType": "base64" and pass a base64FileString array of base64-encoded PDF bytes, again with a matching fileNames array. The API rejects a request that supplies neither, returning fileUrls or base64FileString cannot be empty.
One parameter is easy to miss and breaks the whole flow when omitted. Set processTextTags to true so the API parses the Text Tags embedded in the PDF and converts them into interactive fields. Leave it out and the folder still gets created successfully, but the tags stay inert literal text on the page, the signing UI reports zero required fields, and a signer can reach Finish without ever signing. If your source PDF carries native AcroForm fields instead of Text Tags, the companion processAcroFields flag handles those.
URL-based submission via cURL, pointing at the hosted sample PDF:
curl -X POST "https://na1.foxitesign.foxit.com/api/folders/createfolder" \
-H "Authorization: Bearer $FOXIT_ESIGN_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"folderName": "Service Agreement",
"sendNow": false,
"processTextTags": true,
"createEmbeddedSigningSession": true,
"embeddedSignersEmailIds": ["[email protected]"],
"fileUrls": ["https://github.com/lucienchemaly/foxit-demo-templates/raw/main/esign/sample-text-tags.pdf"],
"fileNames": ["sample-text-tags.pdf"],
"parties": [
{
"firstName": "Alex",
"lastName": "Rivera",
"emailId": "[email protected]",
"permission": "FILL_FIELDS_AND_SIGN",
"sequence": 1
}
]
}'
In this request you ask Foxit eSign to fetch the tagged PDF from its public URL, hold the folder as a draft instead of emailing it by setting sendNow to false, and mint an embedded signing session for the party identified in embeddedSignersEmailIds. The single signer is defined in the parties array with a name, email, the FILL_FIELDS_AND_SIGN permission, and a signing sequence.
Base64 upload via Python, which avoids needing a public URL by sending the file bytes inline:
import os
import base64
import requests
HOST = "https://na1.foxitesign.foxit.com"
TOKEN = os.environ["FOXIT_ESIGN_ACCESS_TOKEN"]
with open("sample-text-tags.pdf", "rb") as pdf:
encoded = base64.b64encode(pdf.read()).decode()
payload = {
"folderName": "Service Agreement",
"sendNow": False,
"processTextTags": True,
"inputType": "base64",
"base64FileString": [encoded],
"fileNames": ["sample-text-tags.pdf"],
"createEmbeddedSigningSession": True,
"embeddedSignersEmailIds": ["[email protected]"],
# Recipient defined in the body overrides any tag-defined party
"parties": [
{
"firstName": "Alex",
"lastName": "Rivera",
"emailId": "[email protected]",
"permission": "FILL_FIELDS_AND_SIGN",
"sequence": 1,
}
],
}
response = requests.post(
f"{HOST}/api/folders/createfolder",
headers={"Authorization": f"Bearer {TOKEN}"},
json=payload,
)
print(response.json())
In this code, you read the local PDF, base64-encode its bytes, and place the result inside the base64FileString array with inputType set to base64 so the API knows to decode it rather than fetch a URL. The rest of the payload mirrors the cURL example, sending the folder as a draft and requesting an embedded session for the listed signer, after which you print the JSON response to read back the folder.folderId and the session URL. When both the PDF’s Text Tags and the API body define recipient parties, the body values take precedence, so you can reuse a tagged PDF template and swap in different signers at request time without touching the document.
3. Generating the Embedded Signing Session and Rendering the iFrame
Setting createEmbeddedSigningSession: true in the createfolder body, paired with an embeddedSignersEmailIds array naming which parties sign in your app, gives you a signed session URL in the same response. No second API call, no separate “recipient view” endpoint. The response carries an embeddedSigningSessions array, and each entry holds the signer email in emailIdOfSigner, the raw token in embeddedToken, and the ready-to-render link in embeddedSessionURL. That URL follows this format, where eetid is the URL-encoded embedded token:
https://{HOST_NAME}/embedded/embeddedsign?eetid={URL-ENCODED-EMBEDDED-TOKEN}
If you omit embeddedSignersEmailIds, the API returns email id of embedded signer(s) not submitted, so always list the embedded signers explicitly. For multi-party workflows you can set createEmbeddedSigningSessionForAllParties: true so every recipient signs in an embedded session rather than over email. When you need each signer’s live URL, request it per signer through the regenerate endpoint described below.
The full lifecycle runs from token request through webhook delivery:
Injecting the Session URL into an iFrame
The signing UI renders entirely inside the iFrame with no additional JavaScript library required.
function launchSigningSession(embeddedSessionURL) {
const iframe = document.createElement("iframe");
// These five sandbox permissions are the minimum required for the signing UI
iframe.setAttribute(
"sandbox",
"allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation",
);
iframe.src = embeddedSessionURL;
iframe.style.width = "100%";
iframe.style.height = "700px";
iframe.style.border = "none";
iframe.onload = function () {
console.log("Signing session ready");
};
document.getElementById("signing-container").appendChild(iframe);
} The sandbox attribute matters here. Remove allow-popups or allow-top-navigation and the signing UI breaks in ways that produce no obvious error. The five attributes above are the minimum viable set. Don’t strip them without testing the complete signing flow.
To verify the flow without wiring this into your app first, download the ready-to-run iFrame test page from the demo repo, open it in a browser, paste the embeddedSessionURL from your createfolder response into the input box, and click Load. It applies the same five sandbox permissions shown above. A correctly tagged document renders with the signing controls active, as shown below.
The sample document loaded in the iFrame with processTextTags enabled. The header shows “Required Fields Left: 2” and a “Next Required Field” button, confirming the Text Tags became interactive fields. If that counter reads zero or the page shows the raw ${...} tag text with no input boxes, recheck that processTextTags was set to true on the createfolder request.
Session URLs are short-lived. Generate the URL at request time and pass it directly to the client. Don’t cache it. If a user returns to an incomplete workflow after the session expires, call POST {HOST_NAME}/api/embedded/regenerateEmbeddedSigningSession with the folder ID and the signer email to get a fresh URL. The response mirrors a single embedded session entry, returning emailIdOfSigner, embeddedToken, and the new embeddedSessionURL.
4. White-Labeling the Signing Experience
Foxit eSign exposes branding control at several levels. You can apply a custom logo to the signing UI and outgoing notification emails, set application colors to match your product’s visual design, and configure a personalized sender name so recipients see your company name rather than a generic Foxit sender identity.
For logo and color configuration, manage these settings through the eSign Portal’s branding section. The portal publishes canonical limits on file size and supported formats. Check the branding settings in your account for current specifications rather than relying on numbers printed here that may have changed.
Configuring Post-Signing Redirect URLs
Custom redirect URLs keep users inside your application after they sign, decline, defer, or hit an error. Pass them as parameters in the createfolder body:
payload = {
"folderName": "Service Agreement",
"sendNow": False,
"processTextTags": True,
"createEmbeddedSigningSession": True,
"embeddedSignersEmailIds": ["[email protected]"],
# Return the user to your confirmation page after a successful signature
"signSuccessUrl": "https://app.example.com/contracts/signed",
# Return to a dedicated page when the signer declines
"signDeclineUrl": "https://app.example.com/contracts/declined",
# Return here when the signer chooses to finish later
"signLaterUrl": "https://app.example.com/contracts/later",
# Return here if the signing session errors out
"signErrorUrl": "https://app.example.com/contracts/error",
"parties": [ ... ],
"fileUrls": [ ... ],
"fileNames": [ ... ],
} Foxit eSign appends two query parameters to your success URL when it redirects, namely folderId for the folder that was signed and event, whose value is signing_success on a completed signature or signing_declined when the signer declines. Without these URLs, signers land on Foxit’s default confirmation page. With them, your application controls the entire post-signing navigation experience.
Tailoring Signer Instructions for Regulated Industries
Regulated workflows often need specific disclosure language in front of signers, which matters for ESIGN Act or eIDAS compliance scenarios where your legal team controls the wording. The createfolder body accepts a signerInstructionId and a confirmationInstructionId that reference instruction templates configured in your account, and you can drop explicit accept and decline button fields into the document itself using the accept (or ab) and decline (or db) Text Tag types. The eSign Developers Guide at developersguide.foxitesign.foxit.com documents these parameters.
5. Handling Webhook Callbacks for Completion Events
Foxit eSign fires HTTP POST requests to your registered endpoint when these lifecycle events occur: folder_sent, folder_viewed, folder_signed, folder_cancelled, folder_completed, folder_executed, and folder_deleted. Register your callback URL in the eSign Portal under API Settings. Make sure the endpoint is publicly reachable over HTTPS before you start testing with the sandbox.
Verifying the Webhook Signature
Every webhook POST includes a signature query parameter. It’s a base64-encoded HMAC-SHA-256 digest of the raw request body, computed using your webhook secret. Recompute the same digest server-side and compare before doing any processing. An unverified webhook is an open door.
import os
import hmac
import hashlib
import base64
from flask import Flask, request, abort
app = Flask(__name__)
WEBHOOK_SECRET = os.environ["FOXIT_ESIGN_WEBHOOK_SECRET"].encode()
@app.route("/webhook/foxit", methods=["POST"])
def foxit_webhook():
# Step 1: Pull the signature from the query string
received_sig = request.args.get("signature", "")
# Step 2: Recompute HMAC-SHA-256 over the raw request body
raw_body = request.get_data()
computed_sig = base64.b64encode(
hmac.new(WEBHOOK_SECRET, raw_body, hashlib.sha256).digest()
).decode()
# Step 3: Constant-time comparison guards against timing attacks
if not hmac.compare_digest(received_sig, computed_sig):
abort(403)
payload = request.json
event_name = payload.get("event_name")
folder_id = payload.get("data", {}).get("folder", {}).get("folderId")
if event_name in ("folder_completed", "folder_executed"):
handle_completion(folder_id)
elif event_name == "folder_cancelled":
handle_cancellation(folder_id)
# A non-2xx response triggers Foxit's automatic retry logic.
# Return 200 once verification and basic parsing succeed.
return "", 200
The payload structure is consistent across all events, carrying a top-level event_name, an event_date timestamp, and a data object whose folder field holds the full folder record. The folder identifier lives at data.folder.folderId, alongside the rest of the envelope-level metadata such as folderName and folderStatus.
Downstream Actions Triggered from folder_completed
When folder_completed or folder_executed fires, two actions cover the majority of production workflows. Fetch the signed document via the documents endpoint using the folder ID and store the result in your document storage layer. For contracts that require sequential agreements (a master services agreement followed by a statement of work, for example), fire the next createfolder call as part of the completion handler.
Audit history is available programmatically via GET {HOST_NAME}/api/folders/viewActivityHistory?folderId={FOLDER_ID}, which returns the full signing log once a folder has been shared or sent. This is a GET-only endpoint, and a folder still in DRAFT returns logs of a non-shared folder can not be viewed.
6. Common Mistakes and Troubleshooting
Text Tag Syntax Breaks on Copy-Paste
Smart-quote autocorrect in Word, Google Docs, and many other editors replaces straight ASCII brackets and quote characters with typographic equivalents. Tag parsing fails silently when this happens. Always paste tags into a plain-text editor first and verify the bracket characters are straight ASCII. The eSign Developers Guide writes every field-type notation in lowercase, such as signfield or s and textfield or t, so author your tags in lowercase to match the documented syntax rather than experimenting with capitalized variants.
Visible Text Tags Reaching Production
Foxit eSign converts embedded tags to fields but does not remove them from the document. If you ship a PDF without setting the tag text color to match the page background, signers see the raw ${...} strings on the page. Build the color-hide step into your PDF preparation pipeline before it becomes a support ticket.
Body-Level parties Overriding Tag-Defined Recipients
Tags define field layout and recipient assignment and must be embedded in the PDF itself, while recipient definitions in the API request body override tag-defined recipient metadata. If you’re seeing the wrong signer name or email appear, check whether a body-level parties definition is overriding the tag.
Expired Session URLs
Embedded session URLs are short-lived. Caching one and reusing it on the next page load will fail. Call POST {HOST_NAME}/api/embedded/regenerateEmbeddedSigningSession with the folder ID and signer email each time a returning user needs access to an incomplete session.
Over-Restrictive sandbox on the iFrame
The five required sandbox permissions are allow-scripts, allow-same-origin, allow-forms, allow-popups, and allow-top-navigation. If the UI loads but behaves unexpectedly, check your sandbox attributes first.
Credential Confusion Between eSign and PDF Services
The API Key and API Secret from the eSign Portal are specific to the eSign API, and the OAuth 2.0 flows also differ between the two. Using PDF Services credentials against the eSign /api/oauth2/access_token endpoint returns an authentication error. Keep the two credential sets separate and named clearly in your environment configuration.
Skipping Webhook Signature Verification
Always verify the signature query parameter before processing any payload. Return a 200-class status code once verification and basic parsing succeed, because a non-2xx response causes Foxit to retry delivery, which can create duplicate processing if your handler is not idempotent.
Embedded Signing FAQ
Can I regenerate an expired embedded signing session?
Yes. Call POST {HOST_NAME}/api/embedded/regenerateEmbeddedSigningSession with the folder ID and signer email. Foxit eSign returns a fresh embeddedSessionURL for the same envelope without resetting the signing state.
Do I need a separate Foxit account if I’m already using Foxit PDF Services?
Yes. The Foxit eSign API operates from a separate portal at na1.foxitesign.foxit.com with its own credentials. The two portals don’t share API keys, secrets, or authentication tokens.
Can I use an existing template instead of uploading a PDF?
Yes. Use POST {HOST_NAME}/api/templates/createFolder to assemble the envelope from a saved template rather than a raw document upload.
Does the embedded signing session work on mobile browsers?
Yes. The iFrame renders responsively on modern mobile browsers without additional configuration.
Is the audit trail accessible programmatically?
Yes. GET {HOST_NAME}/api/folders/viewActivityHistory?folderId={FOLDER_ID} returns the full signing activity log for any shared or sent envelope, including timestamps for each event. A folder still in DRAFT has no shared history to return.
What is the difference between folder_completed and folder_executed?
Both events signal that the folder has been completed with all required parties’ signatures, and the eSign Developers Guide describes them in the same terms, each delivering the folder record in data.folder. Listen for either to trigger downstream retrieval of the signed document, and make your handler idempotent so receiving both for the same folder does not double-process it.
Next Step
Activate your free Foxit eSign developer account at account.foxit.com/site/sign-up, no credit card required. Generate your OAuth token, fire a POST /api/folders/createfolder request with createEmbeddedSigningSession: true against the sandbox, and verify the returned URL loads in a local iFrame. From account creation to a working embedded signing session takes under 30 minutes.
DOCX to PDF via the Foxit PDF Services API: Python and cURL Walkthrough

This walkthrough covers the full DOCX-to-PDF flow on the Foxit PDF Services API with runnable Python and cURL for each call.
Automated document pipelines demand conversion tooling that accepts a file, queues a job, and returns clear status at every step. The Foxit PDF Services API gives you exactly that: a four-endpoint async flow covering upload, convert, poll, and download. Each step returns a typed payload, the task model exposes four explicit states with a numeric progress field, and error codes map cleanly to distinct recovery paths.
This tutorial walks through every step of that flow in Python 3 with the requests library, plus cURL equivalents for each call. You’ll have a runnable convert.py script you can drop into a pipeline today.
Prerequisites
Before you run a single line of this tutorial, get the following in place. Each item links to its canonical install or setup guide.
- Python 3.8 or newer — verify with
python3 --version. The script uses only standard library modules plus one external package, so any modern 3.x will do. - pip — bundled with Python 3.4+. Verify with
python3 -m pip --version. - A virtual environment — isolates project dependencies so they don’t collide with system Python or other projects. See the venv tutorial for platform-specific activation commands.
- The
requestslibrary — the only third-party dependency in this walkthrough. Installed inside the venv below. - A code editor — Visual Studio Code with the Python extension is a solid default, but PyCharm, Sublime Text, or any editor you like will work.
- cURL — pre-installed on macOS and most Linux distros. Windows users can install from the official site or use WSL.
- A Foxit Developer account — register for free (no credit card required). The Foxit Developer Portal provisions a default application with your
CLIENT_IDandCLIENT_SECRETimmediately after signup.
Set up the project workspace:
mkdir foxit-docx-to-pdf && cd foxit-docx-to-pdf
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install requests Export your credentials as environment variables so the script never sees them as hardcoded strings:
export CLIENT_ID=your_client_id_here
export CLIENT_SECRET=your_client_secret_here import os
CLIENT_ID = os.environ.get("CLIENT_ID")
CLIENT_SECRET = os.environ.get("CLIENT_SECRET")
BASE_URL = "https://na1.fusion.foxit.com" All four API calls go to https://na1.fusion.foxit.com. The developer portal also offers a live sandbox and pre-built Postman collections if you want to verify calls in a GUI before scripting.
For a sample DOCX to work with right away, download input.docx directly from the foxitsoftware/developerapidemos GitHub repository and save it to your working directory.
How the Auth Model Works
The Foxit PDF Services API authenticates through named request headers. Pass client_id and client_secret directly on every call:
headers = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
} json_headers = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"Content-Type": "application/json",
} The API expects the raw key/secret pair in those named headers. Wrapping credentials in an Authorization: Bearer header instead returns 400, since the required client_id and client_secret headers are missing.
Step 1 and Step 2: Upload the DOCX and Initiate Conversion
Step 1: Upload the DOCX File
POST /pdf-services/api/documents/upload accepts the file as multipart/form-data and returns a documentId that every subsequent call needs.
import requests
def upload_doc(file_path: str) -> str:
url = f"{BASE_URL}/pdf-services/api/documents/upload"
headers = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
}
with open(file_path, "rb") as f:
files = {"file": (os.path.basename(file_path), f)}
response = requests.post(url, headers=headers, files=files)
response.raise_for_status()
return response.json()["documentId"] cURL equivalent:
curl -X POST "https://na1.fusion.foxit.com/pdf-services/api/documents/upload" \
-H "client_id: $CLIENT_ID" \
-H "client_secret: $CLIENT_SECRET" \
-F "[email protected]" Uploaded files carry a 100 MB cap and are automatically deleted after 24 hours. A documentId scopes to the current upload session and expires with the source file, so treat it as ephemeral.
Step 2: Initiate the PDF Conversion
POST /pdf-services/api/documents/create/pdf-from-word accepts a JSON body with the documentId and returns a taskId. The API handles 10 to 10,000+ conversions per day across production pipelines, queuing jobs asynchronously to avoid blocking the connection until the PDF is ready.
import json
def convert_to_pdf(document_id: str) -> str:
url = f"{BASE_URL}/pdf-services/api/documents/create/pdf-from-word"
headers = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"Content-Type": "application/json",
}
payload = {"documentId": document_id}
response = requests.post(url, headers=headers, data=json.dumps(payload))
response.raise_for_status()
return response.json()["taskId"] cURL equivalent:
curl -X POST "https://na1.fusion.foxit.com/pdf-services/api/documents/create/pdf-from-word" \
-H "client_id: $CLIENT_ID" \
-H "client_secret: $CLIENT_SECRET" \
-H "Content-Type: application/json" \
-d '{"documentId": "<your_document_id>"}' The endpoint returns 202 Accepted, confirming the job is queued. It also accepts .doc, .rtf, .dot, .dotx, .docm, .dotm, and .wpd files through the same documentId input, so legacy Word formats work through the same pipeline.
Step 3: Polling the Task Status
GET /pdf-services/api/tasks/{task-id} returns four fields you need to act on in your polling loop:
status: one ofPENDING,IN_PROGRESS,COMPLETED, orFAILEDprogress: int32, 0 to 100resultDocumentId: populated when status reachesCOMPLETEDerror: populated when status reachesFAILED
The task state machine advances in one direction: PENDING to IN_PROGRESS, then to either COMPLETED or FAILED.

import time
def poll_task(task_id: str, max_attempts: int = 30) -> str:
url = f"{BASE_URL}/pdf-services/api/tasks/{task_id}"
headers = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
}
for attempt in range(max_attempts):
response = requests.get(url, headers=headers)
response.raise_for_status()
data = response.json()
status = data.get("status")
progress = data.get("progress", 0)
print(f"Attempt {attempt + 1}: status={status}, progress={progress}%")
if status == "COMPLETED":
return data["resultDocumentId"]
if status == "FAILED":
raise RuntimeError(f"Conversion failed: {data.get('error')}")
time.sleep(2)
raise TimeoutError(f"Task {task_id} did not complete in {max_attempts} attempts") Two-second polling intervals work across a wide range of document sizes, and polling more aggressively only consumes rate limit budget without affecting conversion time.
Step 4: Downloading the Converted PDF
GET /pdf-services/api/documents/{documentId}/download fetches the finished PDF. The path parameter in the API reference reads {documentId}, but the value you pass here is the resultDocumentId from the completed poll response. The server assigns that ID to the generated PDF output at conversion time, making it the correct identifier to use at this step.
Stream the response to disk with stream=True and iter_content(chunk_size=8192). Buffering a large PDF fully into memory before writing it causes problems on high-volume pipelines.
def download_result(result_document_id: str, output_path: str) -> None:
url = f"{BASE_URL}/pdf-services/api/documents/{result_document_id}/download"
headers = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
}
with requests.get(url, headers=headers, stream=True) as response:
response.raise_for_status()
with open(output_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk) The cURL equivalent uses the --output flag to write directly to disk:
curl -X GET "https://na1.fusion.foxit.com/pdf-services/api/documents/<result_document_id>/download" \
-H "client_id: $CLIENT_ID" \
-H "client_secret: $CLIENT_SECRET" \
--output output.pdf To verify the output, check response.headers.get("Content-Type") for application/pdf, or inspect the first four bytes of the written file for the %PDF magic bytes if your pipeline requires format validation.
Error Handling for Production
The Foxit PDF Services API documentation covers 400, 404, 413, and 500 across the four endpoints. The 401 appears on authentication failures as a practical case even though it’s absent from the documented example responses. Each status code points to a specific root cause with a concrete recovery path:
- 400: malformed request body or unsupported file type. Validate the input file path and extension before calling
upload_doc(). - 401: credential misconfiguration. Verify that CLIENT_ID and CLIENT_SECRET are exported in your shell and that the header names are lowercase
client_idandclient_secret. - 404: the
documentIdhas expired. The server deletes uploaded files after 24 hours, so the convert and download endpoints return 404 for anydocumentIdpast that window. Re-upload the source file and restart from the upload step. An expired or unknowntaskIdon the poll endpoint behaves differently: it returns HTTP 200 withstatus: "FAILED"and anerrorobject whosemessagereads"task is not exist". The poll loop’sFAILEDbranch already catches that case. - 413: file exceeds the 100 MB upload cap. Pre-check with
os.path.getsize()before uploading, or split the document. - 500: transient server error. Apply exponential backoff with a ceiling of 3 retries (wait times of 1s, 2s, and 4s).
def call_with_retry(fn, *args, max_retries: int = 3, **kwargs):
for attempt in range(max_retries + 1):
try:
return fn(*args, **kwargs)
except requests.HTTPError as e:
code = e.response.status_code
if code == 400:
raise ValueError(
"Bad request. Confirm the input is a supported Word format."
) from e
if code == 401:
raise PermissionError(
"Authentication failed. Check CLIENT_ID and CLIENT_SECRET env vars."
) from e
if code == 404:
raise FileNotFoundError(
"Document or task expired (24h TTL). Re-upload and retry."
) from e
if code == 413:
raise OverflowError(
"File too large. The upload cap is 100 MB."
) from e
if code == 500 and attempt < max_retries:
wait = 2 ** attempt # 1s, 2s, 4s
print(f"Server error. Retrying in {wait}s ({attempt + 1}/{max_retries})")
import time
time.sleep(wait)
continue
raise Pipeline authors should treat documentId values as ephemeral: each one expires with its source file after 24 hours, so pipeline code that caches documentId values between sessions will see 404s on every convert call, and re-uploading is always the correct recovery path.
The Complete Script
Set your environment variables, then run python convert.py input.docx output.pdf:
import os
import json
import time
import sys
import requests
CLIENT_ID = os.environ.get("CLIENT_ID")
CLIENT_SECRET = os.environ.get("CLIENT_SECRET")
BASE_URL = "https://na1.fusion.foxit.com"
def call_with_retry(fn, *args, max_retries: int = 3, **kwargs):
for attempt in range(max_retries + 1):
try:
return fn(*args, **kwargs)
except requests.HTTPError as e:
code = e.response.status_code
if code == 400:
raise ValueError(
"Bad request. Confirm the input is a supported Word format."
) from e
if code == 401:
raise PermissionError(
"Authentication failed. Check CLIENT_ID and CLIENT_SECRET env vars."
) from e
if code == 404:
raise FileNotFoundError(
"Document or task expired (24h TTL). Re-upload and retry."
) from e
if code == 413:
raise OverflowError(
"File too large. The upload cap is 100 MB."
) from e
if code == 500 and attempt < max_retries:
wait = 2 ** attempt # 1s, 2s, 4s
print(f"Server error. Retrying in {wait}s ({attempt + 1}/{max_retries})")
time.sleep(wait)
continue
raise
def upload_doc(file_path: str) -> str:
url = f"{BASE_URL}/pdf-services/api/documents/upload"
headers = {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET}
with open(file_path, "rb") as f:
files = {"file": (os.path.basename(file_path), f)}
r = requests.post(url, headers=headers, files=files)
r.raise_for_status()
return r.json()["documentId"]
def convert_to_pdf(document_id: str) -> str:
url = f"{BASE_URL}/pdf-services/api/documents/create/pdf-from-word"
headers = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"Content-Type": "application/json",
}
r = requests.post(url, headers=headers, data=json.dumps({"documentId": document_id}))
r.raise_for_status()
return r.json()["taskId"]
def poll_task(task_id: str, max_attempts: int = 30) -> str:
url = f"{BASE_URL}/pdf-services/api/tasks/{task_id}"
headers = {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET}
for attempt in range(max_attempts):
r = requests.get(url, headers=headers)
r.raise_for_status()
data = r.json()
status = data.get("status")
print(f"[{attempt + 1}/{max_attempts}] status={status}, progress={data.get('progress', 0)}%")
if status == "COMPLETED":
return data["resultDocumentId"]
if status == "FAILED":
raise RuntimeError(f"Conversion failed: {data.get('error')}")
time.sleep(2)
raise TimeoutError(f"Task {task_id} did not complete after {max_attempts} attempts")
def download_result(result_document_id: str, output_path: str) -> None:
url = f"{BASE_URL}/pdf-services/api/documents/{result_document_id}/download"
headers = {"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET}
with requests.get(url, headers=headers, stream=True) as r:
r.raise_for_status()
with open(output_path, "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
def convert_docx_to_pdf(input_path: str, output_path: str) -> None:
print(f"Uploading {input_path}...")
document_id = call_with_retry(upload_doc, input_path)
print(f"Uploaded. documentId={document_id}")
print("Initiating conversion...")
task_id = call_with_retry(convert_to_pdf, document_id)
print(f"Queued. taskId={task_id}")
print("Polling for completion...")
result_document_id = call_with_retry(poll_task, task_id)
print(f"Completed. resultDocumentId={result_document_id}")
print(f"Downloading to {output_path}...")
call_with_retry(download_result, result_document_id, output_path)
print("Done.")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python convert.py <input.docx> <output.pdf>")
sys.exit(1)
convert_docx_to_pdf(sys.argv[1], sys.argv[2]) The Foxit PDF Services API also supports merging, compression, linearization, and OCR through additional endpoints. All of them share the same host and header-based auth pattern, so the functions you’ve built here extend naturally as your pipeline grows.
Create your free Foxit developer account and run your first conversion in under five minutes, with no credit card required at signup.
DOCX to PDF API FAQ
Does the Foxit PDF Services API support formats other than .docx?
Yes. The /pdf-services/api/documents/create/pdf-from-word endpoint accepts .doc, .docx, .rtf, .dot, .dotx, .docm, .dotm, and .wpd. The same four-step flow applies for all of them.
How long are uploaded files retained?
Uploaded documents are automatically deleted after 24 hours. Treat documentId values as ephemeral and re-upload whenever you need to convert a file after that window.
What happens if I poll the task endpoint faster than every 2 seconds?
Faster polling consumes rate limit budget without affecting conversion speed. The server determines conversion time based on document complexity and queue load, so polling intervals below 2 seconds add no throughput benefit.
Can I run multiple DOCX-to-PDF conversions in parallel?
Yes. Each upload returns an independent documentId and each conversion returns an independent taskId. Run concurrent conversions by launching multiple threads or async tasks, with each one tracking its own taskId. Python’s concurrent.futures.ThreadPoolExecutor is a straightforward way to manage this.
Where do I get my CLIENT_ID and CLIENT_SECRET?
From the Foxit Developer Portal dashboard, under the default application created at signup. Both values are available immediately after account creation.
Does the API require an OAuth token exchange?
The API authenticates through named request headers. Pass client_id and client_secret directly on every request, and the server reads those credentials on each call.
Embed Secure eSignatures into Your App with Foxit API

Foxit eSign makes electronic signatures easy, but developers can take it further by automating the process. This tutorial shows how to use the Foxit eSign API to embed secure eSignatures in your apps. With Python code examples, you’ll learn to send documents for signing, dispatch reminders, and check the signing status programmatically.
Foxit eSign is an electronic signature solution that lets individuals and businesses sign, send, and manage documents online. Users can create legally binding eSignatures, prepare forms, and track document status in real time. Reusable templates, automated workflows, and audit trails reduce manual paperwork and keep signing processes moving.
At the simplest level, a user can log into the eSign dashboard and handle 100% of their signing needs. For example, they can upload a Microsoft Word template and drag and drop fields for the signing process. I did this with a simple Word document, and after uploading, the editor let me place fields exactly where I needed them:
That screenshot shows three fields added to my document: a date field, a signer name field, and the actual signature spot. Each field has many configuration options, and your own documents could have far more or far fewer. You can design these forms to meet whatever need you have. You can also do all of this directly within Word. The docs explain how to add fields directly into Word that become active during the signing process.
Once you’ve set up your template, you can initiate the signing process right from the app. The dashboard gives you a full history and audit trail covering whether someone has signed, when they signed, and who signed. As a developer, you’re probably wondering whether this process can be automated. It can.
If you’d rather watch an introduction first, the API introduction video walks through the same material.
eSign Via API
Before digging into the APIs, take a quick look at the API Reference. The signing process itself can get complex. Two, three, or more people may need to sign a document in a specific order, and the template field setup can be done entirely in Word. The focus here is a simple signing example, but nothing stops you from building more advanced, flexible workflows.
The full signing flow this article walks through, end to end:

The first step in any API usage is authentication. When you have an eSign account with API access, you receive a client_id and client_secret value, both of which you exchange for an access token at the appropriate endpoint. You’ll find the client_id and client_secret under the API tab in your Foxit eSign account settings once you’ve activated API access. A simple Python implementation looks like this:
CLIENT_ID = os.environ.get("CLIENT_ID")
CLIENT_SECRET = os.environ.get("CLIENT_SECRET")
def getAccessToken(id, secret):
url = "https://na1.foxitesign.foxit.com/api/oauth2/access_token"
payload=f"client_id={id}&client_secret={secret}&grant_type=client_credentials&scope=read-write"
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data=payload)
token = (response.json())["access_token"]
return token
access_token = getAccessToken(CLIENT_ID, CLIENT_SECRET) In this code, you pull the client_id and client_secret from environment variables, post them as application/x-www-form-urlencoded to na1.foxitesign.foxit.com/api/oauth2/access_token with the client_credentials grant and read-write scope, and read access_token off the JSON response. Every subsequent call in this article reuses that token in the Authorization: Bearer ... header.
The example uses the US region host (na1.foxitesign.foxit.com). If your account is in another region, swap in the appropriate host: eu1.foxitesign.foxit.com for EU, na2.foxitesign.foxit.com for Canada, or au1.foxitesign.foxit.com for Australia.
All remaining demos use this method, and at the end of this post you’ll find GitHub links for the full source.
Kicking Off the Signing API Process
With authentication handled, the code can drive the full signing process. The first thing to add is a signing flow using the template shown above. From the dashboard I noted the template ID, 392230, though APIs for working with templates let you retrieve that via code as well.
The Create Envelope from Template endpoint starts the signing process. An envelope is a set of documents a user must sign. For this demo it’s one document, but you can include multiple. The API reference example shows a large input body because the electronic signing process can be complex. For this simple demo, you only need the signer’s name and email address. This Python utility handles that:
def sendForSigning(template_id, first_name, last_name, email, token):
url = "https://na1.foxitesign.foxit.com/api/templates/createFolder"
body = {
"folderName":"Sending for Signing",
"templateIds":[template_id],
"parties":[
{
"permission":"FILL_FIELDS_AND_SIGN",
"firstName":first_name,
"lastName":last_name,
"emailId":email,
"sequence":1
}
]
}
headers = {
'Authorization': f'Bearer {token}',
}
response = requests.request("POST", url, headers=headers, json=body)
return response.json() The code above builds the create-envelope payload, with the folder name, the template ID list, and a single-element parties array carrying the signer’s name, email, and FILL_FIELDS_AND_SIGN permission, then POSTs it to /api/templates/createFolder with the bearer token and returns the parsed JSON. parties is an array because real signing flows often need multiple signers, and permission is required on each entry because it defines the role that party plays.
Passing in the template ID and signer details works like this:
# Hard coded template id
tid = "392230"
sendForSigningResponse = sendForSigning(tid, "Alex", "Rivera", "[email protected]", access_token) The call returns a large set of data. For now, pull out just the envelope ID:
envelopeId = sendForSigningResponse['folder']['folderId']
print(f"ID of the envelope created: {envelopeId}") Note: You’ll see ‘folder’ referenced in the API endpoints and results, but the eSign API is migrating to the ‘envelope’ term. Both terms are used interchangeably in the current API.
A few seconds after running this code, the signing email appeared in my account:
Sending out Electronic Reminders
To nudge signers who haven’t acted yet, use the Send Signature Reminder endpoint. It takes the envelope ID created earlier (and again, see the note above about envelope vs folder):
def sendReminder(envelope_id, token):
url = "https://na1.foxitesign.foxit.com/api/folders/signaturereminder"
body = {
"folderId":envelope_id
}
headers = {
'Authorization': f'Bearer {token}',
}
response = requests.request("POST", url, headers=headers, json=body)
result = response.json()
return result In this code, you build a one-key body containing the envelope ID, attach the bearer token, POST to /api/folders/signaturereminder, and return the parsed JSON. The endpoint is fire-and-forget from the client’s perspective, so a 2xx response means Foxit has queued the reminder email to the outstanding signer.
With the access token and envelope ID in hand, triggering a reminder takes a single call:
access_token = getAccessToken(CLIENT_ID, CLIENT_SECRET)
result = sendReminder(envelope_id, access_token) Running this sends an email reminder to the signer:
Ok, But Did They Sign Their Document Yet??
To check whether the signer has completed the process, use the Get Envelope Details endpoint. It takes the envelope ID from before. Here’s a Python wrapper for that API:
def getStatus(envelope_id, token):
url = f"https://na1.foxitesign.foxit.com/api/folders/myfolder?folderId={envelope_id}"
headers = {
'Authorization': f'Bearer {token}',
}
response = requests.request("GET", url, headers=headers)
result = response.json()
return result The code above issues a GET to /api/folders/myfolder with the envelope ID as a query-string parameter, sends the bearer token in the Authorization header, and returns the parsed JSON. The full response body carries every audit-trail field the dashboard surfaces (parties, timestamps, folder status), and the next snippet pulls just folderStatus out for a quick yes/no.
Checking status against the envelope ID:
result = getStatus(envelope_id, access_token)
print(f"Envelope status: {result['folder']['folderStatus']}") The endpoint returns a lot of information, but printing just the status gives you a high-level view of where the process currently stands.
With the example shown above, the envelope status is SHARED. Clicking the link in the signing email opens the signing view:
The date is already filled to today’s date, and the name is pre-filled because eSign knows who the document was sent to. Clicking to sign is all that remains. Once the signer does that, the same status call returns EXECUTED.
Next Steps
If you’re new to eSign, the main homepage gives you a solid introduction, and the Foxit eSign YouTube channel has video content covering the service in depth.
Beyond the basics covered here, the API has significantly more to offer. Webhooks deliver automatic notifications when envelope events fire, so you don’t need to poll for status. The API also supports embedded signing sessions for keeping signers inside your own application, SSO authentication for signers, and multi-party workflows with sequential or parallel signing order. The API Reference covers all of these in full.
All three code examples from this post are available in the GitHub repo. The eSign API is also part of the broader Foxit developer platform, which includes APIs for PDF processing, document generation, and embedded PDF viewing. Bring your questions to the developer forums.
Ready to wire signing into your own product? Create a free developer account directly at account.foxit.com/site/sign-up (no credit card required). The direct URL skips the pricing-page redirect from the developer portal and drops you on the account form, with API credentials waiting in the API Keys section once you’re in.
eSign API FAQ
How do I embed e-signatures in my app with the Foxit eSign API?
You authenticate with OAuth2 to get an access token, then call Create Envelope from Template to send a document for signature. In this article’s flow, the signer completes signing through an emailed link. For a fully in-app experience where signers never leave your interface, the Foxit eSign API also supports embedded signing sessions, which you load directly inside your app and pair with webhooks to capture completion events.
What is an embedded signature?
An embedded signature is one a signer applies inside your own application’s interface rather than on a separate hosted signing page. Instead of redirecting the signer to an external Foxit eSign page, your app presents the signing experience in context, keeping users in your product end to end. With the Foxit eSign API, this is delivered through embedded signing sessions rather than the standard email-based envelope flow.
What is an embedded signing API?
An embedded signing API generates a secure signing session you load inside your own app — typically in an iframe or web view — so signers complete documents without leaving your interface. The Foxit eSign API provides this through embedded signing sessions, alongside the email-based flow demonstrated in this article (create an envelope, signer signs via an emailed link). Webhooks then notify your app the moment an envelope reaches EXECUTED status.
How do I authenticate with the Foxit eSign API?
Authentication uses the OAuth2 client-credentials grant. You exchange your client_id and client_secret — found under the API tab in your Foxit eSign account settings — for an access token by POSTing to the regional OAuth2 endpoint (for example, na1.foxitesign.foxit.com for the US, or eu1 for the EU). Send that token as a Bearer header on every subsequent call; the same token is reused across envelope creation, reminders, and status checks.
How do I check whether a signer has completed a document?
Call the Get Envelope Details endpoint with your envelope ID, passing the Bearer token in the Authorization header. The response carries the full audit trail — parties, timestamps, and status. Reading folderStatus gives a quick state: SHARED while the document is out for signature, and EXECUTED once the signer finishes. For real-time updates instead of polling, the Foxit eSign API offers webhooks that fire on envelope events.
Why does the Foxit eSign API use both "folder" and "envelope"?
They refer to the same thing. An envelope is the set of documents a signer must complete. The Foxit eSign API is migrating from the older term “folder” to “envelope,” so you’ll still see folder in endpoint paths and response fields — for example, createFolder, folderId, and folderStatus — while the documentation increasingly uses envelope. Both terms are interchangeable in the current API.
Document Generation Explained: How the Template-to-API Pipeline Actually Works

Manual document workflows break down fast as volume grows. This guide explains what document generation is, how template-driven APIs replace manual processes, and what the pipeline looks like from a Word template and JSON payload to a finished PDF.
You’ve inherited a document workflow built on Word macros, save-as duplication, and a shared drive folder someone named “FINAL_v3.” Every time a contract needs to go out, someone opens the master template, manually replaces the client name and date, exports to PDF, and emails it. Scaled to one deal a week, that works. Scaled to a thousand deals a quarter, it breaks down in ways that are hard to trace and painful to fix.
Document generation APIs make the relationship between input data and output document deterministic. This article covers how that pipeline is structured, what the token contract between template and data looks like, and what the actual API call looks like from a POST request to a decoded file.
What Document Generation Is
Document generation is the programmatic production of populated, formatted documents from a template and a structured data source. Three components are always present: a template (the structure and placeholders), a data payload (the values to inject), and a rendering engine (the API that merges the two and produces the final file).
These components map cleanly onto a separation of concerns. The template owner controls layout, language, and branding. The data owner controls what goes in each field. The rendering engine enforces the merge contract between them. When that separation holds, changing the template doesn’t require a code change, and changing the data schema requires only a template update.
Document generation occupies a distinct category from the adjacent tools that crowd the same search space. E-signature platforms collect binding signatures on completed documents. Document management systems store, version, and retrieve files. OCR and extraction tools pull structured data out of existing documents. Document generation puts data in.
Why Manual Document Workflows Break Under Load
Manual Word-based workflows fail in three predictable ways when volume grows.
Version drift happens when templates live in shared folders across teams. One team updates the disclaimer text, another adds a new liability clause, and a third is still using a version from Q3. After six months, your organization has five variants of the same contract template producing inconsistent output, with no reliable way to identify which version generated any given document.
Merge errors compound at scale. Copy-paste and mail-merge workflows both require human coordination of field-by-field substitution. When an invoice ships with the previous client’s name, or a renewal letter shows last year’s rates, the error traces back to a single manual step that had no validation layer. A 0.5% error rate is invisible at 20 documents a month. At 4,000 documents a month, it means 20 wrong documents going out the door.
Audit trail absence creates compliance exposure. A manually assembled document carries no machine-readable record of what data produced it or when. When a regulator asks which policy documents were generated from the October 2024 rate table, the answer requires a manual search through email threads and file name timestamps.
Programmatic generation makes each of these problems tractable. The same JSON payload processed against the same template version always produces the same output, and every generation event is a logged API call with a traceable input and output. The document generation software market is valued at $4.05B in 2025 and projected to grow at a 9.2% CAGR through 2035, driven by enterprise automation and compliance requirements that manual workflows can’t satisfy at scale.
How Template-Driven Generation Works: Tokens, Loops, and Conditionals
Foxit’s DocGen API uses standard Microsoft Word as the template authoring environment. Template authors work in Word, inserting double-bracket placeholders whose key names map directly to keys in the JSON payload supplied at generation time. This keeps template ownership with the people who understand the document content, with no proprietary editor and no additional software license required.
The basic token syntax covers three common cases:
{{ companyName }}renders the string value ofcompanyNamefrom the payload{{ invoiceDate \@ MM/dd/yyyy }}applies a Word date picture string to the raw date value (the leading\@is required; the friendly form without it renders blank){{ totalDue \# "$#,##0.00" }}formats a numeric value as currency using a Word numeric picture string (a friendly keyword like\# Currencyis unsupported and renders blank)
A minimal JSON payload for a template containing those three tokens would be:
{
"companyName": "Meridian Analytics",
"invoiceDate": "2025-06-15",
"totalDue": 8250.0
} The rendering engine walks the template, matches each token to the corresponding key in the payload, and writes the formatted value into the output. Template authors work entirely in Word, while the engine handles token resolution, format application, and output assembly.
Repeating sections use loop delimiters to produce table rows that repeat for each element in a JSON array. Placing {{TableStart:lineItems}} before a table row and {{TableEnd:lineItems}} after it tells the engine to emit one row per object in the lineItems array. Both delimiters must sit in cells of the same Word table row. Inside that loop, {{ROW_NUMBER}} auto-increments across rows, and a footer row immediately below the loop can use {{=SUM(ABOVE) \# "$#,##0.00"}} to compute and format a column total, so a ten-line invoice produces a correctly numbered, fully summed table with no post-processing.
Conditional content uses Word’s native Field Code View (opened with ALT + F9) to write IF-field conditions that show or hide text blocks based on data values. A clause that should appear only when contractType equals "enterprise" lives inside a field condition, and the rendering engine evaluates it at generation time. There’s no separate scripting layer and no custom expression language to learn.
The three components converge at a single API endpoint: your base64-encoded DOCX template and JSON data payload go in together, and the generated document comes back in the same HTTP response.

The API Pipeline: From POST Request to Final Document
The Foxit DocGen API compresses the generation pipeline into a single synchronous call. You POST to one endpoint with your template and data, and you receive the generated document in the same HTTP response, with no separate template upload step, no job ID to poll, and no webhook to configure for individual document generation.
Before building a generation workflow, you can use the Analyze Document API to scan a DOCX template and return a list of all embedded tokens, which confirms the token-to-key mapping before you commit to a data schema. That’s a single POST to a separate endpoint on the same host, and it returns a structured list of placeholder names and their types.
For the generation call itself, the dev-tier endpoint is:
POST https://na1.fusion.foxit.com/document-generation/api/GenerateDocumentBase64
Authentication passes your client_id and client_secret as custom HTTP headers alongside Content-Type: application/json. You retrieve both credentials from the dashboard at account.foxit.com/site/sign-up after activating your free developer plan, with no OAuth exchange and no session setup required before your first call.
The request body takes three fields:
base64FileStringis your DOCX template, base64-encoded. Keep the source.docxunder 4 MB (the practical ceiling for a single request) since base64 encoding inflates the payload by roughly 33%. If a template runs large, embedded images are usually the cause, so compress them through Word’s Picture Format settings before exporting.documentValuesis the JSON object whose keys map to token names in the templateoutputFormatis the string"pdf"or"docx", lowercase and exact (the API returns HTTP 500 for any other value, including"PDF"or"DOCX")
For an invoice template with a lineItems array, the full curl command carries your base64-encoded DOCX, the matching data object, and your credentials in the request headers:
curl -X POST "https://na1.fusion.foxit.com/document-generation/api/GenerateDocumentBase64" \
-H "client_id: YOUR_CLIENT_ID" \
-H "client_secret: YOUR_CLIENT_SECRET" \
-H "Content-Type: application/json" \
-d '{
"base64FileString": "BASE64_ENCODED_DOCX_HERE",
"documentValues": {
"companyName": "Meridian Analytics",
"invoiceDate": "2025-06-15",
"totalDue": 8250.00,
"lineItems": [
{ "description": "Platform License", "quantity": 1, "unitPrice": 8250.00 }
]
},
"outputFormat": "pdf"
}' The API returns a synchronous JSON response carrying a human-readable message, the fileExtension for naming the output file, and the base64FileString containing the generated document:
{
"message": "PDF Document Generated Successfully",
"fileExtension": "pdf",
"base64FileString": "JVBERi0xLjQK..."
} message gives you a status string for logging. fileExtension tells you whether you received "pdf" or "docx", which lets you construct the output filename programmatically without parsing the message string. base64FileString is the generated document. Your application decodes that value and routes the resulting bytes to storage, email delivery, a document management system, or whatever downstream step your workflow requires.
For teams evaluating the API before writing integration code, the Foxit developer portal includes a Postman collection with GenerateDocumentBase64 preconfigured. You can load the collection, paste your credentials and a test template, send the request, and confirm the response structure before writing a single line of application code. Foxit also provides SDKs for Node.js, Python, Java, C#, and PHP if you prefer a language-native integration path over raw HTTP.
Where Organizations Are Actually Using This
Five industries where the template-to-API pipeline produces direct operational value:
Insurance carriers face renewal cycles that generate thousands of policy documents each quarter. They pull policyholder data from their CRM, pass it as a JSON payload to the generation API, and produce populated renewal packets without manual assembly. Each document reflects current policy terms from the system of record, cutting the per-document preparation time from minutes of human work to milliseconds of API latency.
Healthcare providers need patient intake packets and HIPAA disclosure forms ready before each appointment. Clinics pull patient demographic and consent data from their EHR system, generate the packet at appointment scheduling time, and deliver it to the patient portal. The data source is the live EHR record, so the document always reflects current information.
Government agencies and courts produce case-related documents (orders, notices, motions) with fixed structure and variable case data. API-based generation means each document draws directly from structured court records, reducing transcription errors and producing a machine-readable audit trail that links every output document to the specific data that created it.
High-tech and SaaS companies trigger NDA and quote generation directly from their CRM or CPQ tools. A deal record in Salesforce or HubSpot becomes the JSON payload, and the generation API produces a finalized, formatted document without a manual drafting step. The document lands in the deal room minutes after the pricing conversation closes.
Education institutions generate hundreds or thousands of admission offer letters during enrollment periods. Student data from the Student Information System becomes the payload, and each letter reflects the correct program, scholarship amount, and enrollment deadline for that individual student. What a staff member would take days to produce manually runs as a scheduled batch job.
What to Evaluate When Choosing a Document Generation API
Output format coverage deserves attention before you commit to an API. Receiving both PDF and DOCX from the same endpoint matters when your workflow requires human review before a document is finalized. PDF suits direct delivery. DOCX suits draft-and-review cycles where a lawyer or editor needs to modify the generated document before it goes to signature. APIs that produce only PDF force you to finalize at generation time, which eliminates the review step entirely.
The execution model determines whether an API fits your latency requirements. Synchronous APIs return the document in the same HTTP response, which works for real-time generation triggered by a user action or a CRM event. Asynchronous APIs accept a job and require polling or a webhook to retrieve the result, which works better for batch jobs processing thousands of documents in a run. Confirm which model the API offers before you design your integration, because retrofitting from synchronous to async (or vice versa) affects how you handle errors, retries, and downstream routing. Foxit’s DocGen API is synchronous, so individual requests resolve in a single HTTP round trip.
Template portability determines your long-term maintenance cost. A template stored as a standard DOCX file is editable by anyone with Word, version-controllable in Git, and portable across environments. A template stored in a proprietary format requires the vendor’s editor for every update, and losing access to that editor means losing the ability to maintain your own document logic. Word-based templates also let business users own content changes without involving a developer.
Compliance posture matters as soon as your documents contain PII, PHI, or financial data. Confirm the provider’s certifications before sending real records through the API. SOC 2, GDPR compliance, and HIPAA certification are the relevant checks for most enterprise document workflows. A provider’s architecture (multi-tenant SaaS vs. single-tenant hosted) also affects how you address data residency requirements.
Developer onboarding cost is a real selection criterion. A free tier with immediate credential access, a working Postman collection, and SDK support for your language stack lets your team validate fit in hours. A procurement process that requires a sales conversation before you can run a test extends your evaluation cycle by weeks. Foxit’s developer plan is free, credit-card-free, and gives you dashboard access and credentials immediately, so your team can make an informed build-vs-buy decision based on a working integration rather than a demo.
Getting Started: Generate Your First Document Today
A working end-to-end generation pipeline takes under an hour to set up:
Go to account.foxit.com/site/sign-up and activate a free Developer plan. Dashboard access and credentials are immediate, with no credit card and no sales call required.
Retrieve your Client ID and Client Secret from the dashboard.
Grab a ready-to-use template, or author your own. Download
invoice_simple.docxfor the smallest possible smoke test, orinvoice_table.docxif you want the full loop,{{ROW_NUMBER}}, and{{=SUM(ABOVE)}}round-trip. To build your own instead, open Microsoft Word, add two or three{{ tokenName }}placeholders, and save as DOCX. Base64-encode the file usingbase64 -i template.docxon macOS or Linux, or[Convert]::ToBase64String([IO.File]::ReadAllBytes("template.docx"))in Windows PowerShell.Open the Postman collection linked on the Foxit API page, load the
GenerateDocumentBase64request, paste your base64-encoded template intobase64FileString, and add a JSON object todocumentValueswith keys matching your placeholder names. SetoutputFormatto"pdf"and send the request. Copy thebase64FileStringvalue from the JSON response and decode it. You now have a generated PDF.
From this point, connecting to a real data source is the only remaining step. Pull a record from your CRM, a row from your database, or a response from an upstream API, map its fields to the token names in your template, and pass the result as documentValues. That connection makes the pipeline production-ready, and every document it generates becomes a deterministic, auditable function of the data that produced it.
Activate your free Foxit Developer plan (no credit card, no sales call) and run your first document generation call in minutes at account.foxit.com/site/sign-up.
Document Generation Pipeline FAQ
What is document generation?
Document generation is the programmatic production of populated, formatted documents from a template plus a structured data source. Three components are always present: a template holding the layout and placeholders, a JSON data payload holding the values, and a rendering engine that merges the two into a final PDF or DOCX. The same payload against the same template always produces the same output, which makes the process deterministic and auditable.
How is document generation different from e-signature or OCR tools?
They occupy adjacent but distinct categories. E-signature platforms like DocuSign collect binding signatures on documents that already exist. Document management systems store, version, and retrieve files. OCR and extraction tools pull structured data out of existing documents. Document generation does the opposite — it puts data in, producing a new populated document from a template. Many workflows chain them: generate a contract, then route it for signature.
What does a Foxit DocGen API request and response look like?
You POST to GenerateDocumentBase64 with three fields: base64FileString (your base64-encoded DOCX template), documentValues (the JSON object whose keys match your tokens), and outputFormat ("pdf" or "docx", lowercase). Authentication uses client_id and client_secret headers. The synchronous response returns a message, a fileExtension, and a base64FileString containing the generated document, which your app decodes and routes downstream.
How do you create repeating table rows in a document generation template?
Use loop delimiters. Place {{TableStart:lineItems}} before a Word table row and {{TableEnd:lineItems}} after it, with both delimiters in cells of the same row. The engine emits one row per object in the lineItems array. Inside the loop, {{ROW_NUMBER}} auto-increments, and a footer row can use {{=SUM(ABOVE) \# "$#,##0.00"}} to compute and format a column total — so a ten-line invoice renders fully numbered and summed with no post-processing.
Can the document generation API return both PDF and DOCX?
Yes. The Foxit DocGen API returns either format from the same endpoint based on the outputFormat value. PDF suits direct delivery where the document is final at generation time. DOCX suits draft-and-review cycles, where a lawyer or editor needs to modify the generated file before it goes to signature. APIs that emit PDF only force you to finalize at generation and eliminate that review step.
PDF Translation with Verifiable Quality: Build a Confidence-Scored Pipeline with Foxit API and Straker.ai

Most machine translation tools hand back a translated PDF with no signal about which parts to trust — a real problem for contracts, medical forms, and regulatory filings. This guide shows how to build a pipeline that scores every segment before the final render, using Foxit for structural extraction and layout-preserving rendering and Straker.ai for translation plus per-segment quality scoring.
Most machine translation tools give you a translated file and nothing else. They do not tell you which parts are correct and which parts are wrong. For a simple blog post, that is fine. For a contract, a medical form, or a legal notice, it is a real problem. A bad translation can sit in the final PDF for days before anyone notices, often only after the document has already been signed or sent.
Teams today are translating more documents, into more languages, and faster than ever. Legal, finance, healthcare, HR, and insurance teams all deal with PDFs where one wrong word can cause a lot of damage: a broken contract, a failed audit, or even a safety issue. Most translation tools were not built to catch these mistakes. They just move text from one language to another. When quality checks happen at all, they usually mean a person reading the final PDF line by line and hoping they spot the errors.
This article shows how to build a better setup. You will learn how to build a PDF translation pipeline that gives every segment a quality score before the final PDF is created. Instead of hoping the translation is right, the pipeline tells you which parts to trust, which parts to review, and which parts to send back to a human translator. All of this happens automatically on every run.
Architecture at a Glance
Before going deeper, it helps to see the full pipeline in one picture. The diagram below traces a source PDF through every stage: extract, translate, score, route, and render. Each box is a single responsibility handled by a single service, with the routing layer acting as the glue you control.

The pipeline has two external services:
- Foxit PDF Translation API handles anything PDF-specific. It pulls the structured text out of the source document with element IDs attached, then renders the final PDF back in the original layout (multi-column text, tables, font substitution, image positions) using the approved translations.
- Straker AI translates each source segment AND scores the translation in the same request. It returns the target text, a numeric score on a 0.0 to 1.0 scale, and a categorical label (
best,good,acceptable,bad) for every element ID. This step is pluggable, so you can swap Straker for DeepL, Google Cloud Translation, AWS Translate, or an in-house NMT if you already have a contract with one of them. The contract between this step and the rest of the pipeline is a flat dict of element IDs to translated text plus per-segment scores.
and one piece of code you own:
- Routing layer is your business logic. It reads the score, decides whether the segment auto-accepts, flags for human review, or escalates to a translator, and then hands the approved set to Foxit’s render call.
With the shape of the pipeline on the table, the rest of the article works through each piece in order, starting with why per-segment quality scoring is worth the integration effort in the first place.
The Quality Gap
You ship a translated PDF to a legal team. Three days later, compliance flags a clause in the German version. The term “indemnification” was rendered as “Entschädigung” (compensation) rather than “Freistellung” (hold harmless). Your MT pipeline returned a 200 status. Nobody’s alerting on that delta.
Raw machine translation output carries no quality signal by default. Every segment comes back translated, and your pipeline treats them identically regardless of whether the model was confident or guessing. For marketing copy that’s an acceptable tradeoff, but for a loan covenant, a clinical trial protocol, or a regulatory filing, a 95%-accurate translation can still be contractually or legally dangerous because the 5% failure may concentrate precisely in the high-stakes clauses.
A confidence score, in the translation QA context, is a per-segment numeric signal from a verification engine. It tells you how reliable each translated unit is on a scale your system can act on programmatically. High-confidence segments auto-accept, medium-confidence ones queue for post-edit review, and low-confidence segments escalate directly to a human translator before they ever reach the final document.
The compound problem for PDFs specifically is that most translation pipelines strip document structure before the MT engine even sees the text. The extraction step flattens multi-column layouts, collapses table cells, and drops font metadata. By the time you get a translated output, you’ve lost both layout fidelity and any quality signal. The rendered PDF looks wrong and you have no programmatic way to know which segments caused it.
Foxit’s PDF Translation Trial API extracts structured text from a source PDF with element IDs preserved, so the layout blueprint travels alongside the text through the entire workflow. You hand the source segments to Straker AI, which returns the translated text plus a per-segment numeric score and a quality label in a single call. (If you already run DeepL, Google Cloud Translation, AWS Translate, or an in-house NMT Engine, you can drop it in at this step without changing the rest of the pipeline.) Your routing logic decides which segments pass, which get flagged, and which escalate to human review. Foxit’s render endpoint then re-assembles the PDF in the original layout using the accepted translations, giving you a layout-preserved translated PDF with a documentable quality trail attached to every segment.
How the Pipeline Works
Foxit and Straker are two independent APIs that you wire together. Foxit owns PDF structure, extracting structured text keyed by element ID and re-rendering the final PDF in the original layout. Straker AI handles translation and per-segment quality scoring in a single request, returning the translated text alongside a numeric score and a quality label. You own the routing decision that sits between the scores and the render call.
The pipeline runs in seven steps:

Foxit covers steps 1-3 and 6-7 (PDF structure and rendering). Straker AI covers step 4, producing translations and per-segment quality scores in one round-trip. Step 5 is your business logic.
The Foxit PDF Translation API defines steps 2, 3, and 6. The upload and download calls use the general PDF Services endpoints. Straker AI is a separate API at https://api-verify.straker.ai. You submit XLF 1.2 files containing source segments and Straker returns the translated target_text per segment plus a numeric score (0.0 to 1.0) and a quality label (best, good, acceptable, bad). Because Foxit’s ExtractedText.json is a flat { "elementId": "text" } map, and XLF trans-unit IDs round-trip through Straker’s external_id field unchanged, the element IDs Foxit emits are the same IDs that come back with translations and scores attached. That alignment is what makes programmatic routing possible.
One clarification for readers who’ve seen the Foxit-Straker partnership announcement: that partnership covers Foxit eSignature Services, enabling end users to translate and sign documents in the eSign product. That’s an end-user feature. The PDF Translation Trial API used here is a separate developer surface. Its OpenAPI spec (v2.2.0) contains zero Straker references, and the preprocess-pdf documentation explicitly instructs developers to “translate the text in ExtractedText.json using your preferred translation tool.” You wire the two APIs together manually. This tutorial uses Straker AI as the default translation engine because it produces translations and quality scores in the same call, but you can substitute DeepL, Google Cloud Translation, AWS Translate, or your own NMT at step 4 without changing the Foxit calls.
Credentials and Setup
Get your Foxit credentials at app.developer-api.foxit.com/pricing. The free Developer plan gives you 20 AI credits per month with no credit card and no sales call required. Once you’ve signed in, your Client ID and Client Secret appear in the developer dashboard. Every Foxit API call requires both in the request headers as client_id and client_secret (lowercase snake_case). Export them in your shell as FOXIT_CLIENT_ID and FOXIT_CLIENT_SECRET so the code below reads them from the environment rather than hard-coding secrets.
For Straker, sign up at straker.ai/ai-platform/verify for API access. Straker issues a UUID-style API token that you send as a bearer token on every call (Authorization: Bearer <your-token>). The API lives at https://api-verify.straker.ai and its full reference is published at api-verify.straker.ai/docs. Export your token as STRAKER_API_KEY for the code below. You can confirm the token works and check your balance with a quick GET /user/balance. Both services offer trial access, so you can build and test the full pipeline before any procurement conversation.
Before you finalize your language matrix, check both APIs for supported languages. Foxit’s render endpoint accepts 23 target language codes (en, zh, zh_tw, fr, de, es, it, pt, nl, ja, ko, th, vi, hi, ru, ar, tr, pl, sv, no, nb, da, and fi). Straker AI identifies languages by UUID rather than ISO code. You fetch the full list with GET /languages and look up the UUID for your target (for example, 917FF728-0725-A033-1278-33025F49CA40 is French (France), 917FF7D8-9107-0BF8-97EE-065C20F453DE is German). The intersection of the two sets determines your production language coverage.
If you already have a contract with DeepL, Google Cloud Translation, AWS Translate, or an in-house NMT service, you can swap that engine in at step 4. The pipeline contract upstream (Foxit element IDs mapped to source strings) and downstream (a dict of {element_id: {score, quality, target_text}} feeding the router) does not change. The code below uses Straker AI by default because the same API returns the translation and the quality signal in one call.
Building the PDF Translation Pipeline
The complete seven-step pipeline runs in Python using requests, json, zipfile, os, and the standard-library xml.etree.ElementTree for building XLF. The first snippet covers Foxit steps 1-3 (upload, structural extraction, and preprocessing).
import requests
import json
import zipfile
import io
import time
FOXIT_BASE = "https://na1.fusion.foxit.com/pdf-services/api"
HEADERS = {
"client_id": "YOUR_CLIENT_ID",
"client_secret": "YOUR_CLIENT_SECRET"
}
def poll_task(task_id: str) -> dict:
"""Poll GET /tasks/{task_id} until COMPLETED or FAILED."""
while True:
r = requests.get(f"{FOXIT_BASE}/tasks/{task_id}", headers=HEADERS)
r.raise_for_status()
data = r.json()
status = data.get("status")
if status == "COMPLETED":
return data
if status == "FAILED":
raise RuntimeError(f"Task {task_id} failed: {data.get('error')}")
# PENDING or IN_PROGRESS: wait and retry
time.sleep(3)
# Step 1: Upload source PDF
with open("source.pdf", "rb") as f:
upload_resp = requests.post(
f"{FOXIT_BASE}/documents/upload",
headers=HEADERS,
files={"file": ("source.pdf", f, "application/pdf")}
)
upload_resp.raise_for_status()
source_document_id = upload_resp.json()["documentId"]
# Step 2: Structural Extract (async - must complete before preprocess)
extract_resp = requests.post(
f"{FOXIT_BASE}/documents/pdf-structural-extract",
headers=HEADERS,
json={"documentId": source_document_id}
)
extract_resp.raise_for_status() # 202 Accepted
extract_task_id = extract_resp.json()["taskId"]
extract_result = poll_task(extract_task_id)
extracted_doc_id = extract_result["resultDocumentId"]
# Step 3: Preprocess (synchronous - returns 200, no polling needed)
preprocess_resp = requests.post(
f"{FOXIT_BASE}/documents/translation/preprocess-pdf",
headers=HEADERS,
json={"documentId": extracted_doc_id}
)
# Errors from preprocess-pdf per the Foxit spec:
# 400 VALIDATION_ERROR - "Document ID is required"
# 500 INTERNAL_SERVER_ERROR - "Failed to preprocess document"
preprocess_resp.raise_for_status()
preprocess_result_id = preprocess_resp.json()["resultDocumentId"]
# Download the ZIP containing ExtractedText.json and StructureInfo.json
zip_resp = requests.get(
f"{FOXIT_BASE}/documents/{preprocess_result_id}/download",
headers=HEADERS
)
zip_resp.raise_for_status()
with zipfile.ZipFile(io.BytesIO(zip_resp.content)) as zf:
extracted_text = json.loads(zf.read("ExtractedText.json"))
# StructureInfo.json: do not modify - the render step requires it untouched
# structure_info = json.loads(zf.read("StructureInfo.json"))
# extracted_text is now {"elementId1": "original text", "elementId2": "original text", ...} The preprocess step is synchronous, which means you get a 200 OK directly with the resultDocumentId. No polling required. The ZIP it produces contains two files: ExtractedText.json maps every element ID to its original text, and StructureInfo.json carries the full layout blueprint (bounding boxes, font metadata, column positions). You pass StructureInfo.json to the render step unmodified. Modifying it breaks the render because it’s the mechanism that makes layout preservation possible.
The second snippet covers steps 4-7, calling Straker AI to translate and score every segment in one round-trip, routing by score, rendering the translated PDF, and downloading the result. Straker’s AI Translation and Quality Evaluation workflow accepts a source-only XLF and returns a translated target_text per segment alongside the numeric score and the quality label, so the same response feeds both the translation choice and the routing decision.
import xml.etree.ElementTree as ET
STRAKER_BASE = "https://api-verify.straker.ai"
STRAKER_TOKEN = "STRAKER_API_KEY"
STRAKER_HEADERS = {"Authorization": f"Bearer {STRAKER_TOKEN}"}
# Straker identifies languages by UUID. Look these up once via GET /languages
# and cache them. Full list: https://api-verify.straker.ai/languages
STRAKER_LANG_FRENCH = "917FF728-0725-A033-1278-33025F49CA40"
STRAKER_LANG_GERMAN = "917FF7D8-9107-0BF8-97EE-065C20F453DE"
# Workflow UUID for "AI Translation and Quality Evaluation". Fetch the full
# list of workflows once via GET /workflow and cache the UUID for the one you
# want; this workflow produces both the translation and the per-segment score.
STRAKER_WORKFLOW_AI_TRANSLATE_AND_EVAL = "390b47a9-d5dc-46ae-92e2-56c43d128c44"
def build_xlf_1_2_source_only(source_lang: str, target_lang: str,
sources: dict) -> bytes:
"""
Build a minimal XLF 1.2 document with source segments and empty targets.
trans-unit/@id preserves Foxit's element IDs; Straker surfaces the same
value as `external_id` on the segments it returns, so the keys round-trip.
"""
ns = "urn:oasis:names:tc:xliff:document:1.2"
ET.register_namespace("", ns)
xliff = ET.Element(f"{{{ns}}}xliff", {"version": "1.2"})
file_el = ET.SubElement(xliff, f"{{{ns}}}file", {
"source-language": source_lang,
"target-language": target_lang,
"datatype": "plaintext",
"original": "foxit-extract",
})
body = ET.SubElement(file_el, f"{{{ns}}}body")
for element_id, source_text in sources.items():
unit = ET.SubElement(body, f"{{{ns}}}trans-unit", {"id": element_id})
ET.SubElement(unit, f"{{{ns}}}source").text = source_text
ET.SubElement(unit, f"{{{ns}}}target") # empty - Straker fills it in
return b'<?xml version="1.0" encoding="UTF-8"?>\n' + ET.tostring(xliff, encoding="utf-8")
# Step 4: Translate and score every segment with Straker AI in one call.
def translate_and_score_with_straker(sources: dict, source_lang_code: str,
target_lang_uuid: str) -> dict:
"""
Submit source-only XLF to Straker's AI Translation + Quality Evaluation
workflow. Returns a dict keyed by Foxit element ID ->
{"score": float|None, "quality": str, "target_text": str}.
"""
xlf_bytes = build_xlf_1_2_source_only(source_lang_code, "fr", sources)
# 4a. Create the project on the AI Translation + Quality Evaluation
# workflow. confirmation_required=false commits the token cost
# immediately; set to true to review cost and call POST /project/confirm
# before processing begins.
create_resp = requests.post(
f"{STRAKER_BASE}/project",
headers=STRAKER_HEADERS,
files={"files": ("segments.xlf", xlf_bytes, "application/xliff+xml")},
data={
"languages": target_lang_uuid,
"title": "Foxit PDF translation batch",
"workflow_id": STRAKER_WORKFLOW_AI_TRANSLATE_AND_EVAL,
"confirmation_required": "false",
},
)
create_resp.raise_for_status()
project_id = create_resp.json()["project_id"]
# 4b. Poll the project until it reports COMPLETED.
while True:
status_resp = requests.get(
f"{STRAKER_BASE}/project/{project_id}", headers=STRAKER_HEADERS
)
status_resp.raise_for_status()
project = status_resp.json()["data"]
if project["status"] == "COMPLETED":
break
if project["status"] in ("FAILED", "PROCESSING_FAILED", "CANCELED"):
raise RuntimeError(f"Straker project {project_id} failed")
time.sleep(3)
# 4c. Fetch the per-segment translations + scores. file_uuid is returned
# in the project payload.
file_uuid = project["source_files"][0]["file_uuid"]
seg_resp = requests.get(
f"{STRAKER_BASE}/project/{project_id}/segments/{file_uuid}/{target_lang_uuid}",
headers=STRAKER_HEADERS,
)
seg_resp.raise_for_status()
results = {}
for seg in seg_resp.json()["segments"]:
element_id = seg["external_id"] # matches the Foxit key we packed into XLF
t = seg["translation"]
results[element_id] = {
"score": t["score"], # float 0.0 to 1.0, or None
"quality": t["quality"], # "best" | "good" | "acceptable" | "bad"
"target_text": t["target_text"], # Straker's translation
}
return results
scored = translate_and_score_with_straker(
extracted_text,
source_lang_code="en",
target_lang_uuid=STRAKER_LANG_FRENCH,
)
# Step 5: Route by score and quality label (developer-controlled business logic).
HIGH_THRESHOLD = 0.85
LOW_THRESHOLD = 0.65
accepted = {}
flagged_for_review = {}
rejected = {}
for element_id, verdict in scored.items():
score = verdict["score"] or 0.0
if verdict["quality"] == "best" or score >= HIGH_THRESHOLD:
accepted[element_id] = verdict["target_text"]
elif verdict["quality"] == "bad" or score < LOW_THRESHOLD:
rejected[element_id] = {"original": extracted_text[element_id],
"score": score, "quality": verdict["quality"]}
else:
flagged_for_review[element_id] = {"translation": verdict["target_text"],
"score": score, "quality": verdict["quality"]}
# Build the render payload. Foxit's render expects every key from the original
# ExtractedText.json. Accepted segments use the scored translation; flagged and
# rejected segments fall back to the original source text so the layout is not
# broken by missing keys. In production, replace the fallback with human-
# reviewed text once it is available, or hold the render step until review
# completes.
render_payload = {}
for element_id, original_text in extracted_text.items():
if element_id in accepted:
render_payload[element_id] = accepted[element_id]
else:
render_payload[element_id] = original_text
# Step 6: Render (async)
# translatedFile is the modified ExtractedText.json with translated values, same keys
translated_json_bytes = json.dumps(render_payload).encode("utf-8")
render_resp = requests.post(
f"{FOXIT_BASE}/documents/translation/render-pdf",
headers=HEADERS,
data={
"sourceDocumentId": source_document_id,
"preprocessResultDocumentId": preprocess_result_id,
"targetLanguage": "fr"
# Optional: "pageRangeStart": 1, "pageRangeEnd": 10
},
files={"translatedFile": ("ExtractedText.json", translated_json_bytes, "application/json")}
)
# Errors from render-pdf per the Foxit spec:
# 400 VALIDATION_ERROR - "Either translatedFile or translatedTextDocumentId must be provided"
# 400 VALIDATION_ERROR - "Unsupported target language: xx"
# 500 RENDER_START_FAILED - "Failed to start render: service unavailable"
render_resp.raise_for_status()
render_task_id = render_resp.json()["taskId"]
render_result = poll_task(render_task_id)
output_doc_id = render_result["resultDocumentId"]
# Step 7: Download translated PDF
pdf_resp = requests.get(
f"{FOXIT_BASE}/documents/{output_doc_id}/download",
headers=HEADERS
)
pdf_resp.raise_for_status()
with open("translated_output.pdf", "wb") as f:
f.write(pdf_resp.content)
print(f"Done. Accepted: {len(accepted)}, Flagged: {len(flagged_for_review)}, Rejected: {len(rejected)}") The render call is multipart/form-data. You pass sourceDocumentId (the original PDF’s document ID from step 1), preprocessResultDocumentId (from step 3), targetLanguage (one of the 23 supported codes), and translatedFile (the modified ExtractedText.json with translated values and original keys). The alternative is uploading the translated JSON first via the upload endpoint and passing its ID as translatedTextDocumentId instead. At least one of the two must be present, or you’ll get a 400 VALIDATION_ERROR.
The render operation is asynchronous. It returns 202 Accepted immediately with a taskId, and the actual rendering runs in the background on Foxit’s side. You must poll GET /tasks/{taskId} on a fixed interval, every 3 seconds is the recommended cadence, until the status flips to COMPLETED before you try to download the output. Skipping the poll, or treating the initial 202 response as if it were a finished render, will cause the program to crash and interrupt the rest of the pipeline because the result document is not yet written when the task is still IN_PROGRESS. The poll_task helper from the first snippet already implements this loop with a 3-second time.sleep between checks and surfaces a FAILED status as a RuntimeError, so reuse it here rather than reading render_resp.json() directly. The same polling discipline applies to the structural extract step (step 2), which is also asynchronous.
Scoring and Routing
Straker AI generates both the translation and the quality signal in this pipeline. Foxit’s responses carry document IDs and task statuses; the translation choice and the per-segment score are entirely Straker’s contribution.
Each segment in the /project/{id}/segments/{file_id}/{language_id} response carries three values you care about. target_text is Straker’s translation. score is a float between 0.0 and 1.0 (it may be null for segments where the model has no confidence signal). quality is a categorical label Straker assigns alongside the numeric score (best, good, acceptable, or bad). You can route on either signal, or combine them. The table below shows a combined policy calibrated for compliance-sensitive documents. These are starting points; your production system should calibrate per language pair and domain, since a French legal contract demands different thresholds than a Spanish marketing brochure.
| Straker verdict | Action | Rationale |
|---|---|---|
quality == "best" or score >= 0.85 | Auto-accept, include in render | High confidence output; suitable for fully automated workflows |
quality in ("good", "acceptable") or 0.65 - 0.84 | Flag segment by element ID for post-edit review | Medium confidence; a human reviewer checks the flagged segments before the final render runs |
quality == "bad" or score < 0.65 | Reject segment, escalate to human translator | Low confidence output; the model is unreliable for this segment |
The element ID key structure matters here. Foxit’s ExtractedText.json keys are packed into XLF trans-unit IDs, and Straker surfaces the same value in its response’s external_id field. That means every entry in your flagged_for_review dictionary carries enough information for a reviewer to open the source document, find the exact element by ID, and return an approved translation. You write the approved translation back into the same key, then trigger the render step. This produces a documentable audit trail. For every element ID in the output PDF, you can show the original text, Straker’s translation, the Straker score and quality label, and whether a human approved it. In regulated industries (finance, legal, healthcare), that’s the evidence your compliance team needs to sign off on an automated localization workflow, and it aligns with ISO 18587, the international standard for post-editing of machine translation output.
Straker AI can also route low-confidence output to expert reviewers automatically when configured through the Straker platform. Check straker.ai/ai-platform/verify for the workflow configuration options.
Layout Preservation
Foxit’s render step preserves multi-column text flow, embedded table cell structure, images at their original positions, headers and footers, and font substitution for target-language character sets. That means CJK scripts (Japanese, Chinese, Korean) render correctly with appropriate glyph substitution, and Arabic output renders right-to-left without manual post-processing.
StructureInfo.json is what makes this possible. When the preprocess step runs, it produces both the text map (which you hand to Straker) and the layout blueprint (which you hand back to Foxit unmodified at render time). The render engine maps translated text back to the original element positions using this blueprint, reflowing text within the same bounding boxes. Because the structure data travels alongside the text through the entire pipeline, Foxit never needs to reconstruct the layout from scratch.
Generic MT pipelines export raw text, losing all spatial relationships, translate it, then attempt to rebuild the PDF from nothing. Tables merge into continuous text, columns collapse to a single flow, and CJK font substitution fails because the rebuilding step has no record of what fonts were originally in use.
Limitations to Test
Text expansion is the first limitation worth stress-testing. English to German translation typically increases text length by 20-35%, and English to Arabic can run even longer. Foxit’s render engine handles reflow within bounding boxes, but extreme length changes in tight table cells or narrow columns may overflow. Test with your actual document types before you commit to a production deployment.
Complex layout edge cases are the second limitation. Overlapping text boxes, embedded SVG charts with text labels, and PDFs with non-standard encoding may produce imperfect renders. The structural extraction step covers standard PDF text elements well, but edge-case layouts require manual review of the rendered output before you sign off on the pipeline for a given document class.
Try It Now
Sign up for Foxit’s free Developer plan and a Straker AI account, grab credentials for both, and run the pipeline from the section above against a real document. An invoice, a multi-page contract, or a regulatory filing works well for testing because each has tables, mixed-column layouts, and high-stakes text segments.
After the render completes, verify four things in the output PDF:
- Tables retain cell structure
- Multi-column text flows correctly in the target language
- Images remain in their original positions
- Fonts render correctly for the target script
Cross-reference the confidence scores from Straker against the rendered segments to calibrate your production thresholds. You may find that legal terminology in German warrants a 0.90 auto-accept threshold while product description text in French is fine at 0.80.
The complete Foxit Translation Trial API reference covers the full parameter list and response schema for preprocess-pdf and render-pdf. The Foxit Structural Extraction Trial API reference documents the structural extract endpoint. Straker’s translation and scoring API documentation lives at straker.ai/ai-platform/verify.
Looking ahead, Straker’s dashboard lists a native Foxit integration as Coming Soon (no release date announced at the time of writing), described as a workflow to translate PDF contracts with Foxit, verify them with experts, and finalize them for signing. When it ships, it’s likely to compress several of the manual steps above into a single call. The underlying mechanics (structural extract, translation, per-segment scoring, routing, render) will remain the same logical stages, so the pipeline you build today stays a useful mental model for reasoning about the native version when it arrives.
For production-scale implementation patterns and how Straker’s translation and verification layer integrates into enterprise localization pipelines, register for the upcoming joint Foxit + Straker.ai webinar with Lee Konstanty from Straker. Get your Foxit API credentials | Get started with Straker AI
PDF Translation API FAQ
What is a PDF translation API with confidence scoring?
A PDF translation API with confidence scoring is a service that translates PDF documents and returns a per-segment quality signal alongside each translation. Instead of handing back a single translated file, the API tells you which segments are high-confidence (safe to auto-accept), which are medium-confidence (queue for human review), and which are low-confidence (escalate to a translator). This pipeline combines Foxit’s PDF Translation Trial API for structural extraction and layout-preserving rendering with Straker.ai for translation and scoring in a single call.
How does the Foxit and Straker.ai PDF translation pipeline work?
The pipeline runs in seven steps: upload the source PDF to Foxit, run structural extraction to get element-ID-keyed text, preprocess to produce ExtractedText.json and StructureInfo.json, send segments to Straker AI’s “AI Translation and Quality Evaluation” workflow which returns translated text plus a 0.0–1.0 score and a quality label, route each segment programmatically by score, then call Foxit’s render endpoint to rebuild the PDF in the original layout. Foxit owns PDF structure, Straker owns translation and scoring, and your code owns the routing decision.
Why do PDFs need per-segment translation quality scores?
For marketing copy, raw machine translation output is usually fine. For contracts, medical forms, clinical trial protocols, or regulatory filings, a 95%-accurate translation can still be legally dangerous because the 5% failure may land on a high-stakes clause — like “indemnification” rendered as “Entschädigung” (compensation) instead of “Freistellung” (hold harmless). Per-segment confidence scores let you route low-confidence segments to human reviewers before they reach the final document, producing the audit trail compliance teams need under standards like ISO 18587.
Can I use DeepL, Google Translate, or AWS Translate instead of Straker.ai?
Yes. The translation step is pluggable. The contract upstream — Foxit element IDs mapped to source strings — and downstream — a dict of element IDs to translated text feeding the render call — does not change if you swap the engine. DeepL, Google Cloud Translation, AWS Translate, or an in-house NMT engine all work. The trade-off is that Straker AI returns translation plus quality score in one call, while other engines require a separate verification step if you want confidence signals.
How does Foxit preserve PDF layout during translation?
Foxit’s preprocess step produces two files: ExtractedText.json with element-ID-keyed text, and StructureInfo.json with the full layout blueprint (bounding boxes, font metadata, column positions, image locations). You modify only ExtractedText.json with translations and pass StructureInfo.json to the render endpoint untouched. The render engine reflows translated text within the original bounding boxes, handles font substitution for CJK and Arabic scripts, and preserves multi-column layouts, tables, and image positions — without rebuilding the PDF from scratch.
What target languages does the Foxit PDF Translation API support?
Foxit’s render endpoint accepts 23 target language codes: en, zh, zh_tw, fr, de, es, it, pt, nl, ja, ko, th, vi, hi, ru, ar, tr, pl, sv, no, nb, da, and fi. Straker AI identifies languages by UUID rather than ISO code, fetched via GET /languages. Your production language coverage is the intersection of both sets — check both APIs before finalizing your language matrix.
How do I set confidence score thresholds for auto-accept versus human review?
A reasonable starting policy for compliance-sensitive documents: auto-accept segments with quality == “best” or score >= 0.85, flag for post-edit review at 0.65–0.84 or quality in (“good”, “acceptable”), and reject for human translation at score < 0.65 or quality == “bad”. These are starting points — calibrate per language pair and domain. A French legal contract may warrant a 0.90 auto-accept threshold while a Spanish marketing brochure is fine at 0.80. Run the pipeline against a representative sample of your real documents and tune from there.
Extract Anything from Any PDF: Inside Foxit’s Advanced Extraction Engine

Basic PDF extraction libraries break on scanned documents, complex tables, and form fields, leaving downstream pipelines starved of clean data. Foxit’s PDF Structural Extraction API combines OCR, layout recognition, and AI parsing to return all twelve PDF element types as structured JSON, ready for RAG, BI, and CRM workflows.
Your PDF extraction pipeline passes unit tests against the sample invoices you built it on. Then production arrives and you’re looking at 47% garbled output on the Q4 contract batch because half those documents are scanned TIFFs wrapped in a PDF envelope, and your extraction library has no concept of what an image-only page actually is.
The failure modes are specific. PyMuPDF’s get_text() returns empty strings on scanned PDFs because it reads content streams directly, and image-only pages carry no text stream. pdfplumber’s table detection merges rows when column widths span non-uniform grids, which is standard in any financial statement that mixes summary and line-item rows on the same page. Embedded images containing meaningful text (stamped signatures, engineering drawing annotations, letterhead logos) get silently dropped. The library extracts coordinates for the XObject reference but does nothing with the raster data inside. Form fields built on non-standard annotation types (AcroForms using widget annotations with custom action streams) lose their values entirely when you serialize to text.
The architectural distinction that creates this problem is the difference between content serialization and semantic extraction. A PDF converter reads a content stream and writes out whatever character sequences it finds in rendering order. An extraction engine understands the spatial relationships between those character sequences: that two columns of text at x=72 and x=320 are parallel body copy, that the row at y=210 belongs to the table starting at y=180, that the text block repeating on every page is a header carrying lower retrieval weight in a RAG index. Output that lacks spatial and semantic classification looks correct on screen but breaks every downstream consumer that depends on structure.
BI dashboards require numbers tied to the right row labels. AI ingestion pipelines require heading hierarchy to chunk accurately. CRMs require form field values extracted from AcroForm widget dictionaries, delivered with field names intact. The delta between what basic extraction libraries return and what those systems can actually consume is where document pipeline engineering hours accumulate.
How Foxit’s PDF Structural Extraction Engine Works Under the Hood
Foxit exposes this capability as the PDF Structural Extraction (Trial) endpoint inside the PDF Services API (POST /pdf-services/api/documents/pdf-structural-extract). Trial status means the schema is versioned at v1.0.7 and may evolve, but the contract is stable enough to build against today, and the endpoint runs against the production base URL at developer-api.foxit.com.
The engine runs three coordinated layers. The OCR layer operates on rasterized page content, recognizing characters from image-based PDFs and scanned documents across 200+ languages. The layout recognition layer applies spatial analysis to identify column boundaries, reading order, table cell boundaries, figure regions, and header/footer zones. The AI-based parsing layer classifies extracted objects semantically, resolving ambiguous blocks (a text run that spans two layout columns, or a figure caption that reads syntactically like a section heading) into typed elements.
All three layers run inside Foxit’s core PDF engine, which powers 700 million+ users across 20+ years of production deployments. That engine has native awareness of PDF internal structures: content streams, XObject dictionaries, AcroForm field trees, and annotation layers. The OCR layer operates on the same internal page representation the rendering engine uses, so it handles annotated PDFs where text overlaps image regions, and form fields where the visual display and stored value diverge.
The same Structural Extraction endpoint is also Step 1 of Foxit’s PDF Translation (Trial) workflow, which signals that the extraction output is structured enough to backbone a full rewrite-and-rerender pipeline.
NVIDIA’s July 2025 NeMo Retriever research on PDF extraction showed that specialized OCR-based pipelines outperform general-purpose vision-language models on retrieval recall and throughput for complex elements including tables, charts, and infographics. VLMs produce plausible-looking output on clean documents but degrade on exactly the edge cases (multi-column scans, mixed-content pages, annotated overlays) that a specialized pipeline handles systematically.
The Full Object Map: All 12 Extractable PDF Element Types
The Structural Extraction schema v1.0.7 defines twelve element types in the type enum: title, head, paragraph, table, image, headerFooter, form, hyperlink, footnote, sidebar, annotation, and formula.
The API exposes no per-object filter parameters. The only request body fields are documentId (required) and password (optional, for protected PDFs). The engine extracts the full element graph and returns everything in one asynchronous round-trip. You filter client-side on the returned JSON. The design is correct for the workload because partial extraction would require re-running layout recognition per request, costing more compute than transmitting the full element set in a single ZIP.
The result is a ZIP archive. At minimum it contains StructureInfo.json, whose top-level analyzeResult object holds version, pages, elements, and info. Documents that contain figures or tables also produce additional binary files (image renditions and table renditions) alongside the JSON, referenced from individual elements so the JSON payload stays manageable on large documents.
Each element in the document-wide flat elements array carries its own id, type, content, region (with page and an 8-point boundingBox polygon), and score confidence value. A table element adds its cell grid. A form element adds field data. An image element points to its binary file in the ZIP. Because title, head, and paragraph elements appear in document reading order in the elements array, they chunk cleanly on semantically correct boundaries, which is what a RAG index needs to return complete, coherent passages.
Each type maps directly to a downstream use case: table feeds financial reporting pipelines, form drives automated CRM data entry, image routes to computer vision workflows or document archives, annotation builds compliance audit trails, and head combined with paragraph elements in reading order feeds RAG ingestion.
API Walkthrough: The Four-Step Async PDF Extraction Flow
There’s no synchronous path. You upload, get a task ID, poll until completion, then download the result ZIP. Every request carries two headers: client_id and client_secret (lowercase snake_case, as specified in the API spec’s security schemes). Both come from the Developer Portal’s default application. Pass them as named HTTP headers on every request and do not use Authorization: Bearer.
The four-step sequence runs as follows:
The four-step sequence diagram uses two headers on every request: client_id and client_secret. Create a free developer account at account.foxit.com/site/sign-up (no credit card required, no sales call). Once you’re in, the credentials live under the default application in the Developer Portal. Copy the Client ID and Client Secret pair and treat them like any other API secret. Pass them as named HTTP headers on every call (lowercase snake_case, not Authorization: Bearer).
Step 1: Upload the PDF to
POST /pdf-services/api/documents/uploadasmultipart/form-datawith the file under field namefile. The 100MB ceiling is enforced with a413and error codeMAX_UPLOAD_SIZE_EXCEEDED. The response body returns{ "documentId": "doc_abc123" }.Step 2: Starts extraction with
POST /pdf-services/api/documents/pdf-structural-extract, passing{ "documentId": "doc_abc123" }. Add a"password"field for protected PDFs. The response is202 Acceptedwith{ "taskId": "task_xyz789" }.Step 3: Polls
GET /pdf-services/api/tasks/{task-id}. TheTaskResponsecarriestaskId,status,progress(0-100 integer),resultDocumentId, and an optionalerrorobject. Thestatusenum values arePENDING,IN_PROGRESS,COMPLETED, andFAILED. Portal narrative copy occasionally uses “PROCESSING,” but the schema enum value isIN_PROGRESS. Match your code against the enum. Poll untilCOMPLETEDand captureresultDocumentId.Step 4: Downloads with
GET /pdf-services/api/documents/{resultDocumentId}/download, which streams the ZIP archive. The optionalfilenamequery parameter overrides the default filename.
The complete cURL sequence for all four steps:
# Step 1: Upload
curl -X POST "https://na1.fusion.foxit.com/pdf-services/api/documents/upload" \
-H "client_id: YOUR_CLIENT_ID" \
-H "client_secret: YOUR_CLIENT_SECRET" \
-F "file=@invoice_batch.pdf"
# {"documentId":"doc_abc123"}
# Step 2: Start extraction
curl -X POST "https://na1.fusion.foxit.com/pdf-services/api/documents/pdf-structural-extract" \
-H "client_id: YOUR_CLIENT_ID" \
-H "client_secret: YOUR_CLIENT_SECRET" \
-H "Content-Type: application/json" \
-d '{"documentId":"doc_abc123"}'
# 202 Accepted: {"taskId":"task_xyz789"}
# Step 3: Poll task status
curl "https://na1.fusion.foxit.com/pdf-services/api/tasks/task_xyz789" \
-H "client_id: YOUR_CLIENT_ID" \
-H "client_secret: YOUR_CLIENT_SECRET"
# {"taskId":"task_xyz789","status":"COMPLETED","progress":100,"resultDocumentId":"result_def456"}
# Step 4: Download the result ZIP
curl "https://na1.fusion.foxit.com/pdf-services/api/documents/result_def456/download" \
-H "client_id: YOUR_CLIENT_ID" \
-H "client_secret: YOUR_CLIENT_SECRET" \
-o extraction_result.zip The Python version with a polling loop and ZIP parsing:
import requests, json, time, zipfile
BASE_URL = "https://na1.fusion.foxit.com/pdf-services/api"
HEADERS = {"client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET"}
# Step 1: Upload
with open("invoice_batch.pdf", "rb") as f:
doc_id = requests.post(
f"{BASE_URL}/documents/upload", headers=HEADERS, files={"file": f}
).json()["documentId"]
# Step 2: Start extraction
task_id = requests.post(
f"{BASE_URL}/documents/pdf-structural-extract",
headers={**HEADERS, "Content-Type": "application/json"},
json={"documentId": doc_id},
).json()["taskId"]
# Step 3: Poll until COMPLETED or FAILED
while True:
task = requests.get(f"{BASE_URL}/tasks/{task_id}", headers=HEADERS).json()
if task["status"] == "COMPLETED":
result_doc_id = task["resultDocumentId"]
break
if task["status"] == "FAILED":
raise RuntimeError(f"Extraction failed: {task.get('error')}")
time.sleep(2)
# Step 4: Download the result ZIP and save it locally for inspection,
# then parse StructureInfo.json from the saved file
response = requests.get(
f"{BASE_URL}/documents/{result_doc_id}/download", headers=HEADERS
)
with open("advanced-extraction-result.zip", "wb") as f:
f.write(response.content)
with zipfile.ZipFile("advanced-extraction-result.zip") as zf:
json_name = next(n for n in zf.namelist() if n.endswith("StructureInfo.json"))
result = json.loads(zf.read(json_name))["analyzeResult"]
print(f"Schema: {result['version']['schema']}, Elements: {len(result['elements'])}")
On a clean run you should see output like Schema: 1.0.7, Elements: 9 for a small invoice batch. You’ll also find a fresh advanced-extraction-result.zip next to your script. That ZIP holds the full API response, including StructureInfo.json and any rendered image or table binaries, so you can inspect everything the engine returned and not just the parsed JSON.
First, set up and activate a Python virtual environment in your project folder. The official venv guide covers the exact commands for macOS, Linux, and Windows.
Once the virtualenv is active, the sample only needs one third-party package. Drop this into a requirements.txt next to your script and install it with pip install -r requirements.txt:
requests>=2.31.0
If you’re on macOS, use Homebrew Python (brew install python) rather than the system Python from the Xcode command-line tools. The Xcode build is linked against LibreSSL, which is enough to make a correct sample fail.
The ZIP contains a StructureInfo.json file whose top-level object wraps everything under analyzeResult. Inside that wrapper you get a version object, a pages array, a flat elements array, and an info block with analysis metadata. Each element carries its own id, type, content, region (with page and an 8-point boundingBox polygon [x1,y1,x2,y2,x3,y3,x4,y4]), and a score confidence value:
{
"analyzeResult": {
"version": {
"schema": "1.0.7",
"software": "FoxitPDFAnalyzer",
"model": "idp-analysis"
},
"pages": [
{
"pageNumber": 1,
"size": { "width": 612, "height": 792, "unit": "point" },
"state": "success"
}
],
"elements": [
{
"id": "title1",
"type": "title",
"content": {
"text": "Q3 Revenue Summary",
"style": {
"fontName": "Helvetica",
"fontSize": 24.0,
"fontWeight": 0,
"fontItalic": false
}
},
"region": {
"page": 1,
"boundingBox": [72, 47, 317, 47, 317, 80, 72, 80]
},
"score": 0.76
}
],
"info": {
"basicInfo": {
"softwareVersion": "1.6.0",
"analyzedPageCount": 1,
"elementCounts": { "title": 1 }
},
"extendedMetadata": {
"pageCount": 1,
"isEncrypted": false,
"hasAcroform": false,
"language": "en"
}
}
}
} Elements of type table, image, and form carry additional type-specific payload on top of this base shape, and any rendered image or table binary lands as a sibling file inside the ZIP referenced from the element.
HTTP errors return a standard error envelope:
{ "code": "VALIDATION_ERROR", "message": "documentId is required" } The documented error codes include VALIDATION_ERROR (400), MAX_UPLOAD_SIZE_EXCEEDED (413), DOCUMENT_NOT_FOUND (404), STORAGE_ERROR, and INTERNAL_SERVER_ERROR (500).
Password-protected PDFs that arrive with no password parameter reach the processing stage before failing. That failure surfaces in the task status poll response after status reaches FAILED, so your error handler must inspect the task response body in addition to the HTTP status codes from the initial POST calls:
{
"taskId": "task_xyz789",
"status": "FAILED",
"progress": 0,
"error": {
"code": "INTERNAL_SERVER_ERROR",
"message": "Document is password-protected"
}
} Wiring Extracted PDF Data Into Your Workflow
Pattern 1: AI/RAG pipeline. Filter the flat elements array to title, head, and paragraph types. Chunk by heading hierarchy, iterating over the array in the order the engine returned it (document reading order is preserved across columns and pages). Embed each chunk and index in Pinecone, pgvector, or your vector store of choice. Correct reading order, as provided by the extraction engine, is the prerequisite for accurate RAG retrieval on multi-column and paginated documents. When chunks split mid-thought because a layout detector merged two columns, retrieval recall drops and answer quality follows.
Pattern 2: BI reporting. Filter elements by type == "table" client-side, then convert each table’s cell structure into a pandas DataFrame:
import pandas as pd
# `result` is the `analyzeResult` object loaded from StructureInfo.json
tables = [e for e in result["elements"] if e["type"] == "table"]
for i, tbl in enumerate(tables):
# Cells live at content.body.cells[]. Each cell carries rowIndex,
# columnIndex, and a nested paragraph whose content.text holds the value.
body = tbl["content"]["body"]
grid = [["" for _ in range(body["columnCount"])] for _ in range(body["rowCount"])]
for cell in body.get("cells", []):
text = cell.get("paragraph", {}).get("content", {}).get("text", "")
grid[cell["rowIndex"]][cell["columnIndex"]] = text
df = pd.DataFrame(grid[1:], columns=grid[0]) # first row as header
print(f"Table {i}: {df.shape[0]} rows x {df.shape[1]} cols")
# df.to_gbq("finance.q3_revenue", project_id="your-project") # BigQuery
# df.to_sql("q3_revenue", engine) # Postgres / Snowflake The row and column indices from the extraction schema map directly to DataFrame positions, so you get a correctly-structured table with zero manual parsing.
Pattern 3: n8n automation. The four-step flow maps to a chain of HTTP Request nodes in n8n. The first node uploads to POST .../upload and passes documentId through the item. The second sends POST .../pdf-structural-extract and captures taskId. A Loop Over Items construct with an HTTP Request node calling GET .../tasks/{taskId} on a two-second interval checks status until COMPLETED, then routes to the download node. The final HTTP Request node calls GET .../documents/{resultDocumentId}/download, and a Code node using n8n’s binary data helpers unpacks the ZIP and parses the JSON for routing to a Salesforce, HubSpot, Postgres, or Airtable node. The polling requirement makes this a multi-node workflow, but you write zero custom glue code and gain n8n’s built-in error routing and retry handling.
PDF Extraction Tools Compared: Foxit vs. Adobe, Google, Amazon, and Azure
| Tool | Underlying Approach | Ecosystem Lock-in | Handles Scanned PDFs | Pricing Model | Setup Overhead | Status |
|---|---|---|---|---|---|---|
| Foxit Structural Extraction | Proprietary OCR + layout recognition + AI (integrated core engine) | Cloud-agnostic REST API | Yes (dedicated OCR layer) | Subscription, no per-page credits | Low (2 credential headers, 4 REST calls) | Trial (schema v1.0.7) |
| Adobe PDF Extract API | Adobe Sensei ML, reading order + renditions | Adobe Document Services | Yes | Contact sales | Medium (Adobe SDK + ecosystem) | GA |
| Google Document AI | Cloud ML + generative AI, Document Object Model | Google Cloud required | Yes | Per-page pay-as-you-go | Medium-high (GCP + IAM) | GA |
| Amazon Textract | Deep learning OCR, key-value and table extraction | AWS-native | Partial (strong on forms, weaker on complex layouts) | Per-page pay-as-you-go | Medium (AWS + IAM) | GA |
| Azure Document Intelligence | Prebuilt + custom ML models | Azure ecosystem | Yes (prebuilt models) | Per-page + model training costs | High for custom models | GA |
Google Document AI and Azure Document Intelligence win on ecosystem integration if you’re all-in on those clouds. Adobe wins on PDF structural fidelity for workflows already inside the Adobe Document Services ecosystem. Amazon Textract excels on standardized form documents where its pre-trained schema fits the input. These are real advantages, and the comparison is honest only when those contexts are acknowledged.
Foxit’s case is strongest when you need a cloud-agnostic REST API with zero ecosystem dependency, full object coverage across all twelve element types, and enterprise throughput (10 to 10,000+ PDFs/day) with SOC 2, GDPR, and HIPAA compliance built in. The Structural Extraction status is a real trade-off to factor in. The schema at v1.0.7 is callable and stable enough for pipeline integration today, but GA competitors carry a finalized contract. Pin your parser to the version field in the response and you’re insulated from schema evolution.
Your First PDF Extraction API Call, Right Now
Go to developer-api.foxit.com, create a free developer account (no credit card required), and copy your Client ID and Client Secret from the default application. Use the built-in API Playground or import the Postman collection from the Developer Portal to run the four-step sequence: upload a real document (an invoice, a multi-page contract, or a scanned form), call pdf-structural-extract with the returned documentId, poll tasks/{taskId} until COMPLETED, then download via documents/{resultDocumentId}/download.
Unzip the result, open StructureInfo.json, and check three things: analyzeResult.version.schema should report 1.0.7, analyzeResult.elements[] should contain at least one table element and one form element if your source document includes those, and the ZIP root should contain the corresponding binary files for any image-type elements. That verification confirms the full extraction pipeline is wired correctly end-to-end.
The same endpoint pattern scales to enterprise volumes. Increase upload and poll concurrency horizontally and the architecture stays identical, with no schema changes, no infrastructure modifications, and no per-page credit consumption to track.
The engineering gap between what basic extraction libraries return and what downstream systems actually consume is where document pipeline hours accumulate. Structural Extraction closes that gap at the API layer, so the complexity stays in the engine and out of your codebase. Get started at developer-api.foxit.com.
PDF Structural Extraction FAQ
What is PDF structural extraction?
PDF structural extraction is the process of identifying and classifying the semantic elements inside a PDF, such as titles, paragraphs, tables, forms, images, and annotations, rather than just pulling raw text. Foxit’s PDF Structural Extraction API returns twelve distinct element types as structured JSON, preserving spatial relationships, reading order, and table cell grids so downstream systems like RAG pipelines, BI dashboards, and CRMs can consume the data without manual parsing.
Can Foxit's API extract text from scanned PDFs?
Yes. Foxit’s PDF Structural Extraction engine includes a dedicated OCR layer that recognizes characters from image-based and scanned PDFs across 200+ languages. The OCR runs on the same internal page representation as the rendering engine, so it handles edge cases like text overlapping image regions, stamped signatures, and engineering drawing annotations that basic libraries like PyMuPDF silently drop.
How does Foxit's PDF extraction API differ from Adobe, Google Document AI, and Amazon Textract?
Foxit’s API is cloud-agnostic with no ecosystem lock-in, requiring just two credential headers and four REST calls. Adobe PDF Extract requires the Adobe Document Services ecosystem, Google Document AI requires GCP and IAM setup, and Amazon Textract requires AWS infrastructure. Foxit also uses subscription-based pricing without per-page credits, while Google, AWS, and Azure all charge per page.
What PDF elements can Foxit's Structural Extraction API identify?
The API identifies twelve element types: title, head, paragraph, table, image, headerFooter, form, hyperlink, footnote, sidebar, annotation, and formula. Each element returns with its content, an 8-point bounding box polygon, page location, and a confidence score. Tables include full cell grids with row and column indices, forms include field data, and images are extracted as separate binary files inside the result ZIP.
How do I call the Foxit PDF Structural Extraction API?
The API uses a four-step asynchronous flow: upload the PDF via POST /documents/upload to get a documentId, start extraction with POST /documents/pdf-structural-extract, poll GET /tasks/{taskId} every two seconds until status is COMPLETED, then download the result ZIP via GET /documents/{resultDocumentId}/download. Authentication uses two headers, client_id and client_secret, available from the default application in the Foxit Developer Portal.
Is the Foxit PDF Structural Extraction API ready for production use?
The endpoint is currently in Trial status with schema version v1.0.7, meaning the contract is stable but may evolve. It runs on the production base URL at developer-api.foxit.com and is built on Foxit’s core PDF engine, which powers 700 million+ users across 20+ years of deployments. For production pipelines, pin your parser to the version field in the response to insulate against future schema changes.
Automate Dynamic PDF Generation with the Foxit DocGen API: Word Templates, JSON Data, and Real API Calls

Skip the HTML-to-PDF headaches. Use Foxit’s DocGen API to turn Word templates and JSON data into clean, formatted PDFs with one API call.
If you’ve tried to generate a contract or invoice from HTML, you’ve probably burned hours on page-break-inside: avoid declarations that Chrome renders one way and a headless browser renders another. Headers and footers require separate print-media queries, and by the time you’ve got a repeating table header working correctly across pages, you’ve invested a full day of engineering into CSS that exists solely to trick a browser into behaving like a printer.
HTML documents reflow content into a viewport while PDF documents have fixed page geometry. Forcing one model into the other produces predictable failure modes: footnotes that collide with page footers, tables that split at the worst possible row, custom fonts that substitute silently, and signature blocks that drift off-page on longer documents.
There’s a larger practical cost too. For most teams, the authoritative source for enterprise document templates is already a Word file. Your legal team owns the NDA in .docx format. Finance owns the invoice in .docx format. Every structural change flows through Word because that’s where the tracked changes, formatting history, and review process live. Maintaining a parallel HTML version of each template doubles your maintenance surface from day one.
Foxit’s DocGen API eliminates that parallel entirely. You keep your templates as .docx files, embed data tags directly in Word, POST the base64-encoded template and a JSON payload to a single REST endpoint, and receive the rendered PDF (or DOCX) in the response body. You eliminate the browser rendering engine, the print-media CSS layer, and the overhead of a second template format.
How the Foxit DocGen API Works
The core model is a single synchronous POST to the GenerateDocumentBase64 endpoint at developer-api.foxit.com. Your request body carries three fields:
base64FileString: your .docx template, base64-encodeddocumentValues: a JSON object containing your merge dataoutputFormat: either"pdf"or"docx"
The API processes the template, resolves every tag against your data, and returns a JSON response containing base64FileString (the rendered document) and a message field confirming success or describing a failure. The exchange is fully synchronous, so you receive the finished document in the same HTTP response with no job ID to poll and no webhook to configure.
Authentication uses two HTTP headers: client_id and client_secret. Both come from the Foxit Developer Portal when you create an account. The free Developer plan provides 500 credits per year with no credit card required, and each GenerateDocumentBase64 call consumes exactly one credit. The Startup plan ($1,750/year) provides 3,500 credits. The Business plan ($4,500/year) covers 150,000 credits for production workloads. For context, Nutrient’s API starts at $75 for 1,000 credits, and Apryse requires a sales conversation before you can access pricing at all.
The complete call flow runs from template file to PDF on disk.
You can explore every endpoint in the live API playground at developer-api.foxit.com, and the portal includes a Postman collection you can import to run authenticated requests without writing a line of code first.
Build a Word Template with DocGen Tags
Open any .docx file in Microsoft Word and type your tags as plain text directly in the document. The DocGen API uses double-brace syntax: {{field_name}}. Tags go anywhere Word accepts text: headings, body paragraphs, table cells, headers, footers, or text boxes.
Scalar field tags resolve directly to the matching key from your documentValues JSON. A document header with {{customer_name}}, {{invoice_number}}, and {{invoice_date}} pulls those three values straight from the top-level keys of your payload.
For arrays, you wrap a single table row (the data row, not the header row) with {{TableStart:array_name}} and {{TableEnd:array_name}} markers. The wrapped row acts as a template row, and the API renders one output row per item in the JSON array. An invoice line-items table in Word looks like this:
| Description | Qty | Unit Price | Total |
|---|---|---|---|
{{TableStart:line_items}}{{description}} | {{qty}} | {{unit_price}} | {{total}}{{TableEnd:line_items}} |
Within the array row, ROW_NUMBER auto-increments with each rendered row. A SUM(ABOVE) field placed in the row directly below the {{TableEnd:line_items}} marker calculates a column total across all rendered data rows.
For nested JSON objects, use dot-notation in your tags. A shipping address block references {{shipping.street}}, {{shipping.city}}, and {{shipping.postal_code}}, mapping to properties nested inside a shipping object in your payload. The nesting can go multiple levels deep, so {{customer.address.city}} resolves against documentValues.customer.address.city.
For a working starting point, grab the downloadable invoice template from the foxit-demo-templates repo. The file is well under the 4 MB upload limit and demonstrates every pattern this article uses: scalar tags, {{TableStart:line_items}} / {{TableEnd:line_items}} with {{ROW_NUMBER}}, currency and date format switches, and subtotal / tax / total fields below the line-items table.
One sizing constraint applies while you build your own template. DocGen rejects uploads larger than 4 MB, so if you embed product photos, scanned letterhead, or full font subsets, compress the images before saving, drop embedded fonts where you can rely on system fonts, or split a large template into smaller per-section templates that you generate and merge separately.
Make Your First API Call: Generate a PDF from JSON
Run a quick pre-flight check before the first call to catch the issues that derail most clean-account run-throughs:
- Account created and
client_id/client_secretcopied from the Developer Portal API Keys section - Sample template saved locally as
invoice_template.docxin the directory you’ll run the script from - Template file size confirmed under 4 MB (
ls -lh invoice_template.docxon macOS or Linux, right-click → Properties on Windows)
With those in place, confirm your credentials work with a cURL call. The Foxit Developer Portal includes a Postman collection for this, but a quick cURL request against the API catches auth issues before any code runs:
curl -X POST "https://na1.fusion.foxit.com/document-generation/api/GenerateDocumentBase64" \
-H "client_id: YOUR_CLIENT_ID" \
-H "client_secret: YOUR_CLIENT_SECRET" \
-H "Content-Type: application/json" \
-d '{"base64FileString":"","documentValues":{},"outputFormat":"pdf"}' A 401 here means invalid credentials. A 400 with a message about the template confirms your headers are accepted and you can proceed to the full call.
Save your .docx template as invoice_template.docx in the same directory as this script, then run the complete generation:
import requests
import base64
CLIENT_ID = "your_client_id"
CLIENT_SECRET = "your_client_secret"
API_URL = "https://na1.fusion.foxit.com/document-generation/api/GenerateDocumentBase64"
# Read and encode the template
with open("invoice_template.docx", "rb") as f:
template_b64 = base64.b64encode(f.read()).decode("utf-8")
# Build the data payload
document_values = {
"customer_name": "Acme Corporation",
"invoice_number": "INV-2025-0042",
"invoice_date": "07/15/2025",
"due_date": "08/14/2025",
"line_items": [
{
"description": "API Integration Consulting",
"qty": 8,
"unit_price": 195.00,
"total": 1560.00
},
{
"description": "Document Automation Setup",
"qty": 1,
"unit_price": 750.00,
"total": 750.00
}
],
"subtotal": 2310.00,
"tax_rate": 0.08,
"tax_amount": 184.80,
"total_due": 2494.80
}
# Construct the request body
payload = {
"base64FileString": template_b64,
"documentValues": document_values,
"outputFormat": "pdf"
}
headers = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"Content-Type": "application/json"
}
response = requests.post(API_URL, json=payload, headers=headers)
if response.status_code == 200:
result = response.json()
pdf_bytes = base64.b64decode(result["base64FileString"])
if pdf_bytes[:5] != b"%PDF-":
raise ValueError("Response did not contain a valid PDF")
with open("invoice_output.pdf", "wb") as out:
out.write(pdf_bytes)
print("PDF written to invoice_output.pdf")
else:
print(f"Error {response.status_code}: {response.json().get('message')}") The success response is a JSON object with three keys: base64FileString (the rendered PDF, base64-encoded), fileExtension ("pdf"), and message ("PDF Document Generated Successfully"). Decoding and writing the bytes to disk gives you a complete, formatted PDF with every tag replaced by its corresponding data value. If you omit a key from documentValues, the API renders the corresponding tag as an empty string, producing a blank field in the output.
Advanced Data Scenarios: Arrays, Nested Objects, and Built-In Functions
The two-row invoice above works, but most production documents have more complex data shapes. Three patterns cover the majority of real-world cases.
For multi-row tables, the line_items array in the Python snippet above already shows the basic structure. To generate five rows, pass five objects in the array. The Word template row tagged with {{TableStart:line_items}} and {{TableEnd:line_items}} repeats exactly once per array item:
{
"line_items": [
{
"description": "UX Design Review",
"qty": 4,
"unit_price": 150.0,
"total": 600.0
},
{
"description": "Backend API Development",
"qty": 12,
"unit_price": 185.0,
"total": 2220.0
},
{
"description": "Database Schema Migration",
"qty": 3,
"unit_price": 200.0,
"total": 600.0
},
{
"description": "QA Testing",
"qty": 6,
"unit_price": 95.0,
"total": 570.0
},
{
"description": "Deployment and Documentation",
"qty": 2,
"unit_price": 175.0,
"total": 350.0
}
]
} The API generates exactly five table rows. Swap in 50 items and you get 50 rows, with page breaks handled by Word’s native pagination logic.
For nested objects, the DocGen API resolves dot-notation paths against the full depth of your JSON structure. A shipping confirmation template referencing {{customer.address.city}} works against this payload without any flattening on your end:
{
"customer": {
"name": "Sarah Chen",
"email": "[email protected]",
"address": {
"street": "742 Evergreen Terrace",
"city": "Portland",
"state": "OR",
"postal_code": "97201"
}
}
} In the Word template, {{customer.name}}, {{customer.address.city}}, and {{customer.address.postal_code}} each resolve to the correct nested value. You can reference the same nested object from multiple locations in the template, and the API populates each instance independently.
For numeric and date formatting, the DocGen API respects Word’s native field switch syntax. Adding \# Currency to a tag formats a numeric value as a currency string, so {{unit_price \# Currency}} renders 195.00 as \$195.00. Date fields accept \@ "MM/dd/yyyy" to control output format, so {{invoice_date \@ "MM/dd/yyyy"}} formats an ISO date string to 07/15/2025. To auto-calculate a column total, place a SUM(ABOVE) field in the Word table row immediately below {{TableEnd:line_items}} and the API evaluates it against the rendered data rows.
Error Handling and Production Readiness
The DocGen API returns a focused set of HTTP status codes. A 200 confirms successful generation. A 401 means your client_id or client_secret headers are invalid, and the fix is to re-copy the credentials from the Developer Portal. A 400 covers three cases. The first is a malformed request body, for example a missing base64FileString or outputFormat. The second is structural issues with the template itself, such as a {{TableStart}} marker placed outside its table row. The third is an oversize template; DocGen rejects .docx uploads larger than 4 MB, and the fix is to compress embedded images, drop embedded fonts, or split the template before re-encoding. The message field in every non-200 response body gives you the specific reason, so log it rather than discarding the response object.
A production wrapper handles all three cases and adds exponential backoff for transient server errors:
import requests
import base64
import time
def generate_document(client_id, client_secret, template_path,
document_values, output_format="pdf"):
API_URL = "https://na1.fusion.foxit.com/document-generation/api/GenerateDocumentBase64"
with open(template_path, "rb") as f:
template_b64 = base64.b64encode(f.read()).decode("utf-8")
payload = {
"base64FileString": template_b64,
"documentValues": document_values,
"outputFormat": output_format
}
headers = {
"client_id": client_id,
"client_secret": client_secret,
"Content-Type": "application/json"
}
max_retries = 3
for attempt in range(max_retries):
try:
response = requests.post(API_URL, json=payload,
headers=headers, timeout=30)
if response.status_code == 200:
return base64.b64decode(response.json()["base64FileString"])
if response.status_code == 401:
raise ValueError("Authentication failed: re-check client_id and client_secret")
if response.status_code == 400:
msg = response.json().get("message", "Bad request")
raise ValueError(f"Request error: {msg}")
if response.status_code >= 500:
if attempt < max_retries - 1:
wait = 2 ** attempt
print(f"Server error ({response.status_code}), retrying in {wait}s...")
time.sleep(wait)
continue
raise RuntimeError(f"Server error after {max_retries} attempts")
except requests.exceptions.Timeout:
if attempt < max_retries - 1:
time.sleep(2 ** attempt)
continue
raise
raise RuntimeError("Max retries exceeded") The wrapper raises immediately on 4xx responses because retrying a credential error or a malformed request produces the same result. Exponential backoff applies only to 5xx responses and timeouts, where the issue is transient.
Once generate_document() returns raw PDF bytes, routing them downstream takes three lines:
import boto3
s3 = boto3.client("s3")
pdf_bytes = generate_document(CLIENT_ID, CLIENT_SECRET, "invoice_template.docx", document_values)
s3.put_object(Bucket="my-documents-bucket", Key="invoices/INV-2025-0042.pdf", Body=pdf_bytes) To attach the output to an email, pass pdf_bytes directly as the smtplib attachment payload. To collect a signature on the generated document, base64-encode the bytes and POST them to Foxit’s eSign API with the signer’s email address in the request body. The full eSign API reference is at docs.developer-api.foxit.com.
Common Mistakes
A short list of the issues that account for almost every failed first run.
- Smart-quote autocorrect on braces. Word’s AutoCorrect can convert the second
{of{{into a curly-quote glyph, which breaks tag parsing silently. Disable “Straight quotes with smart quotes” under AutoCorrect Options, or paste tags as plain text. - Token case sensitivity.
{{Customer_Name}}and{{customer_name}}are different keys. Match the casing in your JSON exactly. TableStartandTableEndmust sit in the same Word table row. Splitting them across two rows, or placing either marker outside the table, leaves the loop unrendered with no error.- Template over 4 MB. The API rejects oversize uploads with a 400. Compress embedded images, drop embedded fonts where system fonts will do, or split the template into smaller pieces.
- Missing payload key. The API renders an unmatched tag as an empty string rather than failing, so a 200 response does not guarantee every field is populated. Spot-check the rendered PDF as part of any pipeline test.
- Auth header typos. Headers are
client_idandclient_secretin snake_case.Client-Id,ClientId, orX-Client-Idall return 401.
Run the Full Invoice Example End-to-End Right Now
Create a free account directly at account.foxit.com/site/sign-up. This skips the pricing-page redirect you hit from the marketing site and drops you straight into the account form.
- Open account.foxit.com/site/sign-up and complete the form (no credit card required).
- After verification, sign in to the Developer Portal and the Developer plan (500 credits per year) is active by default.
- Open the API Keys section and copy your
client_idandclient_secret.
With credentials in hand, run the example end-to-end:
- Download
invoice_full.docxfrom the foxit-demo-templates repo and save it locally asinvoice_template.docxin your working directory. The file is well under the 4 MB upload limit and exercises every tag pattern this article covers. - Paste your credentials into the
CLIENT_IDandCLIENT_SECRETvariables in the Python script from the previous section. - Edit the
document_valuesdictionary with your own customer name, invoice number, and line items. - Run the script and open
invoice_output.pdf.
The free Developer plan’s 500 annual credits cover this tutorial dozens of times over before you spend anything. The full API reference at docs.developer-api.foxit.com covers every endpoint parameter, the complete tag specification, all supported output formats, and the full GenerateDocumentBase64 request and response schema.
Get started with a free account (no credit card required) and generate your first dynamic PDF in under 10 minutes.