如何在Node.js中填写PDF表单字段

This article was translated from English: Does it need improvement?
Translated
View the article in English

在Node.js中以编程方式填写PDF表单可让您自动化文档工作流:从用数据库记录填充申请表到大规模生成个性化证书。 IronPDF for Node.js为加载现有PDF、在表单字段中写入值并在不离开JavaScript环境下保存完整文档提供了一个简单的API。

本指南涵盖整个工作流程:安装包、申请许可证密钥、填充文本字段、复选框、下拉菜单和单选按钮、平展表单字段以锁定值和保存输出。 所有代码示例均使用 await 以及 @ironsoftware/ironpdf 包。

快速入门:在Node.js中填写PDF表单

安装包,然后在几行代码中加载并填充表单:

//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/install.sh
npm install @ironsoftware/ironpdf
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/install.sh
npm install @ironsoftware/ironpdf
SHELL
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/quickstart.js
const { PdfDocument, IronPdfGlobalConfig } = require("@ironsoftware/ironpdf");

IronPdfGlobalConfig.getConfig().licenseKey = "YOUR-LICENSE-KEY-HERE";

(async () => {
    const pdf = await PdfDocument.fromFile("./form.pdf");
    await pdf.setFormFieldValue("firstName", "Jane");
    await pdf.setFormFieldValue("email", "jane@example.com");
    await pdf.saveAs("./filled-form.pdf");
})();
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/quickstart.js
const { PdfDocument, IronPdfGlobalConfig } = require("@ironsoftware/ironpdf");

IronPdfGlobalConfig.getConfig().licenseKey = "YOUR-LICENSE-KEY-HERE";

(async () => {
    const pdf = await PdfDocument.fromFile("./form.pdf");
    await pdf.setFormFieldValue("firstName", "Jane");
    await pdf.setFormFieldValue("email", "jane@example.com");
    await pdf.saveAs("./filled-form.pdf");
})();
JAVASCRIPT

我需要什么先决条件来在Node.js中填写PDF表单?

在运行下面的代码示例之前,请确认以下三项条件已满足:支持的 Node.js 版本、IronPDF 许可证密钥以及 IronPdfEngine 二进制文件。

Node.js版本:IronPDF需要Node.js 18或更高版本。 从官方Node.js网站下载当前的LTS版本。 该库使用 Node.js 异步 I/O 处理所有 PDF 操作,因此 await 或 Promise 链式调用是贯穿始终的标准模式。 不支持旧版本的 Node.js,因为该包依赖于原生 ESM 和 async_hooks 功能,这些功能需要 Node.js 18 及以上版本。

许可证密钥:激活的IronPDF许可证密钥解锁完整的API。 开始免费试用以获取开发和测试的密钥,或购买许可证用于生产用途。 有关部署选项(环境变量、配置文件、秘密管理器),请参阅使用许可证密钥指南。

IronPdfEngine:该 Node.js 包包含 IronPdfEngine,这是一个负责实际 PDF 操作的跨平台渲染引擎。 安装和平台特定的说明(Windows、Linux、macOS)请参见使用IronPdfEngine文档。

如何在Node.js代码中设置许可证密钥?

请在应用程序启动时,在调用任何 PdfDocument 之前,应用一次许可证密钥:

//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/license-setup.js
const { IronPdfGlobalConfig } = require("@ironsoftware/ironpdf");

// Apply once at startup -- before any PdfDocument operations
IronPdfGlobalConfig.getConfig().licenseKey = process.env.IRONPDF_LICENSE_KEY;
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/license-setup.js
const { IronPdfGlobalConfig } = require("@ironsoftware/ironpdf");

// Apply once at startup -- before any PdfDocument operations
IronPdfGlobalConfig.getConfig().licenseKey = process.env.IRONPDF_LICENSE_KEY;
JAVASCRIPT

将密钥存储在环境变量中(如上文 process.env.IRONPDF_LICENSE_KEY 所示),可避免凭据进入源代码控制。 开始指南概述介绍了不同部署环境的其他初始化模式。


如何安装 IronPDF for Node.js?

安装IronPDF for Node.js只需一个npm命令。 在您的项目目录中运行它:

//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/install-full.sh
npm install @ironsoftware/ironpdf
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/install-full.sh
npm install @ironsoftware/ironpdf
SHELL

该包附带 TypeScript 类型声明,因此 TypeScript 项目无需单独安装 @types 包即可获得完整的 IntelliSense 支持。 Windows、Linux和macOS平台特定的二进制文件在安装期间自动下载。 npm上的@Iron Software/ironpdf包列出了所有发布的版本和对等依赖项。

