How Foxit compares to Google Document AI for document data extraction

Seven Google Document AI processors are being retired in June 2026, pushing teams to look at alternatives. This comparison walks through integration setup, extraction architecture, output schema, and data residency for Foxit’s PDF Structural Extraction API against Google Document AI, so you can decide with real implementation detail instead of a feature list.
Seven Google Document AI processors hit end-of-life on 30 June 2026. Google is retiring the Enterprise Document OCR, Expense, Custom classifier, Custom splitter, Invoice, Pay slip, and Bank statement parsers, and processor versions follow a rolling schedule where each version is deprecated six months after a newer one ships.
For many teams, the deprecation notice does more than prompt a migration ticket. It opens a broader question about whether Google Document AI is still the right foundation for the extraction stack, and what the credible Google Document AI alternatives actually look like once you compare them on implementation detail rather than feature lists.
This article gives you the technical specifics to make that call, comparing the Foxit PDF Structural Extraction API and Google Document AI across five dimensions that drive the real build-vs-switch decision, covering integration overhead, extraction architecture, output schema, document and language coverage, and data residency.
Five axes for evaluating Google Document AI alternatives
Any extraction API comparison lives or dies on the criteria it uses. These five dimensions cover what a production engineering team actually cares about, going well beyond a proof-of-concept benchmark.
Integration complexity measures how many external dependencies you must provision before your first call returns data. A tool that requires a GCP project, service account, IAM role grants, and billing enablement adds meaningful friction before a single byte of document gets processed. For teams with CI/CD pipelines and strict access-control policies, every new cloud dependency is a potential blocker.
Extraction architecture covers how the API reads a document internally, including what happens when a file mixes scanned pages, machine-typed text, and embedded tables in the same document.
Output schema determines how much post-processing your downstream systems require. A flat token list forces you to reconstruct document structure yourself, while a pre-labeled semantic taxonomy reduces that burden before the data reaches your RAG pipeline or BI dashboard.
Document and language coverage sets the practical ceiling on what you can run through the API in production. Language breadth matters especially for multi-region workloads processing invoices or contracts in non-Latin scripts.
Data residency encompasses where documents travel during processing, how long they remain on third-party infrastructure, and what audit evidence you can produce for compliance reviews. For regulated industries, this dimension often decides the question before the others are evaluated.
Integration setup and authentication overhead
Getting to a first call on Google Document AI requires a GCP project, a service account with an IAM role assignment (at minimum roles/documentai.apiUser), billing enablement on the project, and an environment variable pointing to a downloaded service account JSON key. Teams outside the GCP ecosystem absorb all of that as onboarding cost before any extraction runs.
Foxit’s path is shorter. Create a free developer account at the Foxit Developer Portal, retrieve your client_id and client_secret from the default application, and attach them as two HTTP headers on every request. The entire setup takes minutes and requires nothing from GCP.
Prerequisites
To run the code below you need Python 3.8+, the requests library installed into an isolated virtual environment with pip, an editor such as VS Code with the Python extension (PyCharm or Sublime Text work equally well), and a free Foxit developer account from app.developer-api.foxit.com/sign-up to supply the two credential values. Scaffold the workspace in one shot:
mkdir foxit-extract && cd foxit-extract && python3 -m venv .venv && source .venv/bin/activate && pip install requests Extraction then follows a four-step asynchronous workflow, annotated at each step:
export FOXIT_CLIENT_ID="your_client_id"
export FOXIT_CLIENT_SECRET="your_client_secret" Extraction then follows a four-step asynchronous workflow, annotated at each step:
import os
import requests
import time
BASE_URL = "https://na1.fusion.foxit.com/pdf-services/api"
HEADERS = {
"client_id": os.environ["FOXIT_CLIENT_ID"], # lowercase snake_case, not Authorization: Bearer
"client_secret": os.environ["FOXIT_CLIENT_SECRET"]
}
# Step 1: Upload the document (multipart/form-data, field name "file", max 100 MB)
with open("contract.pdf", "rb") as f:
upload_resp = requests.post(
f"{BASE_URL}/documents/upload",
headers=HEADERS,
files={"file": f}
)
document_id = upload_resp.json()["documentId"]
# Step 2: Start structural extraction
extract_resp = requests.post(
f"{BASE_URL}/documents/pdf-structural-extract",
headers=HEADERS,
json={"documentId": document_id}
)
task_id = extract_resp.json()["taskId"]
# Step 3: Poll every 2 seconds until COMPLETED (statuses are uppercase)
result_doc_id = None
for _ in range(60):
status_resp = requests.get(
f"{BASE_URL}/tasks/{task_id}",
headers=HEADERS
)
payload = status_resp.json()
if payload["status"] == "COMPLETED":
result_doc_id = payload["resultDocumentId"]
break
if payload["status"] == "FAILED":
raise RuntimeError(f"Extraction failed: {payload}")
time.sleep(2)
if result_doc_id is None:
raise TimeoutError("Extraction did not complete within 120 seconds")
# Step 4: Download the ZIP archive containing StructureInfo.json
result_resp = requests.get(
f"{BASE_URL}/documents/{result_doc_id}/download",
headers=HEADERS
)
with open("extraction_result.zip", "wb") as out:
out.write(result_resp.content) Authentication uses lowercase snake_case header names on every call. The upload endpoint accepts multipart/form-data with the PDF file under the field name file, with a 100 MB size limit per document.
The four calls against the live API. Note the 202 on the extract call and the COMPLETED status before any download is attempted.
The response shape from that run. Every element sits under analyzeResult, and text elements carry region.boundingBox as an eight-number polygon rather than a four-number rectangle. A table element is the exception, since its region comes back empty and its geometry sits in a regions array instead.
The table below puts both platforms side by side on the integration and output dimensions:
| Dimension | Google Document AI | Foxit PDF Structural Extraction API |
|---|---|---|
| Account setup | GCP project, service account, IAM role, billing | Free developer account, no credit card |
| Authentication | Service account JSON key via GOOGLE_APPLICATION_CREDENTIALS | client_id and client_secret as HTTP headers |
| Call pattern | Synchronous or async depending on processor | Four-step async (upload, extract, poll, download) |
| Output format | Document proto (blocks, paragraphs, tokens) | StructureInfo.json with 12 semantic element types |
| Cloud dependency | GCP-native; Vertex AI integration available | Cloud-agnostic, any stack |
| Language coverage | Varies by processor | 200+ languages via dedicated OCR layer |
Common mistakes and troubleshooting
Four failure modes account for most of the time lost on a first integration. Only the first one reports itself clearly; the other three surface as exceptions in your own code rather than as API errors.
- Sending an
Authorization: Bearerheader : PDF Services authenticates with two separate lowercase headers,client_idandclient_secret. There is no token exchange step and no OAuth flow to implement. This is the one mistake the API names outright, returning HTTP 400 with{"allow": false, "reason": "Missing credentials: provide both 'client_id' and 'client_secret' headers."}. - Treating the extract call as synchronous :
pdf-structural-extractreturns HTTP 202 with ataskId, never the result. Read the status fromGET /tasks/{taskId}, which also returns aprogresspercentage, and note that the values are uppercase (PENDING,IN_PROGRESS,COMPLETED,FAILED). Comparing against lowercase strings produces a poll loop that never exits, which is why the sample above also breaks out onFAILEDand caps its attempts. - Reading
region.boundingBoxon every element : text elements such astitle,head, andparagraphcarryregionas{page, boundingBox}, but atableelement returns an emptyregionand puts its geometry in aregionsarray instead. A loop that assumes one shape raisesKeyErroron the first document containing a table. - Indexing
elementsat the JSON root : every result nests underanalyzeResult, sodata["elements"]raisesKeyErrorwhiledata["analyzeResult"]["elements"]works. The same applies to uploads above the 100 MB per-document limit, which fail at the upload step rather than during extraction.
Extraction architecture, output format, and document coverage
Google Document AI’s processing model is processor-centric. You select a processor type (Invoice Parser, Form Parser, Document OCR), and the service returns a Document proto containing position-anchored blocks, paragraphs, and tokens. Semantic meaning depends on which processor you deployed, so a Form Parser and an Invoice Parser return structurally similar protos but with different field-level annotations.
Foxit’s PDF Structural Extraction API runs three coordinated layers on every document, regardless of document type. The OCR layer handles rasterized content across more than 200 languages. The layout recognition layer maps spatial relationships and table cell grids, resolving multi-column text blocks, overlapping text-image regions, stamped signatures on top of text fields, and engineering drawing annotations. The AI parsing layer then classifies content semantically, assigning each element a type from a fixed taxonomy of twelve labels.
The rendered pipeline. Every document takes the same path, so there is no processor to choose per document type.
Those twelve types appear in StructureInfo.json inside the returned ZIP archive, covering title, head, paragraph, table, image, headerFooter, form, hyperlink, footnote, sidebar, annotation, and formula. Each element carries its reading-order position and spatial coordinates, so the structure your downstream system receives reflects how a human would read the original document rather than raw storage order.
The practical delta shows up in RAG pipeline integration. Google Document AI’s Document proto gives you text and coordinates, but your pipeline needs a post-processing step to decide what each block means semantically. With StructureInfo.json, you filter to table elements, iterate rows, and pass the content directly to your embedding model, because the semantic classification happened upstream.
The output schema comparison below clarifies where each platform puts the interpretive work:
| Schema dimension | Google Document AI (Document proto) | Foxit (StructureInfo.json) |
|---|---|---|
| Structure model | Hierarchical, covering pages, blocks, paragraphs, and tokens | Flat list of semantically typed elements with spatial metadata |
| Semantic labels | Field-level labels tied to specific processor selection | 12 fixed element types, processor-independent |
| Table representation | Cell tokens within a table block | Dedicated table element type with cell grid coordinates |
| Reading order | Implicit (coordinate ordering required client-side) | Explicit, preserved in element sequence |
| Formula support | Limited | Dedicated formula element type |
Document coverage on both platforms is broad. Foxit processes scanned PDFs, image-based PDFs, multi-page contracts, invoices, and form-heavy documents. The layout layer handles edge cases that trip up simpler OCR tools, including stamped signatures overlapping text fields, mixed raster-vector pages, and footnote regions that appear spatially disconnected from their reference markers.
Data privacy and ecosystem independence
Regulated workloads ask two questions before any technical evaluation, starting with where the document goes and what audit evidence you can produce.
Foxit’s API compliance page documents SOC 2 Type II independent audit, HIPAA-aligned features with Business Associate Agreement (BAA) support, and GDPR-supporting features including redaction, anonymization, and secure metadata handling. Foxit’s AI service documentation states that input documents and results are held temporarily and deleted within 24 hours. If your organization requires a BAA, Foxit can provide one.
Google Document AI routes all processing through GCP infrastructure. Teams subject to data residency requirements need to select the appropriate GCP region, review Google’s data processing addendum, and confirm their cloud agreement covers the specific data types being processed. That review is standard for teams already operating within GCP, but it adds a compliance surface for teams that are not.
Foxit’s API is cloud-agnostic. Your team calls it from any existing stack, passing two credential headers, and extracts documents without spinning up a GCP project, provisioning a storage bucket, or accepting GCP billing terms. For teams evaluating outside GCP, that independence cuts both technical and commercial risk from the decision.
When to use Google Document AI and when to use Foxit
The right choice depends on your existing infrastructure and what your extraction output needs to do.
| Scenario | Best fit | Key reason |
|---|---|---|
| Teams already deep in GCP who want Vertex AI integration | Google Document AI | Native Vertex AI pipeline support and Google-managed processor versions reduce ops overhead |
| High-volume PDF processing outside the GCP ecosystem | Foxit | Cloud-agnostic with credit-based pricing, with no GCP billing or IAM dependency |
| Workloads with strict data residency or BAA requirements | Foxit | SOC 2 Type II audit, HIPAA-aligned features with BAA support, and GDPR-supporting features |
| Teams that need semantic element classification ready for downstream consumption | Foxit | StructureInfo.json delivers 12 pre-labeled element types without a client-side post-processing step |
The fourth scenario is worth walking through in detail. Your team has a contract review pipeline that needs to extract all tables and footnotes from multi-page PDFs and push them into a downstream system. With the Foxit API, the workflow runs like this:
- Upload the PDF to
/pdf-services/api/documents/uploadand receive adocumentId. - POST to
/pdf-services/api/documents/pdf-structural-extractwith thedocumentIdand receive ataskId. - Poll
/pdf-services/api/tasks/{taskId}every two seconds untilstatusequalsCOMPLETED. - Download the result ZIP from
/pdf-services/api/documents/{resultDocumentId}/downloadand parseStructureInfo.json.
Once you have StructureInfo.json, filtering to table and footnote elements is a single-pass list comprehension. The labeled elements arrive with spatial coordinates and reading order intact, so your downstream system receives structured, ordered data ready for indexing, embedding, or display, with no second model call, no coordinate sorting, and no block-level classification required.
Teams running active Vertex AI pipelines in GCP, with processors not among the seven being retired, have no technical reason to switch. For everyone else, the four API calls above give you a working extraction against your own documents in minutes.
Google Document AI FAQ
What is Google Document AI?
Google Document AI is a managed cloud service for document parsing and data extraction, built on GCP processors. You select a processor type (such as Invoice Parser, Form Parser, or Document OCR), send a document via the API, and receive a structured Document proto containing text, coordinates, and field-level annotations. All processing runs on Google Cloud Platform infrastructure.
How does the Foxit PDF Structural Extraction API differ from Google Document AI?
Foxit’s API runs three coordinated processing layers on every document (OCR, layout recognition, and AI parsing) regardless of document type, while Google Document AI uses a processor model where semantic classification depends on the specific processor you select. The output schemas also differ. Foxit returns StructureInfo.json inside a ZIP archive with twelve pre-labeled element types preserving reading order and spatial relationships, while Google Document AI returns a Document proto with hierarchical blocks, paragraphs, and tokens that require client-side semantic interpretation. Foxit is also cloud-agnostic and needs no GCP project, while Google Document AI is GCP-native.
What are Foxit’s data-handling and compliance commitments for the extraction API?
Foxit’s API compliance page documents SOC 2 Type II independent audit, HIPAA-aligned features with Business Associate Agreement (BAA) support, and GDPR-supporting features including redaction, anonymization, and secure metadata handling. Foxit’s AI service documentation states that input documents and results are held temporarily and deleted within 24 hours. Foxit does not claim HIPAA certification or GDPR certification, and the API compliance page does not state that documents are never stored, so teams with specific retention requirements should review the documentation directly and request a BAA where applicable.
What output format does the Foxit PDF Structural Extraction API return?
The API returns a ZIP archive containing StructureInfo.json. That file classifies every element in the document using one of twelve labeled types, including title, head, paragraph, table, image, headerFooter, form, hyperlink, footnote, sidebar, annotation, and formula. Each element includes spatial coordinates and reading-order position, so the structure your downstream system receives reflects how a human would read the original document. Table elements carry cell grid coordinates, making row-level data extraction straightforward without additional parsing.
Can I try the Foxit PDF Structural Extraction API without a paid plan?
Yes. Create a free developer account at app.developer-api.foxit.com/sign-up. No credit card is required. Once you register, your client_id and client_secret are available immediately in the Developer Portal, and you can run extractions against your own documents using the API Playground or the downloadable Postman collection.
How does Foxit handle scanned or image-based PDFs?
Foxit’s OCR layer processes rasterized content across more than 200 languages, so scanned PDFs and image-based documents (including TIFFs) are processable without pre-conversion. The layout recognition layer then maps spatial relationships and resolves edge cases such as multi-column text blocks, overlapping text-image regions, and footnote regions that appear spatially disconnected from their reference markers.
Which document types does Google Document AI support after the June 2026 deprecations?
After 30 June 2026, Google is retiring the Enterprise Document OCR, Expense, Custom classifier, Custom splitter, Invoice, Pay slip, and Bank statement processors. Remaining processors (including Form Parser and Document OCR for non-deprecated versions) continue to operate on their own rolling deprecation schedule, where each version is deprecated six months after a newer one ships. Teams relying on any of the seven retired processors need to migrate before that date.
Conclusion
Across all five axes, the practical difference between Google Document AI alternatives comes down to how much infrastructure you take on to reach a first result. Foxit requires two credential headers. Google’s setup adds a GCP project, service account, IAM configuration, and billing enablement before you process a single document. Foxit’s three-layer extraction model (OCR, layout recognition, AI parsing) delivers semantic classification across every document type without processor selection. StructureInfo.json‘s twelve labeled element types reduce client-side post-processing compared to Google’s Document proto. Both platforms handle the major document types, and Foxit’s 200-plus language OCR covers non-Latin scripts across all document categories. Foxit’s SOC 2 Type II audit, HIPAA-aligned BAA support, and GDPR-supporting features give regulated teams a documented compliance baseline, and the cloud-agnostic model means your team runs document extraction without taking on GCP billing, IAM governance, or ecosystem lock-in.
Create a free developer account at app.developer-api.foxit.com/sign-up, no credit card required, and run the four-step extraction against your own document today.
6 Best DocuSign API Alternatives for Developers in 2026

