在iText 7 .NET / C#中为PDF创建图像表单域

问题描述 投票:0回答:1

我正在尝试在PDF中创建一个表单域,用户可以在其中插入图像文件并保存文档,以使图像持久化(在新的PDF文档中,而不是更改现有文档)。我知道这是可能的,因为我已经在其他PDF中看到了它的实现,但是我无法弄清楚在.NET / C#的iText 7中应该如何实现。

[我在Google上发现了this,它似乎至少提供了JavaScript和解决方案的概述,但我不知道如何编辑iText PdfButtonFormField对象的“布局”。我也在iText网站上尝试过this answer,但它的目的是添加到现有文档中,但我还是无法使它正常工作(有些难以捉摸的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文档中创建这些字段。

c# pdf itext acrofields
1个回答
0
投票

但是我得到一个System.NullReferenceException:'对象引用未设置为对象的实例。'

© www.soinside.com 2019 - 2024. All rights reserved.