Specific pages from a PDF file with IronPDF - C#

1.3k Views Asked by At

I have this code, and it's like I don't put any specification to exclude pages. I need to select up to 8, not continuous pages. Let's say, the pages 3, 6, and 9. So I tried this:

                var PDFs = new List<PdfDocument>();
                PDFs.Add(PdfDocument.FromFile(buscarpoliza.FileName));
                PdfDocument PDF = PdfDocument.Merge(PDFs);
                int paginas = (Convert.ToInt32(pdfpaginas.Text)) - 1;
                PDF.CopyPage(paginas).SaveAs("merged.pdf");

                var PDFs2 = new List<PdfDocument>();
                PDFs2.Add(PdfDocument.FromFile(buscarpoliza.FileName));
                PdfDocument PDF2 = PdfDocument.Merge(PDFs2);
                int paginas2 = (Convert.ToInt32(pdfpaginas2.Text)) - 1;
                PDF2.CopyPage(paginas2).SaveAs("merged2.pdf");

                var PDFs3 = new List<PdfDocument>();
                PDFs.Add(PdfDocument.FromFile(buscarpoliza.FileName));
                PdfDocument PDF3 = PdfDocument.Merge(PDFs3);
                int paginas3 = (Convert.ToInt32(pdfpaginas3.Text)) - 1;
                PDF3.CopyPage(paginas3).SaveAs("merged3.pdf");

                var PDF33 = new List<PdfDocument>();
                PDF33.Add(PdfDocument.FromFile("merged.pdf"));
                PDF33.Add(PdfDocument.FromFile("merged2.pdf"));
                PDF33.Add(PdfDocument.FromFile("merged3.pdf"));
                PdfDocument PDF3F = PdfDocument.Merge(PDF33);
                PDF3F.SaveAs("merged3f.pdf");

In my low expertise in programming, I read the entire code trying to find why the code saves the ENTIRE pdf file, and not the pages specified in the textboxes. I read the documentation and found nothing about saving more than one specific page, or a group of pages (from 6 to 9, for example). Any help will be gratefully appreciated. Thank you.

1

There are 1 best solutions below

0
On

Seems that is the way to do things with IronPdf, I haven't found another way of changing the pdf pages, inserting or adding at the beginning or the end pages of another pdf document and so on. This involves coying pages from one pdf to the final one.

To get pages from 6 to 9 for instance, you can iterate based on an index value and then add the pages to the final result:

var finalPdfPages = new List<PdfDocument>();
var originalPdf = PdfDocument.FromFile("pathToPdfFile");
for (int pageIndex = 6; pageIndex == 9; pageIndex++)
{
    finalPdfPages.Add(originalPdf.CopyPage(pageIndex));
}

PdfDocument pdf = PdfDocument.Merge(finalPdfPages);