按流合并PDF

时间:2014-10-09 14:02:54

标签: asp.net vb.net pdf itextsharp

我遇到了一个.ashx的问题,它应该合并一些PDF内存流,在最简单的情况下,我只输出一个流,输出PDF流已损坏,但当我调用另一个ashx时只输入单个流的输出工作,我在下面的代码中遗漏了什么?

我收集内存流:

Dim streamDocument As MemoryStream = FumForm.CreatePdfDocument(context, _fumForm, _formTemplate, _match)
lReader.Add(New PdfReader(streamDocument))

然后我想将所有pdf页面附加到另一个pdf中:

Dim document As Document = New Document(PageSize.A4, 0, 0, 0, 0)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, context.Response.OutputStream)
document.Open()

For Each r As PdfReader In lReader
  For i As Integer = 1 To r.NumberOfPages
    Dim page As PdfImportedPage = writer.GetImportedPage(r, i)
    document.Add(Image.GetInstance(page))

  Next
Next

Dim filename = String.Format("{0}{1}.pdf", "pippo", "test")
document.Close()
context.Response.Clear()
context.Response.ContentType = "application/pdf"
context.Response.AppendHeader("content-disposition", "inline; filename=""" & filename & """")
context.Response.Flush()
context.Response.Close()
context.Response.End()

CreatePdfDocument运作良好,并有此签名

static public MemoryStream CreatePdfDocument(HttpContext context, 
                                             FumForm form, 
                                             FumFormTemplate formTemplate, 
                                             Match match)

任何帮助都将非常感激

1 个答案:

答案 0 :(得分:2)

代码首先将整个PDF写入context.Response.OutputStream

Dim document As Document = New Document(PageSize.A4, 0, 0, 0, 0)
Dim writer As PdfWriter = PdfWriter.GetInstance(document, context.Response.OutputStream)
...
document.Close()
之后

清除并更改context.Response

的标题
context.Response.Clear()
context.Response.ContentType = "application/pdf"
context.Response.AppendHeader("content-disposition", "inline; filename=""" & filename & """")

要正常工作,必须先完成所有响应对象清除和标题操作,然后才能将数据写入响应流。