我正在使用Nreco PDF将html页面转换为PDF。最近实施了Bundling和Minification,因此在Web配置中设置了compilation debug = false
。
从那时起,PDF生成失败,Chrome显示此消息说“#34;无法加载PDF文档"。
当我打开调试模式时,一切都按预期工作。
以下是代码段:
public ActionResult ABC()
{
var htmlContent =System.IO.File.ReadAllText(Server.MapPath("~/Views/abc/abc.html"));
createpdf(htmlContent);
}
public void createpdf(string htmlContent)
{
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "Inline; filename=TEST.pdf");
Response.BinaryWrite(pdfBytes);
Response.Flush();
Response.End();
}
我想知道在使用debug = false运行时导致此代码失败的原因。
答案 0 :(得分:2)
没必要回答:
试试装饰代码 - > catch,debug看看catch中是否有任何错误,很可能htmlToPdf.GeneratePdf会失败,如果没有继续下一个调试步骤
确保您的PDF生成器工作正常,这意味着您将拥有一个有效的pdf文件,然后在解决方案中的App_Data文件夹上返回字节存储pdf
var appDataPath = Server.MapPath("~/App_Data");
var filename = string.Format(@"{0}.pdf", DateTime.Now.Ticks);
var path = Path.Combine(appDataPath, filename);
System.IO.File.WriteAllBytes(path, pdfBytes.ToArray());
检查创建和关闭响应
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "Inline; filename=TEST.pdf");
Response.BinaryWrite(pdfBytes);
Response.Flush();
Response.Close()
Response.End()
修改强> 经过长时间的调试,发现了什么: 当使用WebMarkupMin.Mvc进行压缩内容或最小化时,控制器动作结果被压缩不正确(是正确的,但不是以你的方式返回pdf)。
webMarkupMin默认设置如下:
enableMinification ="真"
disableMinificationInDebugMode ="假"
enableCompression ="真"
disableCompressionInDebugMode ="假"
这就是调试模式在
时运行正确的原因编译debug =" true"
当debug =" true"时出现同样的错误在web.config中设置:
<webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd">
<webExtensions enableMinification="true" disableMinificationInDebugMode="false" enableCompression="true" disableCompressionInDebugMode="false" />
<!-- rest of shebang -->
</webMarkupMin>
您可能会问的问题在哪里,您的建议很简单。响应流压缩不正确。
克服问题:
//you can use FileResult, same outcome
public ActionResult ABC()
{
var htmlContent = System.IO.File.ReadAllText(Server.MapPath("~/Views/abc/abc.html"));
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
//return File(pdfBytes, "application/pdf", "TEST.pdf");
//will add filename to your response, downside is that browser downloads the response
//if your really need Content Disposition in response headers uncomment below line
//Response.AddHeader("Content-Disposition", "Inline; filename=TEST.pdf");
return File(pdfBytes, "application/pdf");
}
答案 1 :(得分:0)
更改为使用File()返回字节,如:
return File(pdfBytes, "application/pdf");
不要使用Response.BinaryWrite()直接返回字节,这会导致minifer无法读取pdf流,所以返回一个空的响应给客户端