我有一个链接,点击它,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/