【问题标题】:How to view PDF document in MVC and not download it directly?如何在 MVC 中查看 PDF 文档而不是直接下载?
【发布时间】:2018-04-30 17:08:25
【问题描述】:

我有一个链接,点击它,HTML 页面将被转换为 PDF 文档,然后将此 PDF 文件返回给用户。

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文件显示给用户,然后他可以下载。

我该怎么做?

【问题讨论】:

    标签: c# asp.net-mvc html-to-pdf fileresult


    【解决方案1】:

    您必须在对inline 的响应中设置Content-Disposition 标头

    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());
        //Content-Disposition header set to inline along with file name for download
        Response.AppendHeader("Content-Disposition", "inline; filename=" + empID + ".pdf");
           
        return File(databytes, "application/pdf;");
    }
    

    浏览器将解释标题并直接在浏览器中显示文件,只要它有能力这样做,无论是内置的还是通过插件。

    【讨论】:

      猜你喜欢
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2018-07-20
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多