如何将现有pdf添加到创建的pdf中?

时间:2011-11-18 19:31:09

标签: c# asp.net .net pdf-generation itextsharp

我正在创建一个pdf,并希望添加现有的pdfs和/或图像。我有以下代码适用于图像,但我在pdf部分遇到问题,因为现有的pdf没有显示在新的pdf中,而图像很好。我找到了以下question,但我的代码看起来很相似。关于我缺少什么的任何想法?

        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;
        }

1 个答案:

答案 0 :(得分:0)

如果生成了Pdf且代码中没有抛出Exception,从快速浏览看起来确实没问题,我会检查两件事:

  1. uploadType中的内容 - 值是否始终为0?
  2. bufList中有什么 - 有PDF吗? (文件路径或字节数组)
  3. 由于问题也标有 asp.net ,这里有一个简单的工作示例(HTTP处理程序.ashx),其中bufList使用文件路径 - 这样您就不需要维护uploadType集合:

    <%@ 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; }
      }
    }