2014-10-09 73 views
1

我遇到了一個.ashx問題,它應該合併一些PDF存儲流,在一個最簡單的情況下,輸出只有一個流,輸出PDF流已損壞,但當我調用另一個ashx哪一個輸出中只有單個流可以工作,我在下面的代碼中錯過了什麼?按流合併PDF

我收集內存流:

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

我認爲在整個PDF已經寫入'context.Response.OutputStream'之後,清除並更改'context.Response'的標題是一個非常糟糕的主意。 – mkl 2014-10-09 14:44:15

+1

@mkl該死的,你是對的:)請添加你的答案 – InferOn 2014-10-09 14:56:34

+0

@AlexisPigeon ty Alex我會提煉字符串格式,bwt字符串不是問題;) – InferOn 2014-10-09 14:57:43

回答

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 & """") 

頭才能正常工作,所有響應對象清算和頭部的操作有在數據寫入響應流之前完成。