如何在iText7 v8.0.3中创建PDF签名域?
在iText7 8.0.3中创建PDF签名域的解决方案
iText7 8.x版本对表单域相关API做了重构,原PdfFormField.CreateSignature方法已被移除,需要改用PdfSignatureFormField类来创建签名域。
修改后的签名域创建代码
替换你原代码中创建签名域的部分为以下内容:
// Add signature field PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true); // 使用PdfSignatureFormField构造方法创建签名域 PdfSignatureFormField signatureField = new PdfSignatureFormField(pdf, new Rectangle(100, 100, 200, 50)); signatureField.SetFieldName("Signature"); // 可选:添加签名提示文本(默认显示"Click here to sign") signatureField.SetValueAsString("请在此处签名"); form.AddField(signatureField);
完整修改后的代码
public async Task<FileStreamResult> DownloadPropertyList(LDSC_DownloadParams downloadParams) { Instance instance = await GetInstance(downloadParams.ImplementationId); // Create a new PDF document MemoryStream memoryStream = new MemoryStream(); PdfWriter writer = new PdfWriter(memoryStream); writer.SetCloseStream(false); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf); // Create a table with a column for each property attribute Table table = new Table(UnitValue.CreatePercentArray(new float[] { 20, 20, 20, 10, 10, 20 })) .UseAllAvailableWidth(); // Add headers to the table table.AddHeaderCell("Property Name"); table.AddHeaderCell("Address"); table.AddHeaderCell("City"); table.AddHeaderCell("State"); table.AddHeaderCell("Zip Code"); table.AddHeaderCell("Contact"); // Iterate over ScreeningProperties and add rows to the table foreach (var property in instance.ScreeningProperties) { table.AddCell(property.PropertyName ?? ""); table.AddCell(property.Address ?? ""); table.AddCell(property.City ?? ""); table.AddCell(property.State?.ToString() ?? ""); table.AddCell(property.ZipCode ?? ""); table.AddCell($"{property.ContactPerson ?? ""}\n{property.PhoneNumber ?? ""}"); } // Add the table to the document document.Add(table); // Add signature field - 修改后的代码 PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true); PdfSignatureFormField signatureField = new PdfSignatureFormField(pdf, new Rectangle(100, 100, 200, 50)); signatureField.SetFieldName("Signature"); signatureField.SetValueAsString("请在此处签名"); // 可选提示文本 form.AddField(signatureField); // Close the document document.Close(); // This finalizes the document and writes it to the memory stream // Prepare the memory stream to be returned memoryStream.Position = 0; // Return the FileStreamResult // Adjust the file name as needed return new FileStreamResult(memoryStream, "application/pdf") { FileDownloadName = "PropertyList.pdf" }; }
关键说明
PdfSignatureFormField是iText7 8.x中专门用于创建签名域的类,构造方法需要传入PdfDocument和签名域的矩形区域(位置和大小)- 可以通过
SetValueAsString设置签名域的提示文本,用户未签名时会显示该文本 - 其他表单域的操作逻辑保持不变,仅替换签名域的创建方式即可
内容的提问来源于stack exchange,提问作者user1274820
相关产品推荐
相关产品推荐

