How to view PDF document in MVC and not download it directly?

允我心安 提交于 2020-06-16 05:13:52

问题


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 code:

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

Code behind:

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

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.

How can I do this?


回答1:


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.



来源:https://stackoverflow.com/questions/50105122/how-to-view-pdf-document-in-mvc-and-not-download-it-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!