如何在MVC中查看PDF文档而不直接下载? [英] How to view PDF document in MVC and not download it directly?

查看:85
本文介绍了如何在MVC中查看PDF文档而不直接下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我点击链接后,HTML页面将转换为PDF文档,然后将该PDF文件返回给用户.

I have a link on click on it an HTML page will be converted to PDF document then return this PDF file to the user.

HTML代码:

<li><a href='@Url.Action("GetHTMLPageAsPDF", "Transaction", new { empID = employee.emplID })'>ViewReceipt</a></li>

后面的代码:

public FileResult GetHTMLPageAsPDF(long empID)
{
    string htmlPagePath = "anypath...";
    // convert html page to pdf
    PageToPDF obj_PageToPDF = new PageToPDF();
    byte[] databytes = obj_PageToPDF.ConvertURLToPDF(htmlPagePath);

    // return resulted pdf document
    FileResult fileResult = new FileContentResult(databytes, "application/pdf");
    fileResult.FileDownloadName = empID + ".pdf";
    return fileResult;
}

问题是当此文件直接将其下载返回到用户计算机时,我想向用户显示此PDF文件,然后如果他希望他可以下载它.

The problem is when this file returned its downloaded to the user computer directly, I want to display this PDF file to the user then if he wants he can download it.

我该怎么做?

推荐答案

您必须将响应中的Content-Disposition标头设置为inline

You have to set the Content-Disposition header on the response to inline

public FileResult GetHTMLPageAsPDF(long empID) {
    string htmlPagePath = "anypath...";
    // convert html page to pdf
    PageToPDF obj_PageToPDF = new PageToPDF();
    byte[] databytes = obj_PageToPDF.ConvertURLToPDF(htmlPagePath);

    //return resulted pdf document        
    var contentLength = databytes.Length;      
    Response.AppendHeader("Content-Length", contentLength.ToString());
    Response.AppendHeader("Content-Disposition", "inline; filename=" + empID + ".pdf");

    return File(databytes, "application/pdf;");
}

浏览器将解释标题并直接在浏览器中显示文件,只要它能够(通过内置或通过插件)这样做即可.

The browser will interpret the headers and display the file directly in the browser provided it has the capability to do so, either built in or via plugin.

这篇关于如何在MVC中查看PDF文档而不直接下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