【问题标题】:AcroFields not copied using PDFWriter未使用 PDFWriter 复制 AcroFields
【发布时间】:2016-01-08 11:14:23
【问题描述】:

我正在创建一个使用 ITextSharp 在现有 PDF 文档末尾添加页面的函数。 PDF 包含我在添加新页面之前填充的 acrofields。

当我在不添加新页面的情况下执行它时,会按预期生成 PDF,并填充所有字段。 但是当我执行并调用我的函数来添加页面时,会生成带有新页面的 PDF,但现在所有字段都是空白的......

这是我的代码:

// The first PdfReader in the list is my main pdf, with all fields.
private void AddPages(List<PdfReader> pdfs)
{
 byte[] all;

 using (MemoryStream ms = new MemoryStream())
 {
  Document doc = new Document();

  PdfWriter writer = PdfWriter.GetInstance(doc, ms);

  doc.SetPageSize(PageSize.A4);
  doc.Open();
  PdfContentByte cb = writer.DirectContent;
  PdfImportedPage page;

  foreach (PdfReader p in pdfs)
  {
    int pages = p.NumberOfPages;

    // loop over document pages
    for (int i = 1; i <= pages; i++)
    {
      doc.SetPageSize(PageSize.A4);
      doc.NewPage();
      page = writer.GetImportedPage(p, i);
      cb.AddTemplate(page, 0, 0);
    }
  }

  doc.Close();
  all = ms.GetBuffer();
  ms.Flush();
  ms.Dispose();
}

// I tried to add this code, but doesn't change anything.
AcroFields fields = Output.AcroFields;

// Output is my PdfStamper I returned, my final PDF
Output = new PdfStamper(new PdfReader(all), outStream);

foreach (var field in fields.Fields)
Output.AcroFields.Fields.Add(field);

}

知道为什么我的字段被空白以及如何解决吗?

非常感谢


编辑:

根据 cmets,这是我的新功能:

byte[] all;

using (MemoryStream ms = new MemoryStream())
{
  Document doc = new Document();
  PdfCopy copy = new PdfCopy(doc, ms);

  doc.Open();
  foreach (PdfReader pdf in pdfs)
      copy.AddDocument(pdf);

  doc.Close();

  all = ms.ToArray();
}

Output = new PdfStamper(new PdfReader(all), outStream);

但我仍然有同样的问题。我做错了什么?

【问题讨论】:

  • PdfWriter.GetImportedPage 只导入页面 content,而不是像注释这样的附加组件(例如表单字段小部件)。如需复制完整页面,请使用PdfCopy
  • 您遇到的行为是预期的并在文档中进行了描述。请参阅Chapter 6 of my bookHow to merge documents correctly?official iText developers site 上的许多其他示例和问答。您使用PdfStamper 填写表格,为什么不直接使用insert an extra page
  • 感谢您的 cmets。我已经编辑了我的代码,但我仍然遇到同样的问题(添加了页面但字段被空白)。我已经用新代码编辑了我的问题
  • 编辑:深入检查后,似乎填充了字段,但只有当我点击该字段时内容才可见!

标签: c# pdf itextsharp


【解决方案1】:

如果它可以帮助任何人,这是我现在可以使用的代码:

byte[] all;

using (MemoryStream ms = new MemoryStream())
{
  Document doc = new Document();
  PdfCopy copy = new PdfCopy(doc, ms);
  copy.SetMergeFields();

  doc.Open();
  foreach (PdfReader pdf in pdfs)
       copy.AddDocument(pdf);

  doc.Close();

  all = ms.ToArray();
}

Output = new PdfStamper(new PdfReader(all), outStream);
Output.AcroFields.GenerateAppearances = true;

感谢@Bruno Lowagie 和@mkl!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2020-03-27
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多