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

发布于 2024-12-17 06:51:49 字数 1761 浏览 0 评论 0原文

我正在创建一个 pdf 并想添加现有的 pdf 和/或图像。我有以下代码,对于图像效果很好,但是我在处理 pdf 部分时遇到了问题,因为现有的 pdf 没有显示在新的 pdf 中,而图像则很好。我发现了以下问题,但我的代码看起来很相似。关于我缺少什么有什么想法吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不顾 2024-12-24 06:51:49

如果生成了 Pdf 并且代码中没有抛出Exception(乍一看确实不错),我会检查两件事:

  1. uploadType 中的内容 - 是值总是0?
  2. bufList 中有什么 - 有 PDF 吗? (文件路径或字节数组)

由于问题也用 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; }
  }
}

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; }
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文