请注意对于 TypeScript 项目,包含的 .d.ts 声明意味着 IntelliSense 可在 VS Code 及其他支持 TypeScript 语言服务的编辑器中开箱即用。

有关将IronPDF添加到现有monorepo或基于Docker的工作流程的说明,请参见IronPDF for Node.js文档


如何以编程方式填写 PDF 表单?

加载 PDF/A 并向其表单字段写入值需要三个异步调用:setFormFieldValue()saveAs()。 下面的示例填写了一个多字段的申请表,并可选择将其平展,以便在交付后无法更改这些值。

完整的表单填写示例是什么样的?

以下示例加载具有多种字段类型的PDF,填写它们并保存结果。 欲了解有关创建表单而不是填写表单的集中型内容,请参阅PDF表单示例页

//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/fill-pdf-form.js
const { PdfDocument, IronPdfGlobalConfig } = require("@ironsoftware/ironpdf");

IronPdfGlobalConfig.getConfig().licenseKey = process.env.IRONPDF_LICENSE_KEY;

async function fillApplicationForm() {
    // Load the PDF containing form fields
    const pdf = await PdfDocument.fromFile("./forms/application-form.pdf");

    // Discover available field names before filling
    const fieldNames = await pdf.getFormFieldNames();
    console.log("Form fields:", fieldNames);

    // Text fields
    await pdf.setFormFieldValue("firstName", "Jane");
    await pdf.setFormFieldValue("lastName", "Doe");
    await pdf.setFormFieldValue("email", "jane.doe@example.com");
    await pdf.setFormFieldValue("phone", "+1-555-987-6543");

    // Date field
    await pdf.setFormFieldValue("dateOfBirth", "03/22/1988");

    // 复选框 fields -- pass "true" or "false" as strings
    await pdf.setFormFieldValue("agreeToTerms", "true");
    await pdf.setFormFieldValue("subscribeNewsletter", "false");

    // Dropdown / select field
    await pdf.setFormFieldValue("country", "United States");

    // Multi-line text area
    await pdf.setFormFieldValue("comments", "Application submitted via automated workflow.");

    // Flatten the form to lock values -- prevents further editing
    // await pdf.flattenAllFormFields();

    await pdf.saveAs("./output/filled-application.pdf");
    console.log("Form saved.");
}

fillApplicationForm().catch(console.error);
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/fill-pdf-form.js
const { PdfDocument, IronPdfGlobalConfig } = require("@ironsoftware/ironpdf");

IronPdfGlobalConfig.getConfig().licenseKey = process.env.IRONPDF_LICENSE_KEY;

async function fillApplicationForm() {
    // Load the PDF containing form fields
    const pdf = await PdfDocument.fromFile("./forms/application-form.pdf");

    // Discover available field names before filling
    const fieldNames = await pdf.getFormFieldNames();
    console.log("Form fields:", fieldNames);

    // Text fields
    await pdf.setFormFieldValue("firstName", "Jane");
    await pdf.setFormFieldValue("lastName", "Doe");
    await pdf.setFormFieldValue("email", "jane.doe@example.com");
    await pdf.setFormFieldValue("phone", "+1-555-987-6543");

    // Date field
    await pdf.setFormFieldValue("dateOfBirth", "03/22/1988");

    // 复选框 fields -- pass "true" or "false" as strings
    await pdf.setFormFieldValue("agreeToTerms", "true");
    await pdf.setFormFieldValue("subscribeNewsletter", "false");

    // Dropdown / select field
    await pdf.setFormFieldValue("country", "United States");

    // Multi-line text area
    await pdf.setFormFieldValue("comments", "Application submitted via automated workflow.");

    // Flatten the form to lock values -- prevents further editing
    // await pdf.flattenAllFormFields();

    await pdf.saveAs("./output/filled-application.pdf");
    console.log("Form saved.");
}

fillApplicationForm().catch(console.error);
JAVASCRIPT

调用 getFormFieldNames() 后,返回的数组会告知您 PDF 作者使用了哪些字段名称。 这是避免与您没有创建的表单集成时键入错误的最快方法。

提示在开发过程中调用 getFormFieldNames() 一次,即可在 PDF 中打印出确切的字段名称。 硬编码错误的名称是字段在 setFormFieldValue().
之后显示为空的最常见原因。)}]


如何处理不同的表单字段类型?

IronPDF支持标准AcroForm字段类型:文本框、复选框、单选按钮、下拉菜单、列表框和签名字段。 setFormFieldValue() 方法接受所有类型的字符串值;对于复选框和单选按钮字段,其接受的值取决于 PDF 中的具体字段定义。

下表显示了每种字段类型的值格式:

