tags:

views:

282

answers:

1

I've written an application to process a big load of PDF's by parsing data from a CSV file. The problem I've got is that I want to save the first page of the PDF and the first page only. When I use PdfReader's reader.SelectPages("1") it causes the form fields to be flattened. If I comment it out, everything works fine.

Any ideas why this method would cause all form fields to be flattened? It exports the one page correctly however.

Here's a small extract:

PdfReader reader = new PdfReader(formFile);
reader.SelectPages("1");
string newFile = Environment.CurrentDirectory + @"\Out" + documentCount  + ".pdf";
PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create), '\0', true);
AcroFields fields = stamper.AcroFields;

If I comment out the second line, there's no problems at all. I guess this is for people whom know how to use iTextSharp.

Cheers

A: 

If you just want to extract pages from an existing PDF I recommend you take a look at code I found on James Welch's blog article How to extract pages from a PDF document.

Here's the original code from the blog:

private static void ExtractPages(string inputFile, string outputFile, int start, int end) {
    // get input document
    PdfReader inputPdf = new PdfReader(inputFile);

    // retrieve the total number of pages
    int pageCount = inputPdf.NumberOfPages;

    if (end < start || end > pageCount) {
        end = pageCount;
    }

    // load the input document
    Document inputDoc = new Document(inputPdf.GetPageSizeWithRotation(1));

    // create the filestream
    using (FileStream fs = new FileStream(outputFile, FileMode.Create)) {
        // create the output writer
        PdfWriter outputWriter = PdfWriter.GetInstance(inputDoc, fs);
        inputDoc.Open();
        PdfContentByte cb1 = outputWriter.DirectContent;

        // copy pages from input to output document
        for (int i = start; i <= end; i++) {
            inputDoc.SetPageSize(inputPdf.GetPageSizeWithRotation(i));
            inputDoc.NewPage();

            PdfImportedPage page =
                outputWriter.GetImportedPage(inputPdf, i);
            int rotation = inputPdf.GetPageRotation(i);

            if (rotation == 90 || rotation == 270) {
                cb1.AddTemplate(page, 0, -1f, 1f, 0, 0,
                    inputPdf.GetPageSizeWithRotation(i).Height);
            } else {
                cb1.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
            }
        }

        inputDoc.Close();
    }
}
Jay Riggs