0

我正要使用 iTextSharp 填写 PDF 表格,但我发现,这里有一个新的孩子:iText 7.0。自然地,我尝试了一下,但不幸的是,它并不顺利。这是一个问题。我有可编辑的 PDF 表单,需要以编程方式填写。我使用以下代码来完成:

string srcPdfFormPath = @"<Path to source pdf form>";
string destPdfFormPath = @"<Path to destination pdf form>";
using (PdfDocument pdfDocument = new PdfDocument(reader, new PdfWriter(destPdfFormPath)))
{
    PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDocument, true);

    var fieldName = "FullName";
    var pdfField = form.GetField(fieldName);
    if (pdfField != null)
        pdfField.SetValue("John Doe", null);
    else
        Debug.WriteLine($"Cannot find following field {fieldName } on pdf form.");

    pdfDocument.Close();
}

尽管已填充所需的字段,但表单不仅已被展平(AFAIK 不是预期的行为),而且当填充的 pdf 将在 Acrobat 阅读器中打开时,它会产生以下消息:

“此文档在 Adob​​e Acrobat Reader DC 中启用了扩展功能。该文档自创建以来已更改,扩展功能的使用不再可用。请联系作者获取此文档的原始版本。”

这些结果不是我们一直追求的。因此,为了保持文档的可编辑性并摆脱讨厌的消息,我决定在“附加模式”下打开 PDF 表单。这是我使用过的代码:

string srcPdfFormPath = @"<Path to source pdf form>";
string destPdfFormPath = @"<Path to destination pdf form>";
using (PdfDocument pdfDocument = new PdfDocument(reader, new PdfWriter(destPdfFormPath)
                         , new StampingProperties().UseAppendMode()))
{
    PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDocument, true);

    var fieldName = "FullName";
    var pdfField = form.GetField(fieldName);
    if (pdfField != null)
        pdfField.SetValue("John Doe", null);
    else
        Debug.WriteLine($"Cannot find following field {fieldName } on pdf form.");

    pdfDocument.Close();
}

而且,唉,这次尝试也失败了。尽管不再看到讨厌的消息,但不会填充表单本身,这是不可接受的。而对于我的生活,我无法弄清楚为什么这些行为会像马和马车一样坚持并一起走!

所以问题是:我在这里错过了什么?有没有办法使用新版本的 iText 让它工作?

4

0 回答 0