Comparing a DocuSign API alternative can eat hours of research time. This guide breaks down six eSign APIs, including Dropbox Sign, Adobe Acrobat Sign, PandaDoc, SignNow, BoldSign, and Foxit eSign, against the six criteria that matter most for integration speed and long-term maintenance.
DocuSign’s API works, but redirecting signers to an external DocuSign-hosted page puts a seam in your user experience you can’t fully control, pricing tiers require a sales call to decode, and per-envelope costs escalate unpredictably at scale. If you’ve already decided DocuSign isn’t the right fit, this roundup gives you a structured way to narrow the field fast.
Six alternatives are covered here (Dropbox Sign, Adobe Acrobat Sign, PandaDoc, SignNow, BoldSign, and Foxit eSign), evaluated against six criteria that directly affect integration time and long-term maintainability. Each tool is broken down the same way, so you can compare like against like rather than marketing page against marketing page.
What to evaluate in an eSign API
The six criteria below separate APIs worth building on from ones that will cost you significant refactoring time later. Pin them down before you compare options.
Embedded signing depth. An iframe-based session keeps signers inside your application, while a redirect-based session hands them off to a third-party URL. The delta between “supports embedded signing” and “delivers a fully iframe-native experience” is significant.
Auth model. OAuth2 client credentials gives your backend a machine-to-machine token with no user interaction required. API key auth is simpler but typically coarser in permission scope and harder to rotate safely at scale.
Webhook event granularity. A single “document completed” event isn’t enough if your workflow needs to react to individual signer events, field changes, or expiration triggers. Check what event names are actually documented, not listed on a marketing page.
SDK language coverage. Confirm whether the vendor ships official SDKs for Python, Java, Node.js, and Go. If raw REST calls are your only option, factor in the maintenance overhead for your team.
Compliance certifications. eIDAS, ESIGN, UETA, HIPAA, GDPR, and 21 CFR Part 11 have different requirements. Confirm which certifications are documented and current, not featured in a hero banner.
Pricing model transparency. Envelope-based, seat-based, and consumption-based pricing each carry different risk profiles at scale. If you can’t read the pricing page without talking to sales, add that friction to your evaluation score.
The six alternatives at a glance
The table summarizes where each tool lands on the criteria above. Treat it as a shortlist filter, then read the section for any tool that survives. Compliance and pricing move often, so the linked pages are the source of truth, not this table.
| Tool | Auth | Embedded signing | Webhooks | Official SDKs | Pricing model |
|---|---|---|---|---|---|
| Dropbox Sign | OAuth2 + API key | Iframe via sign_url | Signer-level events | Python, Node, Java, Ruby, PHP | API tier, published |
| Adobe Acrobat Sign | OAuth2 | Transient docs + widgets | Extensive | Java, plus REST | Enterprise, sales-led |
| PandaDoc | OAuth2 + API key | Iframe (send + sign) | Document lifecycle | Node, Python, plus REST | Document/seat-based |
| SignNow | OAuth2 + API key | Embedded session URLs | Functional, coarser | Fewer official SDKs | Per-envelope, published |
| BoldSign | OAuth2 + API key | Iframe embedded | Documented events | .NET, Java, Node, Python | Tiered, transparent |
| Foxit eSign | OAuth2 client credentials | Iframe / web view, no redirect | 9 events incl. folder_executed, HMAC-signed | REST, examples in Python | Tiered, published |
Dropbox Sign
Dropbox Sign (formerly HelloSign) runs a clean REST API with solid embedded signing and documentation that developers consistently rate as approachable. If you’re already in the Dropbox ecosystem and don’t need heavy customization, it provides a reliable, well-documented API. But it does have thinner webhook payloads and narrower embedded-UX control than purpose-built full-control APIs.
- Auth model. OAuth2 for multi-account apps, plus straightforward API key auth for single-account integrations.
- Embedded signing. Embedded requests return a
sign_urlyou load directly into an iframe, keeping signers in your app. - Webhook granularity. Events fire at each signer-level state change, though payloads are less granular than the top-tier options.
- SDKs. Official SDKs for Python, Node.js, Java, Ruby, and PHP.
- Compliance. Positioned for general business use; confirm the current certification list in their docs before relying on a specific standard.
- Pricing model. API pricing is published as its own tier, separate from the end-user product.
See the developer docs and API pricing.
Dropbox Sign’s developer documentation. The organized reference and SDK list are the reason it scores well on the docs-quality criterion.
Adobe Acrobat Sign
Adobe Acrobat Sign brings enterprise-scale infrastructure and a deep compliance footprint to its REST API, at the cost of a larger, more complex surface area. It’s a reasonable fit for large enterprises already standardized on Adobe Document Cloud with compliance needs that benefit from Adobe’s footprint. On the other side, it also has the largest integration overhead on this list and pricing that is not self-serve.
- Auth model. OAuth2, integrated with Adobe’s broader identity and Document Cloud platform.
- Embedded signing. Supported via Transient Documents and widget-based flows rather than a single drop-in iframe call.
- Webhook granularity. Extensive event coverage, appropriate for large multi-step enterprise workflows.
- SDKs. An official Java SDK plus a broad REST surface; other languages typically integrate at the REST level.
- Compliance. Strong certification footprint aimed at healthcare, finance, and government; verify the specifics for your regulatory context.
- Pricing model. Enterprise-tier and sales-led; expect a conversation rather than a public per-call rate.
See the developer guide and Adobe’s Acrobat business pricing page.
The Acrobat Sign API overview. The breadth here is the point, and also the integration-overhead warning.
PandaDoc
PandaDoc’s API sits closer to document-creation-plus-signing than pure eSignature, which is a strength if you need both from one integration. It works well for building quote-to-sign or proposal-to-signature workflows where generation and signing happen through one API. The tradeoffs are document-based pricing that adds up at volume, and thinner signing-order controls than purpose-built eSign APIs.
- Auth model. OAuth2 and API key options.
- Embedded signing. Embedded sending and signing via iframe, alongside template-driven document generation.
- Webhook granularity. Document-lifecycle events covering creation, sending, and completion.
- SDKs. Official Node.js and Python SDKs, plus a documented REST API.
- Compliance. Business-grade; confirm the current list against your requirements in their docs.
- Pricing model. Document-centric and can climb at high envelope volumes, so model your cost at target scale.
See the developer documentation and pricing.
PandaDoc’s developer hub. Document generation sitting next to signing is what distinguishes it from pure eSign APIs.
SignNow
SignNow offers a capable REST API that is frequently competitive on per-envelope cost at volume, which makes it a common pick for high-throughput, straightforward signing. It’s a cost-sensitive option that can handle high-volume, straightforward signing if you don’t have any complex embedded-UX requirements. However, its coarser webhooks and narrower SDK coverage will push you toward raw REST.
- Auth model. API key and OAuth2 authentication.
- Embedded signing. Embedded session URL generation for in-app signing.
- Webhook granularity. Functional, but event types are coarser than the top-tier options.
- SDKs. Narrower official SDK coverage, so expect more raw REST work outside the main supported languages.
- Compliance. Business and industry compliance is advertised; verify the current certifications in their docs.
- Pricing model. Per-envelope pricing that is published and tends to reward volume.
See the API documentation and pricing.
SignNow’s REST API documentation. Envelope creation, signer routing, and embedded session URLs are all covered here.
BoldSign
BoldSign is a developer-first eSign API with a clean REST interface and pricing that is more transparent than most enterprise alternatives at the lower tiers. This option offers a modern, well-documented API with straightforward pricing, outside the most heavily regulated industries. Worth noting is a smaller compliance footprint than the established players.
- Auth model. OAuth2 and API key options.
- Embedded signing. Solid iframe-based embedded signing built for developer integration.
- Webhook granularity. Documented event types suitable for most integration workflows.
- SDKs. Official SDKs including .NET, Java, Node.js, and Python.
- Compliance. A newer entrant with a smaller certification footprint than established players, so verify current standards before committing in a regulated industry.
- Pricing model. Tiered and transparent, published without a mandatory sales call at the lower tiers.
See the developer portal and pricing.
The BoldSign Developer Hub. Transparent pricing and a self-serve sandbox are its main developer-experience draws.
Foxit eSign
Foxit eSign gives developers full control over the signing experience, with no redirect to an external Foxit-hosted page at any point. This is the tool covered in the most technical depth here, and the getting-started section below runs against its live API.
- Auth model. OAuth2 client credentials. Your backend gets a machine-to-machine Bearer token with no user login in the loop.
- Embedded signing. Signing sessions load inside an iframe or web view within your own application. You control the header, sidebars, and the exact page signers land on after finishing.
- Webhook granularity. Nine event types, including
folder_executed, and every callback is signed with an HMAC-SHA-256 digest of the raw body so you can verify authenticity. - SDKs. A documented REST API with worked examples; the getting-started code below is Python.
- Compliance. eIDAS at the AES and QES levels (QES requires pairing with a qualified trust service provider), plus the ESIGN Act, UETA, HIPAA, GDPR, 21 CFR Part 11, CCPA, FINRA, FERPA, and SOC 2 Type II infrastructure.
- Pricing model. Tiered and published, with a free developer account to build against.
The Foxit eSign embedded signing session, loaded in-app. Text tags in the source PDF are parsed into the interactive Full name, initial, date, and signature fields shown here, with no redirect to an external page.
Signing order control
Setting signInSequence to false on a folder request puts all recipients into parallel mode, while leaving it true enforces the sequence you define. Hybrid flows mix both, so some signers proceed in parallel while others wait on prior steps.
Compliance coverage
Full details live at the Foxit compliance page and the Foxit Trust Center.
Best for development teams that need full embedded-signing control, flexible signer routing, and broad compliance coverage from a single integration, especially in regulated industries.
Watch out for planning your regional endpoint (the instance_url returned at auth) into your configuration rather than hardcoding one.
Getting started with the Foxit eSign API
Three steps take you from zero to your first signed document. The code below runs end to end against the live API.
The Foxit eSign dashboard you land on after signing in. The API you are about to call drives the same envelopes shown here.
Step 1. Activate the API tab. Log into your Foxit eSign account, navigate to Settings, and open the API tab. Fill out the form to receive your client_id and client_secret.
The API Consumer Credentials screen. Foxit masks the client id, secret, and access token by default and requires a one-time passcode to reveal them, which is the credential-handling behavior worth knowing before you build.
Step 2. Obtain a Bearer token. POST to the regional OAuth2 endpoint with a form-encoded body (sending a JSON body returns HTTP 415 Unsupported Media Type). The response includes access_token, token_type, expires_in, and instance_url.
Step 3. Create an envelope and register a webhook. Use the Bearer token in the Authorization header to create an envelope (Foxit calls it a folder) from a source document, then register a webhook targeting the folder_executed (EXECUTED) event to be notified once every party has signed and the document is executed.
The code reads credentials from environment variables. It exchanges credentials for a token, then creates a draft envelope from a sample PDF without emailing anyone.
import os
import requests
# The token endpoint requires a form-encoded body
# (application/x-www-form-urlencoded). Sending a JSON body returns
# HTTP 415 Unsupported Media Type.
TOKEN_URL = "https://na1.foxitesign.foxit.com/api/oauth2/access_token"
# Step 1: Exchange credentials for a Bearer token.
token_response = requests.post(
TOKEN_URL,
data={ # use data= (form-encoded), NOT json=
"grant_type": "client_credentials",
"client_id": os.environ["FOXIT_ESIGN_CLIENT_ID"],
"client_secret": os.environ["FOXIT_ESIGN_CLIENT_SECRET"],
"scope": "read-write",
},
)
token_response.raise_for_status()
token_data = token_response.json()
access_token = token_data["access_token"] # Bearer token
instance_url = token_data["instance_url"] # already a full URL, e.g. https://na1.foxitesign.foxit.com/
base = instance_url.rstrip("/") # trim trailing slash; do NOT re-add https://
# Step 2: Create an envelope (folder) from a document.
# sendNow=False creates a DRAFT and emails no one.
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
payload = {
"folderName": "Service Agreement",
"fileUrls": ["https://your-app.example.com/agreement.pdf"],
"fileNames": ["agreement.pdf"],
"sendNow": False, # DRAFT; set True to dispatch to signers
# signInSequence True = signers proceed in the sequence you define
# signInSequence False = all signers receive the document in parallel
"signInSequence": True,
"parties": [
{
"firstName": "Jane",
"lastName": "Doe",
"emailId": "[email protected]",
"sequence": 1,
}
],
}
resp = requests.post(f"{base}/api/folders/createfolder", headers=headers, json=payload)
resp.raise_for_status()
folder_id = resp.json()["folder"]["folderId"] # the id nests under "folder"
print("Envelope created:", folder_id) The code above reads your client id and secret from the environment, POSTs them form-encoded to the regional token endpoint, and reads the access_token and instance_url from the response. Because instance_url is already a complete URL, you strip its trailing slash and use it directly rather than prepending a scheme. You then POST to /api/folders/createfolder with the source document, the signing parties, and sendNow set to false so the envelope is created as a draft without notifying anyone, and read the new folder’s id from folder.folderId in the response.
Registering the executed webhook
You register webhooks once in the eSign portal’s API settings, not through the token flow above. Add your endpoint URL and a webhook secret, then enable the events you care about. The screenshot below shows the real configuration screen with folder_executed selected.
The Configure Webhooks page. Note the nine event checkboxes, folder_executed selected, and the field note confirming each request is signed with a Base64 HMAC-SHA-256 digest of the raw body.
folder_executed fires when all parties have signed and the document reaches the EXECUTED state, which is the point at which the completed, legally binding PDF is ready to archive. Foxit delivers each event as an HTTP POST with the signature appended as a query parameter (?signature=...), where the signature is the Base64-encoded HMAC-SHA-256 of the raw request body keyed with your webhook secret. Recompute that digest on receipt and compare it before you act on the callback.
import base64, hashlib, hmac
def verify_webhook(raw_body: bytes, signature: str, secret: str) -> bool:
"""Return True only if the callback's signature matches the raw body."""
expected = base64.b64encode(
hmac.new(secret.encode(), raw_body, hashlib.sha256).digest()
).decode()
return hmac.compare_digest(expected, signature) The full API reference is at developersguide.foxitesign.foxit.com.
Docusign API FAQ
What is an eSignature API?
An eSignature API lets your application send, track, and complete legally binding signature requests without building a separate signing portal. Your app calls the endpoints to create the workflow, route the document to signers, capture their signatures, and pull the completed, audit-ready record, all without anyone leaving your product.
What are the best DocuSign API alternatives for developers in 2026?
Six strong alternatives worth evaluating are Dropbox Sign (well-documented, fits the Dropbox ecosystem), Adobe Acrobat Sign (enterprise compliance depth), PandaDoc (proposal-to-signature workflows), SignNow (cost-effective at volume), BoldSign (developer-first, clean REST interface), and Foxit eSign (full embedded control and multi-standard compliance across eIDAS, ESIGN, UETA, HIPAA, GDPR, and 21 CFR Part 11).
Does the Foxit eSign API support embedded signing?
Yes. Signing sessions load inside an iframe or web view within your own application, with no redirect to an external Foxit page. You can customize headers and sidebars, and configure where signers land after completing the document. The experience stays inside your product throughout.
What compliance standards does the Foxit eSign API meet?
Foxit eSign meets eIDAS at the AES (Advanced Electronic Signature) and QES (Qualified Electronic Signature) levels (QES requires pairing with a qualified trust service provider). Additional certifications include the ESIGN Act, UETA, HIPAA, GDPR, 21 CFR Part 11, CCPA, FINRA, FERPA, and SOC 2 Type II infrastructure. Full details are at the Foxit compliance page.
How do I get started with the Foxit eSign API?
Create an account at developer-api.foxit.com, activate the API tab in your eSign account settings to receive your client_id and client_secret, then POST to https://na1.foxitesign.foxit.com/api/oauth2/access_token with a form-encoded body to obtain a Bearer token. Use that token in the Authorization header to make your first envelope call.
How does OAuth2 client credentials auth work in the Foxit eSign API?
Your backend POSTs a form-encoded request to the regional token endpoint using your client_id and client_secret. The response returns a Bearer token with a defined expiry and a region-specific instance_url. Every subsequent API call passes that token in the Authorization header, with no session-level user login required at any point.
What webhook events does the Foxit eSign API support?
You register webhooks through the eSign API Settings page and configure them to fire on specific event types, nine in total, spanning sent, viewed, signed, cancelled, executed, deleted, completed, assigned, and access-code-failure. The folder_executed event fires when all parties have completed signing. Foxit signs each webhook POST with an HMAC-SHA-256 digest of the raw body, giving you a verifiable authenticity signal on every inbound notification.
How does Foxit eSign handle parallel and sequential signing flows?
Setting signInSequence to false on a folder request sends the document to all recipients simultaneously. Setting it to true enforces the order you define in the sequence field on each party. Hybrid flows combine both modes, so some signers proceed in parallel while others wait on prior steps, all from a single API call.
Which eSign API is best for regulated industries?
Foxit eSign covers the broadest compliance footprint across eIDAS (AES and QES), HIPAA, GDPR, 21 CFR Part 11, FINRA, FERPA, CCPA, and SOC 2 Type II. Adobe Acrobat Sign also carries strong enterprise certifications relevant to healthcare and finance. Teams in regulated industries should verify current certification status directly with each vendor before committing.
What is the difference between envelope-based and consumption-based eSign pricing?
Envelope-based pricing charges a fixed fee per document sent for signature, which makes costs predictable at low volumes but expensive at scale. Consumption-based pricing ties costs to actual usage metrics (API calls, active users, or data volume), which can reduce spend at high volume but introduces budget variability. Seat-based pricing charges per licensed user regardless of volume, which suits teams with consistent, predictable signing activity.
Picking the right eSign API
The six criteria (embedded signing depth, auth model, webhook event granularity, SDK language coverage, compliance certifications, and pricing transparency) cut the field quickly when you apply them consistently.
Dropbox Sign fits teams in the Dropbox ecosystem who want reliable coverage without high complexity. Adobe Acrobat Sign suits large enterprises with existing Adobe infrastructure and deep compliance footprints. PandaDoc is the right call for proposal-to-signature workflows. SignNow works for cost-sensitive, high-volume signing at scale. BoldSign offers a clean developer experience outside the most heavily regulated industries.
If you need full embedded-signing control, flexible signer routing, and compliance coverage across eIDAS, HIPAA, GDPR, and 21 CFR Part 11 bundled without piecing those certifications together from add-ons, Foxit eSign is worth a close look. Once a folder reaches the EXECUTED state, the completed document carries a full audit trail and signer certificate, which is what you archive as the legal record.
An executed Foxit eSign agreement. The EXECUTED state is the archival point the folder_executed webhook announces.
Visit developer-api.foxit.com to create a free developer account and try the full signature flow with no commitment.
How to Turn PDFs into Structured Data with Foxit’s PDF Structural Extraction API

