Split PDF into multiple PDFs using iTextsharp Split PDF into multiple PDFs using iTextsharp asp.net asp.net

Split PDF into multiple PDFs using iTextsharp


You're looping through the pdf and creating a new document every time you advance a page. You'll need to keep track of your pages so that you perform split only every 50 pages. Personally I would put that in a separate method and call it from your loop. Something like this:

private void ExtractPages(string sourcePDFpath, string outputPDFpath, int startpage,  int endpage){    PdfReader reader = null;    Document sourceDocument = null;    PdfCopy pdfCopyProvider = null;    PdfImportedPage importedPage = null;    reader = new PdfReader(sourcePDFpath);    sourceDocument = new Document(reader.GetPageSizeWithRotation(startpage));    pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPDFpath, System.IO.FileMode.Create));    sourceDocument.Open();    for (int i = startpage; i <= endpage; i++)    {        importedPage = pdfCopyProvider.GetImportedPage(reader, i);        pdfCopyProvider.AddPage(importedPage);    }    sourceDocument.Close();    reader.Close();}

So in your original code loop through your pdf and every 50 pages call the above method. You'll just need to add variables in your block to keep track of the start/end pages.


Here is a shorter solution. Haven't tested which method has the better performance.

private void ExtractPages(string sourcePDFpath, string outputPDFpath, int startpage, int endpage){  var pdfReader = new PdfReader(sourcePDFpath);  try  {    pdfReader.SelectPages($"{startpage}-{endpage}");    using (var fs = new FileStream(outputPDFpath, FileMode.Create, FileAccess.Write))    {      PdfStamper stamper = null;      try      {        stamper = new PdfStamper(pdfReader, fs);      }      finally      {        stamper?.Close();      }    }  }  finally  {    pdfReader.Close();  }}