0

I am creating a pdf and would like to add existing pdfs and/or images. I have the following code that works well for the images, but I am having trouble with the pdf section as the existing pdf is not displayed in the new pdf, while the images are fine. I found the following question but my code looks similar. Any ideas as to what I am missing?

        using (MemoryStream ms = new MemoryStream())
        {
            PdfWriter pWriter = PdfWriter.GetInstance(myDoc, ms);

            myDoc.Open();

            int index = 0;
            iTextSharp.text.Image img;
            foreach (var buf in bufList)
            {
                if (uploadType[index] == 0)
                {
                    PdfContentByte pdfContentByte = pWriter.DirectContent;

                    PdfReader reader = new PdfReader(buf);
                    int pageCount = reader.NumberOfPages;
                    myDoc.SetPageSize(reader.GetPageSizeWithRotation(1));

                    for (int pageNum = 1; pageNum <= pageCount; pageNum++)
                    {
                        myDoc.NewPage();
                        PdfImportedPage importedPage = pWriter.GetImportedPage(reader, pageNum);
                        pdfContentByte.AddTemplate(importedPage, 0, 0);
                    }
                    reader.Close();
                }
                else
                {
                    myDoc.NewPage();
                    img = iTextSharp.text.Image.GetInstance(buf);
                    img.ScaleToFit(612f, 792f);
                    img.Alignment = iTextSharp.text.Image.ALIGN_CENTER | iTextSharp.text.Image.ALIGN_MIDDLE;
                    myDoc.Add(img);
                }
                index++;
            }

            pWriter.CloseStream = false;
            myDoc.Close();
            ms.Position = 0;
        }
Community
  • 1
  • 1
MrM
  • 21,709
  • 30
  • 113
  • 139
  • 1
    what exactly is the problem? Exception? – slfan Nov 18 '11 at 20:17
  • I am not getting the existing pdf to be displayed, even though the images are displayed with no problems. – MrM Nov 18 '11 at 20:29
  • It looks near enough to correct to me; though perhaps this might help - http://khsw.blogspot.com/2006/04/merge-pdf-files-using-itextsharp.html – Reddog Nov 18 '11 at 20:39

1 Answers1

0

If the Pdf is generated and no Exception is thrown in your code, which does look OK from a quick glance, I would check two things:

  1. What's in uploadType - are the values always 0?
  2. What's in bufList - are there any PDFs? (either file path or byte array)

Since the question is also tagged with asp.net, here's a simple working example (HTTP handler .ashx) where bufList uses file paths - this way you don't need to maintain the uploadType collection:

<%@ WebHandler Language="C#" Class="appendExisting" %>
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;

public class appendExisting : IHttpHandler {
  public void ProcessRequest (HttpContext context) {
    HttpResponse Response = context.Response;
    HttpServerUtility Server = context.Server;
    Response.ContentType = "application/pdf";
    string[] bufList = {
      Server.MapPath("~/app_data/01.pdf"),
      Server.MapPath("~/app_data/02.pdf"),
      Server.MapPath("~/app_data/01.jpg"),
      Server.MapPath("~/app_data/02.png")
    };
    using (Document document = new Document()) {
      PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
      document.Open();

// simulate the existing content you were asking about
      document.Add(new Paragraph("Paragraph"));

      PdfContentByte cb = writer.DirectContent;
      foreach (var buf in bufList) {
        bool isPdf = Regex.IsMatch(
          Path.GetExtension(buf), @"\.pdf$", RegexOptions.IgnoreCase
        );
        if (isPdf) {
          PdfReader reader = new PdfReader(buf);
          int pages = reader.NumberOfPages;
          for (int i = 0; i < pages; ) {
            document.NewPage();
            PdfImportedPage page = writer.GetImportedPage(reader, ++i);
            cb.AddTemplate(page, 0, 0);
          }
        }
        else {
          document.NewPage();
          iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(buf);
          img.ScaleToFit(612f, 792f);
          img.Alignment = iTextSharp.text.Image.ALIGN_CENTER 
              | iTextSharp.text.Image.ALIGN_MIDDLE
          ;
          document.Add(img);        
        }
      }
    }
  }
  public bool IsReusable {
    get { return false; }
  }
}
kuujinbo
  • 9,272
  • 3
  • 44
  • 57
  • The upload type is either 0 or 1. The images load fine, but the function for the pdf merge does not work. If this is not the code snippet that has the error, any suggestions? – MrM Nov 21 '11 at 19:33
  • That's what I was asking; have you stepped through the values of **both** `uploadType' and `bufList` in your code to make sure they actually have the values you are expecting? – kuujinbo Nov 22 '11 at 06:39