2017-09-13 155 views
1

我能够下载和存储正在生成的PDF文档,但不是下载我想在浏览器中打开它。 我有这样的事情而不是下载在浏览器中打开pdf(使用itext)mvc

MemoryStream os = new MemoryStream(); 
PdfWriter writer = new PdfWriter(os); 
var pdfDocument = new PdfDocument(writer); 

using (var document = new Document(pdfDocument)) 
{ 
    //I am adding different sections here 
} 
var response = new HttpResponseMessage 
{ 
    StatusCode = HttpStatusCode.OK, 
    Content = new ByteArrayContent(os.ToArray()) 
}; 

response.Content.Headers.Add("Content-Type", "application/pdf"); 
response.Headers.Add("Content-disposition", "attachment;filename=" + "testPDF.pdf"); 
return response; 

响应进一步发送到控制器,并且有它被下载,但我希望在新的浏览器中打开。 对于我来说,“Content-disposition”,“attachment; filename”不起作用。

我的返回值正在控制器上进一步传递到存储在blob中并继续下载的地方。

public async Task<IActionResult> GenerateDocument(int id) 
    { 
     var result = await _applicationService.GenerateDocument(id); 
     var blobResult = await _applicationService.SaveDocument(id, result.ResponseObject); 

     IActionResult OnSuccess() => 
      new RedirectResult(blobResult.ResponseObject.URI, true); 

     return HandleResult(OnSuccess, blobResult.Status); 
    } 
+0

我知道有类似的问题,但事情对我来说,他们提到不正常的解决方案....我在我的评论中也提到了这一点。 – Tina

回答

2

您可能需要使用inline的内容部署到让浏览器知道要显示它

//...code removed for brevity 
var buffer = os.ToArray(); 
var contentLength = buffer.Length; 
var statuscode = HttpStatusCode.OK; 
var response = Request.CreateResponse(statuscode); 
response.Content = new ByteArrayContent(buffer); 
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); 
response.Content.Headers.ContentLength = contentLength; 
ContentDispositionHeaderValue contentDisposition = null; 
if (ContentDispositionHeaderValue.TryParse("inline; filename=" + "testPDF.pdf", out contentDisposition)) { 
    response.Content.Headers.ContentDisposition = contentDisposition; 
} 
return response; 
+0

我试着更换代码,但它继续下载。我不介意下载部分,但我需要它在浏览器中打开。我也在想它与控制器有关。 – Tina

相关问题