我正在尝试在 PDF 中创建一个表单字段,用户可以在其中插入图像文件并保存文档,以便图像是持久的(在新的 PDF 文档中,而不是更改现有文档)。我知道这是可能的,因为我已经看到它在其他 PDF 中完成,但我无法弄清楚它应该如何在 iText 7 for .NET/C# 中完成。
我在 Google 上找到了这个,它似乎至少提供了解决方案的 JavaScript 和大纲,但我不知道如何编辑 iTextPdfButtonFormField
对象的“布局”。我也从 iText 网站尝试过这个答案,但它适用于添加到现有文档中,无论如何我都无法让它工作(一些更难以捉摸的System.NullReferenceException
错误)。
使用创建按钮并替换图像的想法,到目前为止我已经尝试过:
PdfWriter writer = new PdfWriter("myfile.pdf");
PdfDocument document = new PdfDocument(writer);
PdfPage pdfPage = document.AddNewPage(PageSize.A4);
PdfCanvas canvas = new PdfCanvas(pdfPage);
PdfAcroForm form = canvas.GetForm();
PdfButtonFormField button = PdfFormField.CreateButton(document, new Rectangle(50, 50), 0);
button.SetAction(PdfAction.CreateJavaScript("event.target.buttonImportIcon();"));
form.AddField(button); // <-- Error on this line
document.Close();
writer.Close();
希望这buttonImportIcon()
足以覆盖按钮的外观。但是我System.NullReferenceException: 'Object reference not set to an instance of an object.'
在指示的行出现错误(不幸的是,它没有比这更具体),堆栈跟踪有点无益:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at iText.Forms.PdfAcroForm.AddField(PdfFormField field, PdfPage page)
at iText.Forms.PdfAcroForm.AddField(PdfFormField field)
at ReplaceIcon.Main(String[] args) in ReplaceIcon.cs:line 65
我还尝试将 替换为CreateButton
,CreatePushButton
如下所示:
PdfButtonFormField button = PdfFormField.CreatePushButton(document, new Rectangle(50, 50), "name", "caption");
使用它编译代码,当我单击 PDF 中的按钮时,我得到一个“选择图像”对话框,但该按钮仍然只是一个灰色的正方形,上面写着“标题”,而不是被选定的图像替换. 但我怀疑需要一个通用按钮,以便您可以覆盖布局(以某种方式)。
如果有人知道这应该如何完成,无论是使用此按钮方法还是其他方式,我都会非常感谢一些指示。正如我所说,我对在 C# 程序中使用 iText 7 在新生成的 PDF 文档中创建这些字段特别感兴趣。