PDF data extraction with Foxit’s Structural Extraction API turns messy invoices and tables into typed JSON, complete with bounding regions and addressable cells. This tutorial walks through the four REST calls, upload, extract, poll, and download, and shows working Python code that builds a clean dictionary from an invoice’s line items. It also covers common mistakes like case-sensitive auth headers and stale document IDs.
Pull text out of a multi-column invoice and you get a flat string with column headers mixed into values, row boundaries gone, and field labels indistinguishable from the data they describe. Foxit’s PDF Structural Extraction API returns typed JSON instead, where every element carries a type, its text, a bounding region, and, for tables, an addressable grid of cells.
This tutorial walks the four REST calls that get you there, uploading a PDF, starting the analysis, polling the task, and downloading the result. By the end you’ll have working Python code that turns an invoice into a dictionary your pipeline can address by key.
Raw text vs. structured extraction
What separates raw text extraction from structured extraction is the shape of the output, not the accuracy of the characters.
Take a vendor invoice with a line-item table covering description, quantity, and unit price. Text extraction returns something like "1 API Integration Consulting 10 $ 150.00 $1,500.00". The content is all there, but the row and column relationships are gone, so your parsing code has to reconstruct structure the PDF already encoded, and it has to do that differently for every layout you encounter.
Structured extraction preserves what raw text discards. The pdf-structural-extract endpoint returns each element with a type, a content object holding the text and its font styling, and a region giving the page number and bounding polygon. Tables come back as a cell grid with explicit rowIndex and columnIndex values, so a cell’s position is data rather than something you infer from coordinates.
Prerequisites
- Python 3.8+ with pip and a virtual environment via venv.
- The requests library for the HTTP calls.
- curl if you want to try the endpoints before writing code.
- A code editor, VS Code with the Python extension is a good default, though PyCharm or Sublime Text work equally well.
- A Foxit Developer account, free with no credit card, created at app.developer-api.foxit.com/sign-up. Activate the Developer plan (500 credits per year) and copy the Client ID and Client Secret from the APIs Dashboard.
- A sample PDF, so you do not have to build one. This tutorial uses invoice_table_test.pdf, a one-page invoice with a five-column line-item table.
Scaffold the workspace in one shot:
mkdir foxit-extract && cd foxit-extract
python3 -m venv .venv && source .venv/bin/activate
pip install requests
curl -L -o invoice.pdf https://github.com/lucienchemaly/foxit-demo-templates/raw/main/invoice_table_test.pdf
export FOXIT_CLIENT_ID="your_client_id"
export FOXIT_CLIENT_SECRET="your_client_secret" Here is the invoice the rest of the tutorial extracts from.
The source document. The five-column table and the labeled fields above it are what the extraction turns into addressable JSON.
Authentication
PDF Services authenticates with two named request headers on every call, client_id and client_secret, both lowercase with an underscore. There is no OAuth exchange and no bearer token, and wrapping the credentials in an Authorization: Bearer header returns a 400 instead. The base host for every endpoint in this tutorial is https://na1.fusion.foxit.com/pdf-services.
Keep the values in environment variables rather than in the file, so nothing secret travels with your code.
The four-call extraction flow
Structural extraction is an asynchronous job, so it runs in four steps.
The four calls and what each one hands to the next. The id you download with comes from the finished task, not the upload.
- Upload the PDF and receive a
documentId. - Start the analysis against that id and receive a
taskId. - Poll the task until its
statusreachesCOMPLETED, which also returns aresultDocumentId. - Download the result, a ZIP archive holding the structured JSON.
Step 1: Upload the document
Send the PDF as multipart/form-data to the upload endpoint, using the form field name file.
curl -X POST "https://na1.fusion.foxit.com/pdf-services/api/documents/upload" \
-H "client_id: $FOXIT_CLIENT_ID" \
-H "client_secret: $FOXIT_CLIENT_SECRET" \
-F "[email protected]" The -F flag is what makes curl send a multipart body, and the @ prefix tells it to read the file from disk rather than treat the value as a literal string. Uploads are capped at 100 MB, and an uploaded document is deleted after 24 hours, so treat the documentId as short-lived rather than a permanent handle.
A successful upload returns a single key:
{
"documentId": "6a6c9834a820c33d30d222e5"
} Step 2: Start the structural analysis
POST that id to the extraction endpoint with a JSON body.
curl -X POST "https://na1.fusion.foxit.com/pdf-services/api/documents/pdf-structural-extract" \
-H "client_id: $FOXIT_CLIENT_ID" \
-H "client_secret: $FOXIT_CLIENT_SECRET" \
-H "Content-Type: application/json" \
-d '{"documentId": "6a6c9834a820c33d30d222e5"}' The call returns HTTP 202 with a taskId rather than the finished document, since analysis runs asynchronously. documentId is the only required field in the body, and a password-protected source PDF takes an optional password alongside it. Full request and response details live in the PDF Structural Extraction reference, which also carries the endpoint’s Trial designation, so pin the schema version you parse against rather than assuming it is stable.
{
"taskId": "6a6c9835d24a2429666f61b6"
} Step 3: Poll the task
Ask for the task by id until it finishes.
curl "https://na1.fusion.foxit.com/pdf-services/api/tasks/6a6c9835d24a2429666f61b6" \
-H "client_id: $FOXIT_CLIENT_ID" \
-H "client_secret: $FOXIT_CLIENT_SECRET" The response carries the state, a percentage, and, once the work is done, the id of the result document:
{
"taskId": "6a6c9835d24a2429666f61b6",
"status": "COMPLETED",
"progress": 100,
"resultDocumentId": "6a6c98375e2cab6bb50e740b"
} Task statuses are uppercase. The schema enum runs PENDING, IN_PROGRESS, COMPLETED, and FAILED, so a comparison against a lowercase "completed" never matches and your loop spins until it times out. Portal copy sometimes says “processing” in prose, but IN_PROGRESS is the value on the wire.
Step 4: Download the result
Fetch the finished artifact using the resultDocumentId from the poll, not the documentId from the upload. Confusing the two is the most common 4xx at this step.
curl -o extract.zip \
"https://na1.fusion.foxit.com/pdf-services/api/documents/6a6c98375e2cab6bb50e740b/download" \
-H "client_id: $FOXIT_CLIENT_ID" \
-H "client_secret: $FOXIT_CLIENT_SECRET" The response comes back as application/zip. Unzipping it gives you StructureInfo.json, the structured output, alongside a rendered PNG of each analyzed page (page_p0.pdf_0.png for a one-page file).
The whole flow in Python
Here is the complete script, reading credentials from the environment.
import os
import time
import zipfile
import json
import requests
BASE = "https://na1.fusion.foxit.com/pdf-services/api"
HEADERS = {
"client_id": os.environ["FOXIT_CLIENT_ID"],
"client_secret": os.environ["FOXIT_CLIENT_SECRET"],
}
def upload(path):
with open(path, "rb") as fh:
r = requests.post(f"{BASE}/documents/upload", headers=HEADERS, files={"file": fh})
r.raise_for_status()
return r.json()["documentId"]
def start_extract(document_id):
r = requests.post(
f"{BASE}/documents/pdf-structural-extract",
headers={**HEADERS, "Content-Type": "application/json"},
json={"documentId": document_id},
)
r.raise_for_status()
return r.json()["taskId"]
def wait_for_task(task_id, interval=3, timeout=180):
deadline = time.time() + timeout
while time.time() < deadline:
r = requests.get(f"{BASE}/tasks/{task_id}", headers=HEADERS)
r.raise_for_status()
body = r.json()
if body["status"] == "COMPLETED":
return body["resultDocumentId"]
if body["status"] == "FAILED":
raise RuntimeError(f"Extraction failed: {body.get('error')}")
time.sleep(interval)
raise TimeoutError(f"Task {task_id} unfinished after {timeout}s")
def download_zip(result_id, out="extract.zip"):
r = requests.get(f"{BASE}/documents/{result_id}/download", headers=HEADERS)
r.raise_for_status()
with open(out, "wb") as fh:
fh.write(r.content)
return out
document_id = upload("invoice.pdf")
result_id = wait_for_task(start_extract(document_id))
archive = download_zip(result_id)
with zipfile.ZipFile(archive) as z:
structure = json.loads(z.read("StructureInfo.json"))
analyze = structure["analyzeResult"]
print("schema", analyze["version"]["schema"], "pages", len(analyze["pages"])) In this code, you upload the invoice and keep the returned documentId, hand that id to the extraction endpoint to get a taskId, then poll the task on a fixed interval until it reports COMPLETED and yields a resultDocumentId. The download call writes the ZIP to disk, and rather than unpacking it to a folder you read StructureInfo.json straight out of the archive. The top-level key is analyzeResult, which is where the schema version, the page list, and the element array all live.
A three-second interval with a 180-second ceiling is comfortable for single-page documents. Back off rather than tightening the loop if you process long files, since polling every second only burns request budget without finishing the job sooner.
Reading the structured JSON
analyzeResult holds four things worth knowing about, an info block of document metadata, a version block, the pages array, and the elements array that carries the content.
{
"analyzeResult": {
"version": {
"schema": "1.0.7",
"software": "FoxitPDFAnalyzer",
"model": "idp-analysis"
},
"pages": [
{ "pageNumber": 1, "size": {}, "state": {} }
],
"elements": [
{
"type": "title",
"content": {
"text": "INVOICE",
"style": { "fontFamilyName": "Arial", "fontSize": 24.0 }
},
"region": {
"page": 1,
"boundingBox": [90, 71, 189, 71, 189, 99, 90, 99]
},
"score": 0.88,
"id": "title1"
}
]
}
} Each element follows the same shape. The type classifies it, and extracting this invoice returns title, head, paragraph, and table. The schema defines a wider set, adding image, headerFooter, form, hyperlink, footnote, sidebar, annotation, and formula, so branch on the types your documents actually produce rather than assuming only four exist. The text and its font styling sit under content, so you read content.text rather than a top-level text key. The region gives the one-based page plus a boundingBox, and that box is an eight-number polygon listing four corner pairs in order, not a four-number rectangle. Every element also carries a confidence score and a stable id such as title1 or paragraph2, and paragraphs additionally carry a paragraphOrder for reading sequence.
Tables are the interesting case. Rather than a headers array and a two-dimensional rows array, a table exposes a cell list under content.body:
{
"type": "table",
"content": {
"body": {
"rowCount": 4,
"columnCount": 5,
"cells": [
{
"paragraph": { "type": "paragraph", "content": { "text": "Description" } },
"rowSpan": 1,
"columnSpan": 1,
"rowIndex": 0,
"columnIndex": 1
}
]
}
}
} Each cell states its own rowIndex and columnIndex along with rowSpan and columnSpan, and its text lives at paragraph.content.text. That is more verbose than a plain grid, but it means merged cells stay describable and you never have to infer column membership from x-coordinates.
Turning the cell list into rows
Since the API hands you cells rather than rows, build the grid yourself once and work with it afterwards.
def table_to_grid(table):
body = table["content"]["body"]
grid = [["" for _ in range(body["columnCount"])] for _ in range(body["rowCount"])]
for cell in body["cells"]:
text = cell.get("paragraph", {}).get("content", {}).get("text", "")
grid[cell["rowIndex"]][cell["columnIndex"]] = text.replace("\r\n", " ")
return grid
tables = [e for e in analyze["elements"] if e["type"] == "table"]
header, *data_rows = table_to_grid(tables[0])
line_items = [dict(zip(header, row)) for row in data_rows]
text_blocks = {
e["id"]: e["content"].get("text", "")
for e in analyze["elements"]
if e["type"] in ("title", "head", "paragraph")
}
print(header)
for item in line_items:
print(item) The code above allocates an empty grid from rowCount and columnCount, then drops each cell’s text into its stated position, which sidesteps any assumption about cell ordering in the array. Cell text can contain literal \r\n where a label wraps inside its column, so the replace call flattens that to a space before it reaches your data layer. Splitting the first row off as the header lets you zip each remaining row into a dictionary keyed by column name, and the same comprehension pattern collects the title, heading, and paragraph text by element id.
Running it against the sample invoice prints the real extraction:
['#', 'Description', 'Qty', 'Unit Price', 'Line Total']
{'#': '1', 'Description': 'API Integration Consulting', 'Qty': '10', 'Unit Price': '$ 150.00', 'Line Total': '$1,500.00'}
{'#': '2', 'Description': 'Compliance Review', 'Qty': '5', 'Unit Price': '$ 200.00', 'Line Total': '$1,000.00'}
{'#': '', 'Description': '', 'Qty': '', 'Unit Price': 'Subtotal:', 'Line Total': '$2,500.00'} Two things in that output are worth designing around. The unit price arrives as the string "$ 150.00", so currency parsing is still your job, and the final row is a subtotal rather than a line item, which is a reminder that the analyzer reports table geometry rather than business meaning. Filter trailing rows on an empty # or Description before you treat them as products. If you want to inspect a full result without running the calls yourself, the StructureInfo_sample.json from this exact run is available to read.
Feeding the output into an agent or downstream workflow
Once the table is a list of dictionaries and the labeled text is keyed by id, the payload is already agent-ready.
agent_context = {
"document": {"schema": analyze["version"]["schema"], "pages": len(analyze["pages"])},
"text_blocks": text_blocks,
"line_items": line_items,
} Because every element also carries a region, you can layer spatial checks on top, such as confirming a table sits below a particular heading by comparing the y values in their bounding polygons before you trust the association. Foxit also publishes an MCP server for PDF Services, so the same operations are reachable from an agent that speaks the Model Context Protocol rather than raw HTTP.
Common mistakes
- PascalCase auth headers : the keys are lowercase
client_idandclient_secret.ClientIdandClientSecretdo not authenticate, and neither does anAuthorization: Bearerheader, which returns a 400. - Comparing status to a lowercase string : task statuses are uppercase, so test against
COMPLETEDandFAILED. - Downloading with the upload id : the download path takes the
resultDocumentIdfrom the completed task, not thedocumentIdfrom the upload. - Reading
elementsfrom the root : the array is nested underanalyzeResult, sostructure["analyzeResult"]["elements"]is the path. - Expecting
bboxor a rows array : positions arrive asregion.boundingBoxwith eight numbers, and tables arrive ascontent.body.cellswith index fields rather than a headers plus rows pair. - Treating the ZIP as the JSON : the download is an archive, and the structured output is the
StructureInfo.jsonentry inside it. - Reusing a stale
documentId: uploads are removed after 24 hours, and the cap on an upload is 100 MB. - Polling every second : that exhausts request budget without speeding anything up. A few seconds between checks is enough.
PDF data extraction FAQ
What element types does the structural extraction return?
Extracting this invoice produces title, head, paragraph, and table elements. Every element carries type, content, region, score, and id, with tables adding a cell grid under content.body.
How is this different from raw text extraction for tables?
Raw text collapses a table into one string and loses row and column boundaries. Structural extraction reports rowCount, columnCount, and a cell list where each cell states its own rowIndex and columnIndex, so position is data rather than inference.
Is the extraction synchronous?
No. The extract call returns HTTP 202 with a taskId, and you poll GET /pdf-services/api/tasks/{taskId} until the status reaches COMPLETED, which is when resultDocumentId appears.
What does the download actually contain?
A ZIP archive holding StructureInfo.json plus a rendered PNG per analyzed page. The JSON is the structured output and the PNG is useful for visual spot checks.
What schema version does the output use?
The sample run reports analyzeResult.version.schema of 1.0.7, produced by FoxitPDFAnalyzer with the idp-analysis model. Read the version from the payload rather than hardcoding it, since it can move.
Does a failed task tell me why?
The task object surfaces the failure state in status as FAILED, so branch on that and log the whole task body when it happens.
Can I extract several documents at once?
Each upload and each task is independent, so run them concurrently and keep one taskId per document. The upload cap is 100 MB per file.
Get started with Foxit’s PDF Structural Extraction API
The pattern is four calls. Upload the PDF for a documentId, start pdf-structural-extract for a taskId, poll until COMPLETED for a resultDocumentId, then download the ZIP and read StructureInfo.json. From there analyzeResult.elements gives you typed titles, headings, paragraphs, and a table cell grid you can turn into dictionaries in a few lines.
Create a free developer account (no credit card) at account.foxit.com/site/sign-up, grab your Client ID and Secret from the APIs Dashboard, and run the script above against invoice_table_test.pdf to see the structured output for yourself.
eSignature API: A Developer’s Guide to Adding Signing to Your App

