【问题标题】:Copying a PDF form with iTextSharp使用 iTextSharp 复制 PDF 表单
【发布时间】:2011-08-22 16:42:18
【问题描述】:

我成功地使用 iTextSharp 读取带有表单的 PDF,填写表单上的字段,然后将其写回客户端。我现在有一个要求,如果某些页面都是空白的,则应该删除它们(出于问题的目的,我可以检查一个布尔变量以了解我是否需要删除这些页面。我的理解是这样做在 iTextSharp 中,您实际上是在将 PDF 从一个复制到另一个,并省略要删除的页面。

我有这个工作,但我丢失了复制的 PDF 上的表格;即,在尝试复制 PDF 以“删除”某些页面之前,没有值被写入,值被正确写入。

如何保留我在复制表单时已经创建的 PDF 表单,或者有没有更好的删除页面的方法?到目前为止,这是我的代码,它将 PDF 写入文件但不填写表格(可能是因为复制时没有保留表格):

    string file = "output.pdf";
    PdfReader reader = new PdfReader("template.pdf");

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

        PdfWriter writer = PdfWriter.GetInstance(doc, ms);
        doc.Open();
        doc.AddDocListener(writer);
        for (int i = 1; i <= reader.NumberOfPages; i++)
        {
            bool skipPage = this.SkipPage; // some nifty logic here
            if (skipPage)
                continue;

            doc.SetPageSize(reader.GetPageSize(i));
            doc.NewPage();
            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage page = writer.GetImportedPage(reader, i);
            int rotation = reader.GetPageRotation(i);
            if (rotation == 90 || rotation == 270)
                cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height);
            else
                cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0);
        }
        reader.Close();
        doc.Close();
        using (FileStream fs = new FileStream(file, FileMode.Create))
        {
            // this is the part stumping me; I need to use a PdfStamper to write 
            // out some values to fields on the form AFTER the pages are removed.
            // This works, but there doesn't seem to be a form on the copied page...
            this.stamper = new PdfStamper(new PdfReader(ms.ToArray()), fs);
            // write out fields here...
            stamper.FormFlattening = true;
            stamper.SetFullCompression();
            stamper.Close();
        }
    }

【问题讨论】:

    标签: c# pdf-generation itextsharp


    【解决方案1】:

    没关系,我似乎已经能够通过在 PDF 阅读器上使用 SelectPages 方法来解决这个问题,而且我可以避免对文件进行实际复制。

    【讨论】:

    • 为什么不发布正确的代码示例而不是提示。
    猜你喜欢
    • 2014-01-06
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2019-10-10
    • 1970-01-01
    • 2011-09-02
    相关资源
    最近更新 更多