2011-12-24 26 views
0

我有一个方法返回一个pdf字节流(从可填写的pdf)有没有一种简单的方法来合并2个流成一个流,并使一个PDF出来?我需要运行我的方法两次,但需要将两个pdf转换为一个pdf流。谢谢。使用Itextsharp合并2个pdf字节流

+0

是由iTextSharp制作的字节流吗?来自两个不同可填写表单的单独字节流还是单个表单?如果他们来自单一形式,你是否把它们弄平了? – kuujinbo 2011-12-24 12:20:12

+0

暂时忘掉字节流。你的问题真的是“如何将两个PDF合并成一个?” – 2011-12-24 14:43:35

+0

这是相同的可填写PDF。我使用了Itexsharp pdf压模。现在在asp.net中使用它并将这个pdf传输到浏览器。所以,我的需求也是调用我的方法,它使用相同的PDF格式,但提供不同的数据并将一些东西放在一个流中。所以,相同的PDF将出现两次,如同一个PDF。 – user282807 2011-12-25 00:14:13

回答

3

你没有说,如果你用PdfStamper压扁填写的表格,所以我只想说,你必须试图合并它们的压平。这里是一个工作.ashx HTTP处理程序:

<%@ WebHandler Language="C#" Class="mergeByteForms" %> 
using System; 
using System.IO; 
using System.Web; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 

public class mergeByteForms : IHttpHandler { 
    HttpServerUtility Server; 
    public void ProcessRequest (HttpContext context) { 
    Server = context.Server; 
    HttpResponse Response = context.Response; 
    Response.ContentType = "application/pdf"; 
    using (Document document = new Document()) { 
     using (PdfSmartCopy copy = new PdfSmartCopy(
     document, Response.OutputStream)) 
     { 
     document.Open(); 
     for (int i = 0; i < 2; ++i) { 
      PdfReader reader = new PdfReader(_getPdfBtyeStream(i.ToString())); 
      copy.AddPage(copy.GetImportedPage(reader, 1)); 
     } 
     } 
    } 
    } 
    public bool IsReusable { get { return false; } } 

// simulate your method to use __one__ byte stream for __one__ PDF 
    private byte[] _getPdfBtyeStream(string data) { 
// replace with __your__ PDF template 
    string pdfTemplatePath = Server.MapPath(
     "~/app_data/template.pdf" 
    ); 
    PdfReader reader = new PdfReader(pdfTemplatePath); 
    using (MemoryStream ms = new MemoryStream()) { 
     using (PdfStamper stamper = new PdfStamper(reader, ms)) { 
     AcroFields form = stamper.AcroFields; 
// replace this with your form field data 
     form.SetField("title", data); 
     // ... 
// this is __VERY__ important; since you're using the same fillable 
// PDF, if you don't set this property to true the second page will 
// lose the filled fields.   
     stamper.FormFlattening = true; 
     } 
     return ms.ToArray(); 
    } 
    } 
} 

希望内联评论是有道理的。上面的方法_getPdfBtyeStream()模拟您的PDF字节流。您需要将FormFlattening设置为true的原因是,当您填写PDF表单字段时,名称应该是唯一的。在你的情况下,第二页是可填写的PDF表单,所以它与第一页具有相同的字段名称,当你填写它们时,它们被忽略。注释掉上面的示例行:

stamper.FormFlattening = true; 

看看我的意思。

换句话说,很多通用代码的合并PDF文件在互联网上,甚至在这里计算器将无法​​正常工作(用于填写的表单),因为Acrofield s的不计在内。事实上,如果你看一下计算器的about itextsharp tagSO常见问题解答&热门”到Merge PDFs,它在第三条评论中提到了@Ray Cheng的正确答案。

另一种合并可填充PDF的方法(不展开表单)是重命名第二个/后续页面的表单域,但这是更多的工作。

+0

感谢Kuujinbo的回答和解释。 – user282807 2011-12-28 04:33:12

+0

干杯兄弟,伟大的东西 – 2012-11-08 01:56:59