PDF AcroForm字段类型及其接受的值格式
字段类型值格式范例
文本/多行任何字符串"Jane Doe"
复选框"true""false""true"
单选按钮选项的导出值"女性"
下拉菜单(组合)选项的显示文本"美国"
列表框(多选)字符串数组["选项1", "选项2"]
日期 / 数字字符串表示"2024-06-15"

复选框和单选按钮如何工作?

复选框使用 "true" 进行勾选,使用 "false" 进行取消勾选。 单选按钮接受选项的导出值进行选择——导出的字符串通常在PDF的字段属性中可见,并且与显示标签不同。

//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/field-types.js
const { PdfDocument, IronPdfGlobalConfig } = require("@ironsoftware/ironpdf");

IronPdfGlobalConfig.getConfig().licenseKey = process.env.IRONPDF_LICENSE_KEY;

async function handleFieldTypes() {
    const pdf = await PdfDocument.fromFile("./forms/complex-form.pdf");

    // Radio button -- use the field's export value, not its display label
    await pdf.setFormFieldValue("gender", "Female");

    // 复选框
    await pdf.setFormFieldValue("termsAccepted", "true");

    // Dropdown
    await pdf.setFormFieldValue("preferredContact", "Email");

    // Numeric field -- pass the number as a string
    await pdf.setFormFieldValue("invoiceAmount", "1250.00");

    // Date picker
    await pdf.setFormFieldValue("appointmentDate", "2024-06-15");

    await pdf.saveAs("./output/complex-form-filled.pdf");
}

handleFieldTypes().catch(console.error);
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/field-types.js
const { PdfDocument, IronPdfGlobalConfig } = require("@ironsoftware/ironpdf");

IronPdfGlobalConfig.getConfig().licenseKey = process.env.IRONPDF_LICENSE_KEY;

async function handleFieldTypes() {
    const pdf = await PdfDocument.fromFile("./forms/complex-form.pdf");

    // Radio button -- use the field's export value, not its display label
    await pdf.setFormFieldValue("gender", "Female");

    // 复选框
    await pdf.setFormFieldValue("termsAccepted", "true");

    // Dropdown
    await pdf.setFormFieldValue("preferredContact", "Email");

    // Numeric field -- pass the number as a string
    await pdf.setFormFieldValue("invoiceAmount", "1250.00");

    // Date picker
    await pdf.setFormFieldValue("appointmentDate", "2024-06-15");

    await pdf.saveAs("./output/complex-form-filled.pdf");
}

handleFieldTypes().catch(console.error);
JAVASCRIPT

多选列表框字段遵循相同的模式。 当一个字段允许多重选择时,传递一个字符串数组,而不是单一值。 签名字段可以接收一个代表签名字形的base64编码图像字符串。

重要如果 setFormFieldValue() 似乎无法更改字段值,请检查字段名称是否完全匹配——PDF 字段名称区分大小写。请使用 getFormFieldNames() 列出文档中的实际名称。


填充后如何扁平化PDF表单字段?

扁平化PDF表单将所有字段值合并到静态页面内容中,移除交互层。 生成的文档不能再进一步编辑,从而防止在分发过程中意外更改,并确保在所有PDF查看器中一致呈现。

在设置所有字段值后、保存前,对加载的文档调用 flattenAllFormFields()

//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/flatten-form.js
const { PdfDocument, IronPdfGlobalConfig } = require("@ironsoftware/ironpdf");

IronPdfGlobalConfig.getConfig().licenseKey = process.env.IRONPDF_LICENSE_KEY;

async function fillAndFlattenForm() {
    const pdf = await PdfDocument.fromFile("./forms/contract.pdf");

    // Fill the required fields
    await pdf.setFormFieldValue("signerName", "Jane Doe");
    await pdf.setFormFieldValue("signatureDate", "2024-06-15");
    await pdf.setFormFieldValue("agreementAccepted", "true");

    // Flatten -- converts interactive fields to static content
    await pdf.flattenAllFormFields();

    await pdf.saveAs("./output/contract-signed.pdf");
    console.log("Contract flattened and saved.");
}

fillAndFlattenForm().catch(console.error);
//:path=/static-assets/pdf/content-code-examples/nodejs/how-to/nodejs-fill-pdf-form/flatten-form.js
const { PdfDocument, IronPdfGlobalConfig } = require("@ironsoftware/ironpdf");

IronPdfGlobalConfig.getConfig().licenseKey = process.env.IRONPDF_LICENSE_KEY;

