开发者

Copying a PDF form with iTextSharp

I am successfully using iTextSharp to read in a PDF with a form, fill out fields on the form, and write it back out to the client. I've now gotten a requirement that certain pages should be removed if they're all blank (for purposes of the question, I can check a boolean variable to know whether or not I need to remove the pages. My understanding is to do this in iTextSharp you are actually copying the PDF from one to another, and omitting the pages to be removed.

I have this working, but I'm losing the form on the copied PDF; i.e. no values are being written out where before trying to copy the PDF to "remove" some pages, the values were being written correctly.

How can I retain the PDF form I've already created when I copy the form, or is there a better way of removing pages? Here is my code so far, that writes the PDF to a file but doesn't fill out the form (presumably because the form isn't preserved when copying):

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

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

        PdfWr开发者_如何转开发iter 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();
        }
    }


Nevermind, I seem to have been able to figure it out by using the SelectPages method on the PDF reader, and I can avoid having to do an actual copy of the files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