如何在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.