Question

I am trying to download and merges multiple pdf files by using ITextSharp.

It used to working before but I being got an "Content can not be added to a PdfImportedPage." error message on the line:

importedPage = writer.GetImportedPage(reader, currentPageIndex);

The full code is below, any help will be very appreciated.

private string MergeDocuments(IList<string> fileUrls, string fileName)
{
  var reportFolder = this.ReportFolder + "\\";

  using (MemoryStream output = new MemoryStream())
  {
      Document document = new Document();

      try
      {
          // Initialize pdf writer
          PdfWriter writer = PdfWriter.GetInstance(document, output);

          // Open document to write
          document.Open();
          PdfContentByte content = writer.DirectContent;
          PdfImportedPage importedPage;

          // Iterate through all pdf documents
          foreach (var url in fileUrls)
          {
              // Create pdf reader
              using (PdfReader reader = new PdfReader(new Uri(url)))
              {
                  int numberOfPages = reader.NumberOfPages;

                  // Iterate through all pages
                  for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                  {
                      // Determine page size for the current page
                      document.SetPageSize( reader.GetPageSizeWithRotation(currentPageIndex) );

                      // Create page
                      document.NewPage();
                      importedPage = writer.GetImportedPage(reader, currentPageIndex);
                      content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);

                  }
              }
          }
      }
      catch (Exception exception)
      {
          throw new Exception("Error occured", exception);
      }

      File.WriteAllBytes(reportFolder + fileName + ".pdf", output.GetBuffer());

  }

  return "Reports/" + fileName + ".pdf";
}

When I try the following code, I get a null pointer exception in the addDocument() method:

using (MemoryStream output = new MemoryStream()) {
    Document document = new Document();
    document.Open();
    PdfCopy copy = new PdfSmartCopy(document, output);
    foreach (var url in fileUrls) {
        using (WebClient client = new WebClient()) {
            var byteArray = client.DownloadData(url);
            PdfReader reader = new PdfReader(byteArray);
            copy.AddDocument(reader);
            reader.Close();
        }
    }
}
Was it helpful?

Solution

I found the problem, the document object should be closed before writing memory stream to file.

Just added document.Close() as below.

 document.Close();
 File.WriteAllBytes(reportFolder + fileName + ".pdf", output.GetBuffer());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top