2013-07-06 70 views
3

我有一些麻煩下載一個PhantomJS生成的文件到我的asp.net應用程序。 我正在運行phantomJs作爲服務器: 該文件生成正確並保存到PhantomJS文件夾中的磁盤,但在傳輸和包含到我的Http響應流期間發生了一些情況。該文件由瀏覽器下載,但是當我嘗試打開它時,文件錯誤與消息無法打開。我懷疑它在流傳輸中被破壞了?無法下載PhantomJS生成pdf

我想避免讀取從文件系統中其存儲的位置的PDF格式,而是把它弄出來響應從PhantomJS返回

PhantomJS代碼:

page.open(url, function (status) { 

    page.render(fullFileName); 

    var fs = require('fs'); 

    var pdfContent = fs.read(fullFileName); 
    response.statusCode = 200; 
    response.headers = { 
        'Cache': 'no-cache', 
        'Content-Type': 'application/pdf', 
        'Connection': 'Keep-Alive', 
        'Content-Length': pdfContent.length 
        }; 

    response.setEncoding("binary"); 
    response.write(pdfContent); 


}); 

ASP.NET代碼:

public ActionResult DownloadPdfFromUrl(ConvertionModel model) 
    { 
     HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:8080"); 

     ASCIIEncoding encoding = new ASCIIEncoding(); 
     string postData = string.Format("url={0}&fileName=myTest&extension=pdf&format=pdf", model.UrlToConvertPdf); 
     byte[] data = encoding.GetBytes(postData); 

     httpWReq.Method = "POST"; 
     httpWReq.ContentType = "application/x-www-form-urlencoded"; 
     httpWReq.ContentLength = data.Length; 

     using (Stream s = httpWReq.GetRequestStream()) 
     { 
      s.Write(data, 0, data.Length); 
     } 

     var response = (HttpWebResponse)httpWReq.GetResponse(); 

     Response.AppendHeader("Content-Disposition", "attachment;filename=test.pdf"); 

     return new FileStreamResult(response.GetResponseStream(), "application/pdf"); 
    } 

回答

1

的C#代碼看起來不錯,但最好不要返回null作用的結果。我最好寫文檔正文之前寫PhantomJS

var stream = response.GetResponseStream(); 

var buffer = new byte[response.ContentLength]; 
stream.Read(buffer, 0, buffer.Length); 

return File(buffer, "application/pdf", "test.pdf"); 

還設置響應編碼:

response.setEncoding("binary"); 
response.write(pdfContent); 
+0

是的,我更新,它返回一個FileStreamResult避免緩衝區分析/ null的返回值 – TGH

+0

我experiementing與二進制選項(更新問題)。使用該設置,我可以打開下載的pdf,但是它只是以白色背景打開爲空白pdf – TGH

+0

下載的pdf與服務器上生成的pdf大小和內容是否相同? –