c# - 如何在MVC中查看PDF文档而不是直接下载?

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

我有一个链接,点击它,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 文件,然后他可以下载它。

我该怎么做?

最佳答案

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

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;");
}

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

关于c# - 如何在MVC中查看PDF文档而不是直接下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50105122/

相关文章:

c# - 调用 Label.Text(在 C# 中)与 Label.innerHTML 导致意外结果

c# - 将代码重构为辅助类以避免重复,但同时又不影响安全性

asp.net mvc url 路由

c# - 依赖注入(inject)初始化

c# - 使用 TheArtOfDev.HtmlRenderer.PdfSharp 从 HTML 创建 PDF

c# - HTML : how do I avoid table tag when using display: table; 中的 iText 7 可访问 PDF

c# - 移动聊天应用程序.net Api 发送消息

c# - 使用 Dependency Property 传递回调方法

asp.net-mvc - HttpContext 和 HttpContextWrapper 在单元测试和 Web 表单和 MVC 方面的区别

php - 使用 FPDF 将网页导出为 PDF