这个简短的教程分享了有关如何使用 C# 填充 PDF 表单字段的详细信息。 PDF 文件可以有不同类型的表单字段,例如文本框、单选按钮和组合框。 以编程方式填写 PDF 表单 C# 代码演示了访问文本框表单字段,然后更新其中的值和格式。
使用 C# 填充 PDF 表单域的步骤
- 设置您的解决方案以从 NuGet 包管理器添加 Aspose.PDF
- 将示例 PDF 文件加载到包含文本框表单字段的 Document 对象中
- 通过提供字段名称并转换为 TextBoxField 来获取对表单字段的引用
- 使用 Value 属性在文本框字段中设置新文本
- 设置文本框字段的文本颜色和文本对齐方式
- 在表单字段中使用新值保存更新的 PDF 文件
这些步骤提供了有关如何通过共享配置详细信息使用 C# 填充 PDF 表单域 的信息,然后逐步加载源 PDF 文件并访问其中的表单域。在后续步骤中,将更新文本框字段的值和格式。最后,更新的 PDF 文件保存在磁盘上。
使用 C# 填充 PDF 表单字段的代码
using Aspose.Pdf; | |
using Aspose.Pdf.Forms; | |
namespace FillPdfFormFieldsInCSharp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function for filling form fields | |
{ | |
// Create and load license to fill form fields | |
License licSetFormField = new License(); | |
licSetFormField.SetLicense("Aspose.PDF.lic"); | |
// Load the sample PDF file having form with fields | |
Document pdfWithFormFields = new Document("TextBox_out.pdf"); | |
// Get reference to the text box whose value is to be updated | |
TextBoxField formFieldTextBox = pdfWithFormFields.Form["textbox1"] as TextBoxField; | |
// Set the new value in the selected form field | |
formFieldTextBox.Value = "Here is the new value for the form field"; | |
// Set the selected form field appearance | |
formFieldTextBox.Color = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Red); | |
formFieldTextBox.TextVerticalAlignment=VerticalAlignment.Bottom; | |
// Save the resultant PDF after updating the form field | |
pdfWithFormFields.Save("TextBoxUpdated.pdf"); | |
System.Console.WriteLine("Done"); | |
} | |
} | |
} |
演示了使用 C# 填写 PDF 表单 操作以及可选的格式化步骤。我们可以通过使用 Document.Form[“FieldName”] 提供字段名称来访问表单字段,然后将其转换为相应的字段类型,即 TextBoxField、RadioButtonField 或 ComboBoxField。选择目标字段后,您不仅可以设置其值,还可以更改其属性以及外观、边框、颜色、内容、高度、宽度、水平和垂直文本对齐方式等等。
本教程指导如何使用 C# 自动填充 PDF 表单。如果您想了解如何展平 PDF 表单域,请参阅 如何在 C# 中展平 PDF 表单域 上的文章。