【发布时间】:2016-04-07 11:11:55
【问题描述】:
我正在尝试使用 NReco.PdfConverter 下载从表单的 HTML 代码解析的 PDF。在发现 AJAX 不起作用后,我在许多帖子中根据建议采取了表单操作。但是,这引发了我自己无法解决的新问题:
- 如何使用模型替换控制器中丑陋的
[ValidateResponse(false)]? 如何确保文件真正被打开?以正确的方式格式化 HTML 字符串,以便 PdfGenerator 可以使用它。- 向 PDF 添加 CSS
编辑: 好的,我更新了控制器代码,现在可以成功创建 PDF 文件。我添加了以下代码行:
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");
Response.BinaryWrite(pdfBytes);
但是内容不是我所期望的。我怀疑 JSON.stringify 没有正确格式化字符串。原来我使用了错误的 jQuery 选择器,实际上选择了包含打印按钮的表单。修复后,我现在可以成功地将 HTML 字符串加载到 PDF 中,但它缺少 CSS。如何确保 PDF 看起来与使用 te PdfConverter 的网页完全一样?
HTML:
<form action="User/Template/Print" method="POST" id="print-form" enctype="multipart/form-data">
<input type="text" hidden ng-model="strHtml" name="strHtml" ng-init="printToPdf()" />
<button class="btn btn-success" type="submit">@Html.Raw(new Icon("print").Html) Print</button>
</form>
AngularJS:
angular.module("app").controller("FormController", function ($scope) {
$scope.printToPdf = function () {
var strHtml = $('#werkorderFormulier form').html();
$scope.strHtml = JSON.stringify(strHtml);
}
});
TemplateController 中的打印动作:
public FileResult Print(FormCollection fC)
{
var pdfConverter = new HtmlToPdfConverter();
var strHtml = fC.GetValue("strHtml").AttemptedValue;
var pdfBytes = pdfConverter.GeneratePdf(strHtml);
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");
Response.BinaryWrite(pdfBytes);
return File(pdfBytes, "application/pdf");
}
【问题讨论】:
标签: c# asp.net angularjs asp.net-mvc