简体   繁体   中英

How to save every page except the first one of a PDF file in C#

Requirement: I have a PDF file, which is in a range of 3 to 8 pages, and i need to remove the first page to save as a single PDF file, and then save the rest of the pages in a secondary file. While i managed to save the first page successfully, the other pages are being saves as One page per PDF file, and I need all pages in a single PDF file.

Current code:

using System;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;


namespace Dividir_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            extercaopdf();
            MergePdf(, @"C:\Users\Usuario\Documents\Fichaclinica\");
            Console.WriteLine("Done");
            Console.ReadKey();
        }

        static void extercaopdf()
        {
            PdfReader pdfReader = new PdfReader(@"C:\Users\Usuario\Documents\ProntuarioCompleto\aso-mesclado.pdf");
            Document document = new Document();

            if (pdfReader.NumberOfPages > 0)
            {
                // Here it saves the first page as a single PDF File.
                PdfCopy pdfCopyASO = new PdfCopy(document, new FileStream(Path.Combine(@"C:\Users\Usuario\Documents\ASO\", string.Format("pagina_{0}.pdf", 1)), FileMode.Create));
                document.Open();
                pdfCopyASO.AddPage(pdfCopyASO.GetImportedPage(pdfReader, 1));

                // Here it saves all pages as individual PDF files, instead of a single one with all pages
                for (int i = 2; i <= pdfReader.NumberOfPages; i++)
                {
                    PdfCopy pdfCopyFicha = new PdfCopy(document, new FileStream(Path.Combine(@"C:\Users\Usuario\Documents\Fichaclinica\", string.Format("ficha_{0}.pdf", i)), FileMode.Create));
                    document.Open();
                    pdfCopyFicha.AddPage(pdfCopyFicha.GetImportedPage(pdfReader, i));

                }
                document.Close();

            }
            else return;


        }

    }
}

You are telling it to do that... with string.Format("ficha_{0}.pdf", i)

PdfCopy pdfCopyFicha = new PdfCopy(document, new FileStream(
    Path.Combine(@"C:\Users\Usuario\Documents\Fichaclinica\", string.Format("ficha_{0}.pdf", i)), 
FileMode.Create));

Just specify the same file

PdfCopy pdfCopyFicha = new PdfCopy(document, new FileStream(Path.Combine(@"C:\Users\Usuario\Documents\Fichaclinica\", "ficha_rest.pdf"), FileMode.Create));  
document.Open();              
for (int i = 2; i <= pdfReader.NumberOfPages; i++)  
{                    
    pdfCopyFicha.AddPage(pdfCopyFicha.GetImportedPage(pdfReader, i));
}
document.Close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM