c# - 使用 iTextSharp 复制 PDF 表单

标签 c# pdf-generation itext

我成功地使用 iTextSharp 读取带有表单的 PDF,填写表单上的字段,然后将其写回给客户。我现在得到一个要求,如果某些页面都是空白的,则应该删除它们(为了这个问题的目的,我可以检查一个 bool 变量来知道我是否需要删除这些页面。我的理解是这样做在 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();
        }
    }

最佳答案

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

关于c# - 使用 iTextSharp 复制 PDF 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5954300/

相关文章:

c# - 如何解决 C# Premature Object Dispose

c# - 将结构数组从 C++ 编码到 C#?

c# - 使用 CSS @Page 渲染打印页面的大小

PDF 规范 : how to specify encoding of core fonts?

pdf - 将禁用智能收缩与 wkhtmltopdf 一起使用不会影响标题字体大小

c# - 间距/前导 PdfPCell 元素

c# - 如何根据条件更改模型的可编辑属性

c# - 如何使用 C# 在 word 中使用打印到文件选项创建 postscript 文件?

itext - 使用新的比利时身份证签署 PDF(eid 中间件和 itext)

java - iText PDF;如何使用 Java 将 jpeg2000 转换为 jpg