将签名表单域添加到最后一页中可见的页面

Adding a signature form field to a page it's visible in the last page also

我正在尝试使用 iText for .NET (v7.0.4) 将签名表单字段放在特定页面的给定位置。我正在处理的代码如下:

public static void test()
    {
        using (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(@"c:\temp\pippo.pdf")))
        {
            //Add some blank pages
            pdfDoc.AddNewPage();
            pdfDoc.AddNewPage();
            pdfDoc.AddNewPage();

            //Instantiate a Signature Form Field using factory
            PdfSignatureFormField sgnField = 
                PdfFormField.CreateSignature(pdfDoc, new Rectangle(100, 100, 200, 100));

            //setting name and page
            sgnField.SetFieldName("pluto");
            sgnField.SetPage(1);

            //Adding to AcroForm
            PdfAcroForm.GetAcroForm(pdfDoc, true).AddField(sgnField);
        }
    }

输出文档 (pippo.pdf) 在第一页有签名字段,这是预期的行为。问题是即使在最后一页(第三页,在本例中)我也能看到签名字段。

此外,如果我通过调用 pdfDoc.RemovePage(3); 删除最后一页,签名字段甚至会从第一页消失。

问题是:如何让签名表单域在最后一页不重复?任何建议真的很受欢迎!

方法AddField(PdfFormField field)记录为

 * This method adds the field to the last page in the document.
 * If there's no pages, creates a new one.

因此,您首先使用

将您的字段分配到第一页
sgnField.SetPage(1)

然后也是最后一个使用

PdfAcroForm.GetAcroForm(pdfDoc, true).AddField(sgnField);

您应该改用 AddField(PdfFormField field, PdfPage page)

PdfAcroForm.GetAcroForm(pdfDoc, true).AddField(sgnField, pdfDoc.GetFirstPage());

@iText DEV:在使用 PDF2 时,应该避免这种情况。

mkl 的回答很棒

也适用于您尝试添加到 PDF 页面的其他组件,例如 PdfTextFormField:

我发现最简单的方法是应用 getPage 作为参数,以确保我得到的正是我所期望的。

示例:

PdfAcroForm
    .getAcroForm(pdfDoc, true)
    .addField(myTextArea, pdfDoc.getPage(pageCount));