【问题标题】:Creating a new PDF from an existing template - odd behavior in Acrobat XI从现有模板创建新 PDF - Acrobat XI 中的奇怪行为
【发布时间】:2013-11-21 16:48:58
【问题描述】:

我正在从在 LibreOffice 中创建的现有模板生成新的 PDF。它包含一个文本框。

代码编译并成功将 PDF 保存到新文件后,如果我在 Acrobat Reader XI 中打开新创建的文档,它会正确呈现,但是,即使我不修改最终文档,在关闭文档时,它会询问“是否要在关闭前保存对“filename.pdf”的更改?”

我已阅读 StackOverflow 及其官方网站 (iTextSharp) 上的其他帖子,并找到了一个解决方案,这可能是我以错误的方式实施。

    public string spdftemplate = @"C:\test\input.pdf";
    public string newFile = @"C:\test\output.pdf";

    private void FillFormsProperly()
    {

        PdfReader reader = new PdfReader(spdftemplate);
        byte[] bytes;
        using (MemoryStream ms = new MemoryStream())
        {
            PdfStamper stamper = new PdfStamper(reader, ms);

            #region ForTesting
            //PdfContentByte cb = stamper.GetOverContent(1);
            //ColumnText ct = new ColumnText(cb);
            //ct.SetSimpleColumn(100, 100, 500, 200);
            //ct.AddElement(new Paragraph("This was added using ColumnText"));
            //ct.Go();
            #endregion ForTesting

            AcroFields pdfFormFields = stamper.AcroFields;

            foreach (DictionaryEntry de in reader.AcroFields.Fields)
            {
                pdfFormFields.SetField(de.Key.ToString(), "test"); //"Text Box 1"
            }

            //string sTmp = "W-4 Completed for " + pdfFormFields.GetField("Text Box 1");
            //MessageBox.Show(sTmp, "Finished");

            //Flush the PdfStamper's buffer
            stamper.FormFlattening = true;
            stamper.Close();
            //Get the raw bytes of the PDF
            bytes = ms.ToArray();

        }

        //Do whatever you want with the bytes
        //Below I'm writing them to disk 
        using (FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            fs.Write(bytes, 0, bytes.Length);
        }
    }

我找到的最佳答案是:creating a pdf from a template in itextsharp and outputting as content disposition.

以上代码是我的(或多或少复制粘贴)实现。

很明显文件已损坏(但仍然可读),我该如何解决这个问题?

【问题讨论】:

  • 如果需要,我可以附上模板。
  • 请同时提供输入模板和输出文档。
  • 看来LibreOffice有罪,输入PDF也提示保存文件对话框。

标签: c# .net pdf itextsharp


【解决方案1】:

您的 input.pdf 包含一个表单域和标志 /NeedAppearances true。您的 output.pdf 不再包含字段(显然......毕竟您已将表单展平)但它仍然包含该标志 /NeedAppearances true

此标志告诉 PDF 查看器 (Acrobat Reader) 为某些表单域生成外观流。因此,Reader 检查所有字段以在必要时创建外观。之后,它删除了标志。因此,文件然后被更改;就算没有字段,至少去掉flag也是一种改变。

这让人想起去年 2 月在 iText 中修复的 iText 问题:

在某些情况下,Adobe Reader X 会在您关闭拼合的 PDF 表单后询问您是否要“保存更改”。这是由于 /AcroForm 字典中存在一些不必要的条目(例如在使用 OOo 创建表单时添加的)。

(iText 修订版 5089,2012 年 2 月 29 日,blowagie)

此更改已在 iTextSharp 修订版 323 中移植到 iTextSharp,2012 年 3 月 3 日,psoares33。

因此,您可能需要更新您使用的 iTextSharp 版本。

【讨论】:

  • 所以,我已经用最新版本的 OOo 和 LO 对此进行了测试。
  • 使用最新版本的 itextsharp 5.4.4 - 在您的 output.pdf 中找不到更多当前 iTextSharp 版本留在文档中的指纹。请检查您使用的库。
猜你喜欢
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多