而不是在浏览器中下载Open pdf(使用itext)mvc

时间:2017-09-13 21:47:56

标签: c# asp.net-web-api itext

我能够下载并存储正在生成的pdf文档但不是下载我想在浏览器中打开它。 我有类似的东西

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;

响应进一步发送到控制器并且正在下载,但我想在新的浏览器中打开。 对我而言,"内容配置","附件;文件名"没有用。

我的返回值正在控制器上传递,我将以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);
    }

1 个答案:

答案 0 :(得分: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;