Adding a signing step to your app involves more than it first appears. Authentication, document preparation, session handling, and completion tracking all need to work together. This guide walks through a full esignature API integration with Foxit eSign, from your first authenticated request to a signed, webhook-confirmed document.
Adding a signing step to an existing app sounds straightforward until you try to implement it. Getting a document signed is a simple idea, but the actual API surface, how authentication works, how you mark up a PDF, and how you learn that signing finished all take longer to figure out than they should. This guide walks a complete Foxit eSign API integration from the first authenticated request through to a webhook-confirmed, digitally signed document. Comfort with REST APIs and bearer tokens is enough to follow along.
What an eSignature API is and how signing workflows work
An eSignature API is a REST interface that owns the document-signing lifecycle, covering preparation, delivery, the signing session, and the audit trail. You supply the document and the signers, and the API handles field rendering, identity capture, signature application, and tamper-evident recordkeeping, so none of that infrastructure is yours to build.
The distinction that matters most for app developers is redirect-based versus embedded signing. Redirect-based signing sends the user to a hosted URL to sign and returns them afterwards, which means they leave your product mid-task. Embedded signing renders the session inside your own application, typically in an iframe, so the user never changes context. If signing sits in the middle of an onboarding or checkout flow, embedded keeps that flow intact.
Foxit eSign supports both. The lifecycle you implement runs through five stages, starting with OAuth 2.0 authentication, then PDF preparation with Text Tags, a POST to /esign/api/v1/folders/createfolder that defines signers and mints a session, the signer completing the embedded session, and a folder_executed webhook confirming the document is final.
The five stages this guide implements in order. Each one maps to a section below.
Prerequisites
Signing up for eSign API access is self-serve on the Foxit API Platform — no sales ticket and no waiting for an administrator. The platform provisions a trial eSign account for you and manages its credentials, so the whole setup is a short walkthrough:
- Create and sign in to your Foxit API Platform account. You need an active Foxit API plan and a complete CAS profile — first name, last name, email address, and company name (a company address is required for eSign provisioning). Your eSign account is provisioned from those profile details, so complete them before you start.
- Open the Dashboard and select Get started with eSign in the Dashboard header. That takes you to the eSign activation page.
- Choose your document-storage region. The activation card preselects United States, with European Union and Canada as alternatives. Select Activate with [region] storage. Confirm the region before activating: once the remote account exists, the region is locked, and changing it later means submitting a case with Foxit Support.
- Wait for provisioning to complete. You may see “Creating your eSign account” and then “Confirming your eSign account” — the second is a reliability check that reconciles ambiguous creation results, so let it finish instead of retrying activation.
- Confirm eSign is ready. A successful activation displays “eSign is ready”, your eSign company number, and the selected region. The platform manages the API account and its credentials, and the same unified
client_id/client_secretyou use for PDF Services also authenticate eSign API, Document Generation, and Embed API — there is no separate eSign key pair to generate. If credential retrieval is still pending or failed, use Resume credentials or Retry credentials on the page; the first-call button stays disabled until credentials are ready. - (Optional but worth it) Run the sample request on the activation page. It uses your profile’s name and email as the first signing party, sends a Base64-encoded one-page contract, adds Signer Name, Today’s Date, Signature, and Date Signed fields, creates a draft with sending disabled, and returns an embedded sending session URL — a quick end-to-end check that everything is wired up. The button switches to Running and then reports “Sample draft created. The embedded sending session is ready.”
Two things to know before you build: your provisioned account is an eSign Business trial that lasts 30 days and starts in TEST mode, so every envelope carries a watermark. Moving the account to Production mode is a Sales/Operations step performed in Foxit Monitor, not something the API can do.
Beyond the account, the rest of the prerequisites are lightweight:
- Python 3.8+ with pip and a venv, for the webhook handler later in this guide.
- Flask and requests for the sample code.
- curl for the token exchange, and ngrok or any tunnel that gives your local webhook endpoint a public HTTPS URL.
- A code editor, VS Code with the Python extension being a reasonable default alongside PyCharm.
- A tagged sample PDF, so you do not have to author one. This guide uses agreement-signable.pdf, which already carries Text Tags for a single signer.
Scaffold the workspace in one shot:
mkdir foxit-esign && cd foxit-esign
python3 -m venv .venv && source .venv/bin/activate
pip install flask requests
export ESIGN_HOST="https://na1.foxitesign.foxit.com"export ESIGN_CLIENT_ID="your_api_key"
export ESIGN_CLIENT_SECRET="your_api_secret"
export WEBHOOK_SECRET="your_webhook_secret" Step 1: Authenticate with the Foxit eSign API
The platform provisions your eSign account and manages its credentials, and that single pair is shared across eSign API, PDF Services, Document Generation, and Embed API. No bearer token, no client_credentials grant, no expires_in to watch.
The quickest way to prove a credential pair works is a minimal folder creation — the same /esign/api/v1/folders/createfolder endpoint Step 3 explains field by field:
curl -X POST "$ESIGN_HOST/esign/api/v1/folders/createfolder" \
-H "client_id: $ESIGN_CLIENT_ID" \
-H "client_secret: $ESIGN_CLIENT_SECRET" \
-H "Content-Type: application/json" \
-d '{
"folderName": "Auth check",
"inputType": "url",
"fileUrls": ["https://github.com/lucienchemaly/foxit-demo-templates/raw/main/esign/agreement-signable.pdf"],
"fileNames": ["agreement.pdf"],
"parties": [
{
"firstName": "Jane",
"lastName": "Smith",
"emailId": "[email protected]",
"permission": "FILL_FIELDS_AND_SIGN",
"sequence": 1
}
],
"processTextTags": false,
"processAcroFields": false,
"createEmbeddedSigningSession": false,
"createEmbeddedSendingSession": true,
"sendNow": false
}' A valid credential pair returns JSON with a folder object carrying folderId and folderStatus (DRAFT here, since sendNow is false), so the response doubles as your auth check — a rejected pair comes back as an error before any folder exists. Send the same two headers on every subsequent request. There is nothing to mint or refresh like an OAuth token; if the platform ever flags the stored credentials as stale, refresh them from the activation page with Resume credentials or Retry credentials. And because eSign shares the PDF Services credential pair, the two integrations are interchangeable — one pair of credentials covers both.
Step 2: Prepare a document and define signature fields with Text Tags
Foxit eSign reads field definitions out of the PDF itself at upload time. You embed them as Text Tags, plain-text strings placed where each field belongs, and the API converts them into interactive fields on ingest.
The syntax is ${fieldtype:party_number:required:field_name:width}, where y marks a field required and n marks it optional, the party number maps to a signer’s sequence, and width is expressed as underscores.
${signfield:1:y:____} # required signature, party 1
${datefield:1:y::____} # required date, party 1
${i:1:______} # initials field, party 1
${t:1:y:Full_Name:__________} # required text field, party 1, named "Full_Name"
${signfield:2:y:____} # required signature, party 2 Each tag names a type, either in full or by its short alias. The supported set covers signfield (s), initialfield (i), datefield (d), textfield (t), textboxfield (tb), checkboxfield (c), radiobuttonfield (rb), securedfield (sc), attachmentfield (a), imagefield (img), accept (ab), decline (db), payfield (pf), and formulafield (ff). Author them in lowercase to match the documented syntax.
Express width as underscores and never as a literal space, because a space stops the tag from being recognized. A tag written ${s:1: } renders in the signing UI as plain ${s:1: } text with no field attached, while ${signfield:1:y:____} becomes a real signature field. That failure is silent, so the create call still succeeds and you only notice when a signer has nothing to sign.
Two preparation details save support tickets later. Foxit eSign converts tags to fields but does not delete the tag text, so set the tag’s text color to match the page background if you do not want signers reading raw ${...} strings. And paste tags through a plain-text editor first, because smart-quote autocorrect in Word or Google Docs silently swaps straight ASCII characters for typographic ones and tag parsing then fails without an error.
If you would rather not tag a document by hand for a first run, agreement-signable.pdf is already prepared and hosted at a public URL you can pass straight to the next step.
Step 3: Send the document and mint an embedded session
One call to /esign/api/v1/folders/createfolder submits the document, defines the signers, and, when you ask for it, returns a ready-to-render signing URL. Foxit calls the signing container a folder rather than an envelope.
{
"folderName": "Customer Agreement - Acme Corp",
"fileUrls": ["https://github.com/lucienchemaly/foxit-demo-templates/raw/main/esign/agreement-signable.pdf"],
"fileNames": ["agreement.pdf"],
"parties": [
{
"firstName": "Jane",
"lastName": "Smith",
"emailId": "[email protected]",
"permission": "FILL_FIELDS_AND_SIGN",
"sequence": 1
}
],
"processTextTags": true,
"createEmbeddedSigningSession": true,
"embeddedSignersEmailIds": ["[email protected]"],
"sendNow": false
} In this body you point the API at the tagged PDF with fileUrls and give it a display name through fileNames, define the single signer in parties with firstName, lastName, emailId, the FILL_FIELDS_AND_SIGN permission and a signing sequence, then set processTextTags to true so the embedded tags become real fields. Asking for createEmbeddedSigningSession and naming the signer in embeddedSignersEmailIds returns a session URL in the same response, and sendNow set to false keeps Foxit from emailing an invitation, which is what you want while testing.
One nuance to expect here. sendNow: false on its own produces a DRAFT folder, but pairing it with createEmbeddedSigningSession returns folderStatus of SHARED, since the folder has to be live for the session URL to open. No email goes out either way, so the flag still suppresses the invitation, and the status you see just reflects that the document is now signable. To attach the file as bytes instead of a URL, send base64FileString as an array together with inputType set to "base64".
The response nests the folder identifier at folder.folderId and carries an embeddedSigningSessions array. Each entry holds emailIdOfSigner, the raw embeddedToken, and the renderable embeddedSessionURL, which follows this shape:
https://{HOST_NAME}/embedded/embeddedsign?eetid={URL-ENCODED-EMBEDDED-TOKEN}
Three behaviors are worth designing around before you ship. Omitting embeddedSignersEmailIds returns email id of embedded signer(s) not submitted, so always list embedded signers explicitly. Every party number used in a Text Tag needs a matching entry in parties, because a sendNow: true create still reports success while silently dropping the fields of a party that is not listed, which means a mandatory signature is never routed. And for a multi-party document where everyone signs in your app, createEmbeddedSigningSessionForAllParties set to true covers all recipients rather than naming them one by one.
To dispatch a draft later, POST to /api/folders/sendDraftFolder.
Folder state moves through DRAFT, SHARED, COMPLETED, and finally EXECUTED once the digital signature is applied. A run of this guide’s single-signer flow produced exactly that path, with the activity log labelling the creation event CREATED and then recording Envelope viewed, Jane Smith signed this folder at COMPLETED, and Document(s) successfully executed at EXECUTED. PARTIALLY SIGNED appears only when a folder has more than one party and some but not all of them have signed, so you will not see it on a single-signer document.
Step 4: Render the signing session in your app
Load the embeddedSessionURL in an iframe. The sandbox attribute needs a specific minimum set of permissions, and trimming it is a common way to break the signing UI with no visible error.
<iframe
id="signing-session"
src="PASTE_EMBEDDED_SESSION_URL_HERE"
width="100%"
height="780px"
style="border: none;"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation"
></iframe> In this markup the src receives the embeddedSessionURL from the createfolder response, and the five sandbox permissions are the minimum the signing UI needs. Removing allow-popups or allow-top-navigation breaks the flow in ways that surface no obvious error, so keep all five unless you have tested a reduced set end to end. Session URLs are short-lived, so generate one when the user is ready to sign rather than caching it, and request a fresh one per signer through /esign/api/v1/embedded/regenerateEmbeddedSigningSession when a session goes stale.
To check the flow before wiring it into your own UI, download the ready-to-run iFrame test page, open it in a browser, paste your embeddedSessionURL into the input, and load it. A correctly tagged document renders with active signing controls.
A real session opened from the embeddedSessionURL this guide’s request returns. All four tags in the sample became required fields, which is what the counter is reporting. The raw tag text still shows through each box, which is exactly why you color it to match the page background before shipping.
Step 5: Confirm completion with webhooks
Polling for completion wastes requests and adds latency. Register a webhook instead and Foxit eSign posts to your endpoint as each signing event happens.
Registration lives on the eSign portal’s API settings page at /consumer/consumerdetails, under Configure Webhooks, where you set the callback URL, a webhook secret, and the events you want. That page is visible only to the account owner, so an admin-level user will not find it. Your endpoint has to be reachable over public HTTPS.
The owner-only webhook settings. The event checkboxes control which callbacks reach your endpoint.
The events available are folder_sent, folder_viewed, folder_signed, folder_cancelled, folder_executed, folder_deleted, folder_completed, folder_assigned, and folder_access_code_failure. In practice folder_viewed, folder_signed, folder_completed, and folder_executed are the ones that fire on an API-dispatched folder.
The event to build on is folder_executed. folder_completed fires once every party has signed, but folder_executed fires after Foxit applies the digital signature and locks the audit trail, so it is the point at which a download gives you the final document.
Foxit signs every callback. It delivers the POST as <your-url>?signature=<base64>, where the signature is the base64 of an HMAC-SHA-256 over the raw request body keyed with your webhook secret. Verify it against the unparsed bytes, since re-serializing the JSON changes whitespace or key order and breaks the comparison.
import base64
import hashlib
import hmac
import os
from flask import Flask, request, jsonify
app = Flask(__name__)
WEBHOOK_SECRET = os.environ["WEBHOOK_SECRET"]
def verify_signature(raw_body: bytes, signature: str) -> bool:
expected = base64.b64encode(
hmac.new(WEBHOOK_SECRET.encode(), raw_body, hashlib.sha256).digest()
).decode()
return hmac.compare_digest(expected, signature)
@app.route("/webhooks/esign", methods=["POST"])
def handle_esign_event():
raw_body = request.get_data()
if not verify_signature(raw_body, request.args.get("signature", "")):
return jsonify({"error": "invalid signature"}), 403
payload = request.get_json(silent=True) or {}
event_name = payload.get("event_name")
folder = payload.get("data", {}).get("folder", {})
if event_name == "folder_executed":
# The document is final here. Archive it, update your record, notify the user.
app.logger.info("Signing finished for folder %s", folder.get("folderId"))
return jsonify({"status": "received"}), 200 In this handler you read the unparsed body first, recompute the HMAC over those exact bytes with your webhook secret, and compare it against the signature query parameter using hmac.compare_digest so the check is not timing-dependent. A mismatch returns 403 before any business logic runs, which stops a spoofed POST to your public URL from triggging an archive. Only after the signature passes do you parse the JSON, read event_name, and branch on folder_executed to run downstream work, returning 200 so Foxit records the delivery as successful. A ready-to-run version of this receiver lives at webhook_receiver.py in the demo repo.
Test the whole path against a draft. Create the folder with sendNow set to false, dispatch it, sign in the embedded session, and watch the events arrive. Once the signer finishes, the session redirects to a result URL carrying event=signing_success, and the document reaches EXECUTED within a few seconds.
The session once every field is filled. The counter reads zero and Finish activates, which is the state that produces folder_completed and then folder_executed.
Step 6: Retrieve the executed document and its audit trail
With folder_executed in hand, pull the final PDF. The download takes the folder id as a query parameter.
curl -o executed.pdf \
"$ESIGN_HOST/api/folders/download?folderId=35117696" \
-H "Authorization: Bearer $ACCESS_TOKEN" The response streams the executed PDF, which arrives with a content type of application/octet-stream rather than application/pdf, so write the bytes to a file rather than sniffing the header. The returned document carries the filled field values and the signature certificate, so a text extraction of it contains the signer’s typed name, the date, and the per-signer Signer ID recorded on the certificate page.
For the audit trail itself, GET /api/folders/viewActivityHistory?folderId={id} returns a details object holding the folder metadata plus an activities array, where each entry carries an activity description and the folderStatus at that moment. That endpoint is GET-only and only returns data once the folder has been shared, so a pure DRAFT folder reports nothing useful.
The signature certificate attached to a document once folder_executed has fired. Each signer’s adopted signature sits beside the identity record Foxit captured, which is the tamper-evident audit trail you are archiving alongside the PDF.
Common mistakes
- Dropping the
/api/prefix : every eSign path sits under/api/, so it is/api/folders/createfolder, not/folders/createfolder. - snake_case request fields : the body is camelCase.
folderName,fileUrls,emailId, andsendNowwork, whilefolder_name,document_url,email, andsend_nowdo not. - Omitting
processTextTags: without it the tags stay inert text, the signer sees raw${...}strings, and they can finish without signing anything. - A tag party with no matching
partiesentry : the create returns success and that party’s fields disappear silently, so their signature is never collected. - Skipping signature verification : a public webhook URL that acts on any POST is a spoofing target. Verify the HMAC before you touch the payload.
- Archiving on
folder_completed: that fires before the digital signature is applied. Wait forfolder_executed. - Caching an
embeddedSessionURL: sessions expire. Mint one when the signer is ready, and regenerate when needed. - Trimming the iframe
sandboxlist : removingallow-popupsorallow-top-navigationbreaks signing with no error message. - Smart quotes or a space inside a tag : both stop tag recognition. Use straight ASCII and underscores.
- Reusing PDF Services credentials : eSign has its own portal, host, and key pair.
eSignature API FAQ
What is an eSignature API?
A REST interface that handles the document-signing lifecycle, covering preparation, delivery, the signing session, and the audit trail, so your app makes calls rather than building signing infrastructure.
What is embedded signing and why does it improve the user experience?
Embedded signing renders the session inside your own application instead of redirecting to a hosted page, so the signer finishes without leaving your product. That matters most when signing sits inside a flow you do not want to interrupt, like onboarding or checkout.
How do Text Tags relate to the parties in the API call?
The party number in a tag maps to a signer’s sequence in the parties array, so ${s:1: } is signed by the party with sequence: 1. Keeping those aligned is the difference between fields routing correctly and vanishing silently.
What is the difference between folder_completed and folder_executed?
folder_completed fires when all parties have signed. folder_executed fires after Foxit applies the digital signature and locks the audit trail, which is why downstream archiving should trigger on folder_executed.
How do I verify a webhook actually came from Foxit?
Recompute a base64 HMAC-SHA-256 of the raw request body using your webhook secret and compare it with the signature query parameter. Verify against raw bytes, never re-serialized JSON.
Can one folder hold several documents?
Yes. Pass additional entries in fileUrls with matching fileNames. Each document carries its own Text Tags, and party assignments stay consistent across the folder.
Do I need a paid plan to build this?
No. The free tier gives you credentials and lets you run the full flow, and no credit card is required to create the account.
Can I review a document before it reaches signers?
Yes. Create it with sendNow set to false for a DRAFT folder, inspect it in the eSign dashboard, then dispatch with /api/folders/sendDraftFolder.
Wrapping up
That is the full path for an eSignature API integration. Authenticate with the client_credentials grant, prepare a PDF with Text Tags, create the folder with processTextTags and an embedded session, render the returned embeddedSessionURL in an iframe, and act on a signature-verified folder_executed webhook.
The same shape extends to multi-signer approval chains, CRM-triggered signing when a deal closes, and template-based documents where fields arrive pre-filled from your own data. Those build on the pieces already in place rather than replacing them.
Ready to build? Create a free account (no credit card required) at account.foxit.com/site/sign-up, generate your API Key and Secret from the API tab, and run the token call above against agreement-signable.pdf to see a session URL come back.
Build a CRM-Triggered PDF Generation and eSign Workflow in Power Automate with Foxit’s REST APIs

