3

I am trying to read some pdf files page by page and add the pages to an existing pdf using itextsharp. Here is my solution:

string path2 = Server.MapPath("~/2.pdf");
PdfReader reader = null;
iTextSharp.text.Document document = null;
PdfCopy pdfCopyProvider = null;
PdfImportedPage importedPage = null;
foreach (var pdfName in pdfNames)
{
    path1 = Path.Combine(Server.MapPath("~/Files/Pdf/temp/"), pdfName);
    reader = new PdfReader(path1);
    for (int pageIndex = 1; pageIndex <= reader.NumberOfPages; pageIndex++)
    {
        document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(pageIndex));
        pdfCopyProvider = new PdfCopy(document, new System.IO.FileStream(path2, System.IO.FileMode.Append));
        document.Open();
        importedPage = pdfCopyProvider.GetImportedPage(reader, pageIndex);
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(importedPage);
        pdfCopyProvider.AddPage(importedPage);
    }
    reader.Close();
    document.Close();
}

But the output pdf just contains the pages of last pdf in the foreach loop.

Hamid Reza
  • 2,913
  • 9
  • 49
  • 76
  • You create the `Document` and the `PdfCopy` again and agan in your loop. You have to create one instance at the very beginning and adding all pages to that instance. – mkl Mar 02 '15 at 10:22
  • [This Q&A is similar](http://stackoverflow.com/a/28661155/231316), the answer should hopefully show you what @mkl is talking about. – Chris Haas Mar 02 '15 at 15:17

0 Answers0