Adrien Tancrez
Adrien Tancrez

Reputation: 13

Copying PDF without loose form field structure with ItextSharp

I would like to get a pdf, keep somes pages, then save it to another destination without losing fieldstructure.

Here the code perfectly working for copying:

string sourceFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        string sourceFile = Path.Combine(sourceFolder, "POMultiple.pdf");

        string fileName = @"C:\Users\MyUser\Desktop\POMultiple.pdf";
        byte[] file = System.IO.File.ReadAllBytes(fileName);

 public static void removePagesFromPdf(byte[] sourceFile, String destinationFile, params int[] pagesToKeep)
    {
        //Used to pull individual pages from our source
        PdfReader r = new PdfReader(sourceFile);
        //Create our destination file
        using (FileStream fs = new FileStream(destinationFile, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (Document doc = new Document())
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, fs);

                //Open the desitination for writing
                doc.Open();
                //Loop through each page that we want to keep
                foreach (int page in pagesToKeep)
                {
                    //Add a new blank page to destination document
                    doc.NewPage();
                    //Extract the given page from our reader and add it directly to the destination PDF
                    writer.DirectContent.AddTemplate(writer.GetImportedPage(r, page), 0, 0);

                }
                //Close our document
                doc.Close();
            }
        }
    }

But when I open "TestOutput.pdf" file in acrobat reader all my fields are empty.

Any Help ?

Upvotes: 1

Views: 1079

Answers (1)

Paulo Soares
Paulo Soares

Reputation: 1916

You need something like this:

PdfReader reader = new PdfReader(sourceFile);
reader.SelectPages(2-4,8-9);
PdfStamper stp = new PdfStamper(reader, new FileStream(destinationFile, FileMode.Create));
stp.Close();
reader.Close();

Upvotes: 3

Related Questions