async function fillAndFlattenForm() {
    const pdf = await PdfDocument.fromFile("./forms/contract.pdf");

    // Fill the required fields
    await pdf.setFormFieldValue("signerName", "Jane Doe");
    await pdf.setFormFieldValue("signatureDate", "2024-06-15");
    await pdf.setFormFieldValue("agreementAccepted", "true");

    // Flatten -- converts interactive fields to static content
    await pdf.flattenAllFormFields();

    await pdf.saveAs("./output/contract-signed.pdf");
    console.log("Contract flattened and saved.");
}

fillAndFlattenForm().catch(console.error);
JAVASCRIPT

对于最终交付非常适合的情况——签署后的合同、发行后的证明书或批准后的发票。 对于需要进一步审核才能定稿的文档,请跳过 flattenAllFormFields() 并节省该部分进行保存。

警告扁平化对已保存的副本是不可逆的。 如果需要重新生成文档,请保留原始未填充的PDF作为模板。)]}


PDF表单自动化的常见用例是什么?

自动化表单填写从高容量文档工作流中移除手动数据输入。 以下场景涵盖开发人员使用IronPDF进行的最常见模式。

应用处理:从数据库或REST API中提取申请人数据,并填充用于金融服务、保险或政府接受工作流程的PDF表单。 使用合并PDF示例将填充的表单结合起来,以生成单一的多页提交包。

发票和收据生成:用行项目数据、客户详情和计算总计填充发票模板。 使用HTML页眉和页脚示例中所示技术添加页眉和页脚。

证书和凭证生成:用收件人姓名、完成日期和课程标题个性化证书模板。 使用数字签名示例添加安全性,以防止发行后篡改。 在受监管行业中,PDF/A标准通常要求进行长期归档。

报告生成:用分析数据或调查结果填充报告模板。 对于需要从头构建PDF布局而不是填充现有表单的情况,请参见HTML到PDF教程。


PDF表单填写在Node.js中的下一步是什么?

本指南演示了加载PDF、填写文本字段、复选框、下拉菜单和单选按钮,将表单扁平化以锁定值,并保存完成的文档。 同一个 PdfDocument 实例支持进一步的操作——添加数字签名、压缩输出或提取文本——而无需重新加载文件。

开始免费试用以在您的项目中测试IronPDF,或者查看许可选项以找到适合您部署的计划。

准备好看看您还能做些什么吗? 在此查看完整的Node.js教程集合:Node.js中的HTML到PDF

常见问题解答

在 Node.js 中填写 PDF 表单需要哪些先决条件?

您需要Node.js 18或更高版本、IronPDF许可证密钥(提供免费试用),以及IronPdfEngine二进制文件。引擎与@ironsoftware/ironpdf包捆绑,在安装时自动下载。

如何安装 IronPDF for Node.js?

在项目目录中运行npm install @ironsoftware/ironpdf。该命令将安装该包及其适用于Windows、Linux和macOS的平台特定二进制文件。TypeScript类型声明已包含在内。

如何发现PDF表单中的字段名?

在使用PdfDocument.fromFile()加载PDF后,调用await pdf.getFormFieldNames()。该方法返回文档中所有字段名称字符串的数组。PDF字段名区分大小写,因此请使用返回的确切字符串。

复选框和单选按钮接受什么值格式?

复选框接受字符串"true""false"以选中和未选中。单选按钮接受目标选项的导出值字符串。使用getFormFieldNames()并检查PDF字段属性以找出正确的导出值。

如何防止填写完的PDF表单被编辑?

在设置所有字段值并在saveAs()之前,调用await pdf.flattenAllFormFields()。展平操作将字段值合并为静态页面内容,并移除交互式表单层。此操作在保存的文件上不可逆。

我可以在Node.js中将IronPDF与TypeScript一起使用吗?

可以。@ironsoftware/ironpdf包内含有TypeScript声明(.d.ts文件),因此您可以在VS Code和其他编辑器中进行完整类型检查和IntelliSense,而无需安装单独的类型包。

Darrius Serrant
全栈软件工程师(WebOps)

Darrius Serrant 拥有迈阿密大学的计算机科学学士学位,目前在 Iron Software 担任全栈 WebOps 市场工程师。从小就被编码吸引,他认为计算机既神秘又易于接触,使其成为创意和问题解决的理想媒介。

在 Iron Software,Darrius 喜欢创造新事物,并简化复杂概念以使其更易理解。作为我们常驻的开发者之一,他还自愿教授学生,与下一代分享他的专业知识。

对于 Darrius 来说,他的工作令人满意,因为它被重视并产生真正的影响。

准备开始了吗?
版本: 2026.5 just released
Still Scrolling Icon

还在滚动吗?

想快速获得证据?
运行示例看着你的HTML代码变成PDF文件。