Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract pages in memory iTextSharp

Tags:

c#

can someone help me with this problem. How can I extract some pages from pdf and return them as byte array or Stream, without using physical file as output.

Here is the way doing this using filestream:

public static void ExtractPages(string sourcePdfPath, string outputPdfPath, int      startPage, int endPage)
{

    PdfReader reader = null;
    Document sourceDocument = null;
    PdfCopy pdfCopyProvider = null;
    PdfImportedPage importedPage = null;

   try
   {

    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();
    }
    catch(Exception ex)
    {
        throw ex;
    }

}

I need something like:

public static byte[] ExtractPages(string sourcePdfPath, int startPage, int endPage)
{
....
    return byte[];
}
like image 872
user3569465 Avatar asked Oct 22 '25 20:10

user3569465


1 Answers

Replace the new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create) with a MemoryStream and return it.

Some thing like (untested, but should work):

public static byte[] ExtractPages(string sourcePdfPath, int startPage, int endPage)
{
    PdfReader reader = null;
    Document sourceDocument = null;
    PdfCopy pdfCopyProvider = null;
    PdfImportedPage importedPage = null;
    MemoryStream target = new MemoryStream();

    reader = new PdfReader(sourcePdfPath);
    sourceDocument = new Document(reader.GetPageSizeWithRotation(startPage));
    pdfCopyProvider = new PdfCopy(sourceDocument, target);
    sourceDocument.Open();

    for(int i = startPage; i <= endPage; i++)
    {
        importedPage = pdfCopyProvider.GetImportedPage(reader, i);
        pdfCopyProvider.AddPage(importedPage);
    }
    sourceDocument.Close();
    reader.Close();

    return target.ToArray();
}
like image 197
Christoph Fink Avatar answered Oct 24 '25 10:10

Christoph Fink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!