This guide shows how to trigger a Word-to-PDF contract from a closed CRM deal, route it for signature through Foxit’s eSign API, and archive the signed copy automatically, using nothing but HTTP actions and a webhook.
Most Power Automate document tutorials stop at a SharePoint file move or an AI Builder extraction, and the ones that touch signatures assume a native connector that does not exist for a headless, API-first pipeline. The gap is the full chain, where a CRM deal closes, a contract is generated from a Word template, the PDF is routed for signature, and the signed copy is archived, with no manual export and no polling. This article builds that pipeline in Power Automate using the HTTP action to call Foxit’s REST endpoints directly, which is the same pattern that carries over to n8n, Zapier, or any orchestrator that can make an HTTP request.
Foxit exposes two REST APIs that chain cleanly for this. The Document Generation API takes a base64-encoded Word template plus a JSON payload and returns a base64 PDF, and the eSign API handles the signing lifecycle behind an OAuth2 token. The base64 PDF from generation drops straight into the eSign upload call, so the handoff stays inside one flow with no SDK to install and no desktop agent. This Power Automate Foxit API integration walks the two hosts and their two auth models, the document generation call, the send-for-signature call with embedded signature fields, and a second flow that receives Foxit’s webhook and archives the executed document.
Prerequisites
Power Automate runs in the browser, so there is no local runtime to install. What you need are the right accounts and one sample file.
A Power Automate account with the HTTP action : the HTTP action is a premium connector, so you need a per-user or per-flow premium license. This is the one paid dependency in the tutorial. On the free Microsoft 365 tier you will hit a wall at the first HTTP action, so confirm the plan before you start.
A Foxit Developer account : create one at account.foxit.com/site/sign-up and activate the free Developer plan, which includes 500 credits per year with no credit card. From the APIs Dashboard, copy the Document Generation Client ID and Secret, and separately the eSign Client ID and Secret. These are two different credential pairs for two different APIs.
A CRM that can trigger a flow : this article uses the Salesforce connector as the example. Any CRM with a Power Automate connector, or any system that can POST to a webhook URL, works the same way.
The sample contract template : download contract_signing.docx so you do not have to author one. It already carries both Document Generation merge tags and eSign signature tags, which is what makes the two-API handoff work.
A REST client : Postman or curl, to test each Foxit call in isolation before wiring it into a flow.
Store both Foxit credential pairs in the Power Automate secure store or as environment variables in your solution, never pasted as literals into an action, so they do not travel in exported flow definitions.
The APIs Dashboard is where you retrieve the Client ID and Secret. Document Generation and eSign each have their own pair.
How the Power Automate Foxit API Integration Works: Two APIs, Two Hosts, Two Flows
The pipeline has four stages. A CRM Closed Won event triggers document generation, the generated PDF is sent for signature, and the executed document is archived once every party has signed.
Salesforce: Opportunity → Closed Won
│
▼
HTTP: POST GenerateDocumentBase64 (na1.fusion.foxit.com) → base64 PDF
│
▼
HTTP: POST createfolder (na1.foxitesign.foxit.com) → folderId, email sent
│
… signer signs (async) …
▼
Flow 2: When a HTTP request is received <- Foxit webhook (folder_executed)
│
▼
HTTP: GET download → OneDrive: Create file
Power Automate owns orchestration and control flow. Foxit owns document rendering and the signature lifecycle. The single most common mistake in this integration is treating the two Foxit products as one, so keep them separate from the start. Document Generation runs on https://na1.fusion.foxit.com and authenticates with lowercase client_id and client_secret request headers. eSign runs on https://na1.foxitesign.foxit.com and authenticates with an OAuth 2.0 bearer token obtained from its own credential pair. They do not share credentials or a portal.
The work also splits into two flows for a reason. Generation and sending are synchronous, so they belong in one flow that runs when the deal closes. Signing completes minutes or days later, so a second flow triggered by Foxit’s webhook handles the archive step. That separation is what removes any polling from the design.
Here is the main flow built in the Power Automate designer, with the four HTTP actions chained after the trigger.
The four HTTP actions in order. This build uses a manual trigger so the flow runs on demand while you test; in production the Salesforce trigger from Step 1 takes its place as the entry point, and nothing downstream changes.
Step 1: CRM Trigger, Firing the Flow on a Closed Deal
Create an automated cloud flow and choose the Salesforce trigger for a created or modified record, pointing it at the Opportunity object. Add a condition so the flow only proceeds when the Stage equals Closed Won, which keeps every mid-pipeline edit from generating a contract.
Map the CRM fields the contract needs. For the sample template, that is the client name, the contract date, the deal value, and the signer’s name and email. Read them from the trigger output with expressions like triggerOutputs()?['body/Account_Name'] and store each in a variable or reference it inline, so the next two steps can assemble their payloads cleanly.
This step is swappable. Any CRM with a Power Automate connector, or any system that can POST JSON to a Power Automate HTTP-request trigger, drops in here without touching the Foxit calls that follow. If you use HubSpot or Dynamics 365, only the trigger and field paths change, so the rest of this tutorial stays identical.
Step 2: Generate the Contract PDF with GenerateDocumentBase64
The contract_signing.docx template drives this step. It contains Document Generation merge tags for the scalar fields and a table loop for line items, using Foxit’s {{ }} syntax:
{{clientName}}
{{contractDate \@ MM/dd/yyyy}}
{{dealValue \# "$#,##0.00"}}
{{TableStart:lineItems}} {{description}} {{amount}} {{TableEnd:lineItems}} The \@ switch formats a date and the \# switch formats a currency value, so you can pass a raw ISO date and a plain number and let the template render them. The {{TableStart:lineItems}} and {{TableEnd:lineItems}} tokens sit in a single Word table row and repeat that row for each object in the lineItems array.
Before the flow can send the template, it needs the file as a base64 string. The build here gets it with an HTTP GET action named Get template, pointed at the raw contract_signing.docx URL, and base64-encodes the response with the base64() expression. For a template you maintain yourself, store it in OneDrive or SharePoint and use a Get file content action instead of the GET. Then add a second HTTP action named Generate PDF, set to POST https://na1.fusion.foxit.com/document-generation/api/GenerateDocumentBase64 with client_id and client_secret headers and this JSON body:
{
"base64FileString": "@{base64(body('Get_template'))}",
"documentValues": {
"clientName": "@{variables('clientName')}",
"contractDate": "2026-07-17",
"dealValue": 48500,
"lineItems": [
{ "description": "Platform license (annual)", "amount": "$36,000.00" },
{ "description": "Onboarding and training", "amount": "$12,500.00" }
]
},
"outputFormat": "pdf"
} In this code, you send the base64-encoded template as base64FileString, pass the CRM-sourced fields as documentValues whose keys match the template tags exactly, and request a PDF with outputFormat set to the lowercase "pdf". The keys clientName, dealValue, and the lineItems array with its description and amount fields have to match the tag names in the Word file, since a mismatch leaves the tag unrendered rather than raising an error. The call is synchronous and returns HTTP 200 with a JSON response containing message, fileExtension, and base64FileString, where base64FileString is the rendered PDF as a base64 string.
The call is synchronous, so there is no task to poll and no status to check, and the generated contract is available immediately. Reference the rendered PDF in the next step directly with the expression body('Generate_PDF')?['base64FileString'], or add a Parse JSON action first if you prefer typed outputs. When you need the raw bytes rather than the string, for archiving or a file action, convert with the base64ToBinary() expression, one of the Workflow Definition Language conversion functions.
One limit to plan for is the upload size. Document Generation rejects .docx payloads larger than 4 MB after base64 encoding, which is roughly a 3 MB raw file, and the limit is not surfaced in a friendly error. If you hit it, compress images through Word’s Picture Format tools, drop embedded fonts and OLE objects, and split oversized templates. The sample here is about 37 KB, so first runs stay well clear of the cap. For template authoring detail and common payload errors, Foxit’s Document Generation API quickstart is the reference.
The generated contract. The signature and date fields at the bottom come from the eSign Text Tags embedded in the same template, ready for Step 3.
Step 3: Send for Signature with OAuth2 and createfolder
The eSign API needs a bearer token first. Add an HTTP action that POSTs to https://na1.foxitesign.foxit.com/api/oauth2/access_token with content type application/x-www-form-urlencoded and this body:
grant_type=client_credentials&client_id=YOUR_ESIGN_CLIENT_ID&client_secret=YOUR_ESIGN_CLIENT_SECRET&scope=read-write Name this action Get eSign token. Its JSON response carries access_token, token_type set to bearer, expires_in, and instance_url, and you reference the token in the next call as body('Get_eSign_token')?['access_token']. This is the client-credentials grant, which fits a server-to-server flow where no human is present to log in.
The signature fields are already defined in the template. contract_signing.docx carries two eSign Text Tags, ${signfield:1:y} and ${datefield:1:y}, which follow the ${fieldtype:party:mandatory} syntax. Here both are mandatory fields assigned to party 1, the client who signs. Because the tags live in the Word file, the PDF that Document Generation produced in Step 2 already has a signature and date field in place, so there is no manual field placement after generation. Keep two rules in mind when you author your own tags. Replace any space inside a tag with an underscore, since a literal space breaks tag recognition, and set the tag text color to match the document background so the tokens do not show in the final PDF.
Now add the send action, an HTTP action named Create signing folder, set to POST https://na1.foxitesign.foxit.com/api/folders/createfolder with an Authorization: Bearer @{body('Get_eSign_token')?['access_token']} header and this body:
{
"folderName": "Acme Corp Contract",
"inputType": "base64",
"base64FileString": ["@{body('Generate_PDF')?['base64FileString']}"],
"fileNames": ["contract_signing.pdf"],
"parties": [
{
"firstName": "Jordan",
"lastName": "Lee",
"emailId": "[email protected]",
"permission": "FILL_FIELDS_AND_SIGN",
"sequence": 1
}
],
"processTextTags": true,
"sendNow": true
} In this code, you attach the Step 2 PDF by passing it as the single element of the base64FileString array together with inputType set to "base64", which is the pairing the API requires for base64 uploads. The parties array names the signer with firstName, lastName, emailId, and a permission of FILL_FIELDS_AND_SIGN, and its sequence of 1 matches the party number in the ${signfield:1:y} tag. Setting processTextTags to true is what converts those embedded tags into real, interactive fields, and sendNow set to true dispatches the signing invitation immediately. The response returns result as success and nests the identifier at folder.folderId, which you store for the archive flow. Foxit calls this container a folder rather than an envelope.
The Create signing folder action. The access_token and base64FileString chips are dynamic references to the two prior HTTP actions, so the eSign token and the generated PDF flow straight into this call with no copy-paste.
Two behaviors are worth handling before you ship. Every party number referenced by a Text Tag must have a matching entry in the parties array, because if a tag points at a party that is not listed, a sendNow: true create still returns success but silently drops that party’s fields, so their signature is never routed. If you need a human to approve the contract before it leaves, set sendNow to false to create a draft without emailing anyone, then dispatch it later with POST https://na1.foxitesign.foxit.com/api/folders/sendDraftFolder.
What the recipient sees after createfolder sends the invitation. The signature field is the one defined by the ${signfield:1:y} tag.
Step 4: Receive the Webhook and Archive the Signed Document
Create a second automated flow using the When a HTTP request is received trigger. Saving the flow generates a callback URL. Register that URL as the webhook endpoint on the eSign portal’s API settings page, which is owner-only, and select the signing events you want delivered.
Archive on the right event. The folder status moves through DRAFT, then SHARED, then PARTIALLY SIGNED, then COMPLETED, then EXECUTED. Trigger the archive on folder_executed, not folder_completed. The folder_completed event fires when all signatures are in but before the digital signature has been applied to the PDF, whereas folder_executed guarantees the file you download is the final, digitally signed document.
Verify each callback before acting on it. Foxit delivers every webhook as POST <your-url>?signature=<base64>, where the signature is the base64 of an HMAC-SHA-256 of the raw request body keyed with your webhook secret. Power Automate’s expression language has no native HMAC function, so there are two practical paths. The stronger one calls a small Azure Function or an Office Script that recomputes the HMAC over the raw body and returns a match boolean, which the flow checks in a Condition. The lighter one restricts the trigger to your tenant and treats the webhook secret as a shared value checked in a Condition, which is simpler but weaker. Choose based on how exposed the endpoint is.
Once a callback is verified and the event is folder_executed, parse folderId from the payload and download the signed file. Add an HTTP action with the bearer token set to GET https://na1.foxitesign.foxit.com/api/folders/download?folderId=@{triggerBody()?['folderId']}, which returns the executed PDF as application/pdf. Pass the response body to the OneDrive for Business Create file action, naming the destination folder by deal name or date so contracts stay retrievable.
The owner-only webhook settings, where you paste the Power Automate callback URL and pick the events to receive.
If you cannot expose a public endpoint, poll instead. GET https://na1.foxitesign.foxit.com/api/folders/viewActivityHistory?folderId={id} returns the audit trail, with actions such as Created, Invitation Sent, Opened, Viewed, Signed, and Folder Executed. This endpoint is GET-only and only returns data once the folder has been shared or sent, so run it on a schedule from a separate flow.
Common Mistakes
Most failures in this pipeline come from a small set of recurring errors. Check these first when something does not work.
- Using one credential pair or one token for both APIs : Document Generation uses
client_idandclient_secretheaders onna1.fusion.foxit.com, while eSign uses a bearer token onna1.foxitesign.foxit.com. They are separate. - Sending the eSign PDF without
inputType: the base64 upload needsinputTypeset to"base64"alongside thebase64FileStringarray, or the API returnsfileUrls or base64FileString cannot be empty. - Omitting
processTextTags: withoutprocessTextTagsset totrue, the tags stay as inert text and the signer can finish without signing. - A tag party number with no matching party : if
${signfield:2:y}appears but thepartiesarray has no party 2, the send succeeds and that party’s fields vanish silently. - Missing a party email field : each party needs
emailId, notemail. The wrong key returnsemail id of party cannot be empty. - Archiving on
folder_completed: download onfolder_executedinstead, or you may pull a PDF before the digital signature is applied. - A stray space or smart quote in a tag : a literal space inside
${...}or a curly quote from Word autocorrect breaks tag recognition. Use straight quotes and underscores.
API Workflow Automation FAQ
Does this work with n8n or Zapier instead of Power Automate?
Yes. Any platform that can make HTTP requests and receive a webhook works, since the Foxit calls are identical. Only the orchestration layer changes.
Do I need a paid plan to test the Foxit side?
No. The free Developer plan gives 500 credits per year with instant activation and no credit card. The paid dependency here is the Power Automate premium license for the HTTP action.
Are Document Generation and eSign on the same credentials?
No. Each API has its own Client ID and Secret, so store two credential pairs and use each on its own host.
Can I skip generation and send an existing PDF to eSign?
Yes. The createfolder call accepts a base64 PDF directly, or a public file URL through fileUrls and fileNames, so the generation step is optional if you already have the document.
How do I add a second signer?
Add party-2 Text Tags to the template, such as ${signfield:2:y}, and a matching party-2 entry to the parties array. Keep the party numbers in the tags and the array aligned.
Next Step
The fastest way to confirm the pieces before building the flow is to run one call by hand. Create your free Foxit Developer account, pull your Document Generation and eSign Client IDs and Secrets from the APIs Dashboard, and run a single GenerateDocumentBase64 call against contract_signing.docx in a REST client. Once it returns a base64 PDF, you know the credentials and payload are right, and the rest of the Power Automate Foxit API integration is just wiring the same calls into actions. Create your free account to get started.
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.