Nate M.
Nate M.

Reputation: 842

Duplicate pdf pages using PdfStamper / PdfReader

I have a file containing multiple shipping labels, 2 per page (I can't choose this format). I am trying to modify the file so that each individual label is printable on a 4x6 label printer.

I am having an issue duplicating the content of a pdf page, to another page so that I can then crop each page with different regions to produce 2 pages, one with each label from the original page. The code I have currently is as follows:

 string filename = "Package.pdf";
        using (var existingFileStream = new FileStream(filename, FileMode.Open))
        {
            var pdfReader = new PdfReader(existingFileStream);

            using (FileStream output = new FileStream("Mod_package.pdf", FileMode.Create, FileAccess.Write))
            {
                using (PdfStamper pdfStamper = new PdfStamper(pdfReader, output))
                {
                    int originalpages = pdfReader.NumberOfPages;
                    for(int page = 1; page <=originalpages; page++)
                    {
                        Rectangle rect = pdfReader.GetCropBox(page);
                        pdfStamper.InsertPage(page * 2, rect);
                    }
                    for(int page = 2; page <=pdfReader.NumberOfPages; page=page+2)
                    {

                        //I want to insert the content from pdf page 1 into
                        //page 2, page 3 into page 4 etc etc.
                    }
                    for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                    {
                        //The basic jyst of how I'm cropping
                        //This will be modified to use an even/odd page scheme
                        Rectangle rect = pdfReader.GetCropBox(page);
                        rect.Bottom = rect.Bottom / 2;
                        pdfReader.GetPageN(page).Put(PdfName.CROPBOX, new PdfRectangle(rect));
                        rect = pdfReader.GetCropBox(page);
                        rect.Top = rect.Top / 2;
                        pdfReader.GetPageN(page).Put(PdfName.CROPBOX, new PdfRectangle(rect));
                    }
                }
            }
            pdfReader.Close();
        }

I would appreciate any recommendations on how to accomplish this task and my apologies if I have weird ITextSharp code.. I'm relatively new to it.

Upvotes: 1

Views: 1242

Answers (1)

Nate M.
Nate M.

Reputation: 842

It figures that as soon as I take the time to post the question, that I would find the answer. In the above code, I inserted the following:

pdfStamper.ReplacePage(pdfReader, page - 1, page);

With that in the second for loop, the contents of page 1 are transferred to page 2, 3 to 4 etc etc.

Upvotes: 2

Related Questions