使用PdfGenerator为PDF添加页码

7
这个问题涉及到NReco's PdfGenerator组件。
我使用这个产品在.NET MVC框架中使用C#将动态生成的HTML字符串转换为PDF文档。
在寻找添加页码(例如1 of 5)到PDF页脚的方法时,我在SO上发现了thisthis。并且毫不奇怪,这两个选项似乎提供了类似的方法来实现相同的目标。
虽然代码本身很有道理,但我很难理解的是 - 我的文档内容(或HTML字符串)是在视图内生成的。然后将HTML字符串传递给控制器(.cs)进行实际的转换过程。根据我对MVC框架的非常有限的了解,我认为没有办法将JavaScript代码添加到控制器中(或者有吗?)。
所以,我不太明白如何将上述两种基于JavaScript的方法合并到处理文档转换的C#函数中。或者这是应该在View中完成的事情吗?
控制器:
[HttpPost]
public ActionResult Html2Pdf(FormCollection form) {

    var docTitle = form["doctitle"].ToString();

    var headerHtml =
        "<div style='width:100%; margin-top:1em; display:block;'>" +
            "<img src='" + System.Web.HttpContext.Current.Server.MapPath("~") + "/media/images/document_banner.png' />" +
        "</div>" +
        "<div style='width:100%; bottom:110px; left:0; position:relative; display:block;'>" +
            "<span style='color:#fff; font-size:2.5em; font-family:georgia; margin-left:1em;'>" + docTitle + "</span>" +
        "</div>";

    var footerHtml =
        "<div style='width:100%; text-align:center; border-top:1px solid #abc; margin-top:2em;'>Page 0 of 0</div>;

    var htmlToPdf = new HtmlToPdfConverter();

    // various parameters get set here
    htmlToPdf.PageHeaderHtml = headerHtml;
    htmlToPdf.PageFooterHtml = footerHtml;
    ....

    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=MyTestDocument.pdf");
    htmlToPdf.GeneratedPdf(form["htmlcontent"].ToString(), null, Response.OutputStream);    // form["htmlcontent"] holds the document body
    Response.End();

    Return new EmptyResult();
}
3个回答

14

如果设置了PageHeaderHtml或PageFooterHtml属性,PdfGenerator会为您渲染页面编号,因此您不需要附加来自wkhtmltopdf帮助的javascript代码。您所需做的就是在您想呈现页码的地方标记具有“page”类元素:

htmlToPdf.PageHeaderHtml = "<div>Page: <span class="page"></span></div>";

就这些。


11

如果您想同时显示总页数(topage类),则可以使用此代码:

 var generator = new NReco.PdfGenerator.HtmlToPdfConverter();
 generator.PageFooterHtml = $@"page <span class=""page""></span> of <span class=""topage""></span>";

非常感谢!这节省了我几个小时的时间。 - Dinesh.net

1
在代码下方,仅此而已。
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.PageFooterHtml = "<div style='padding:5px !important; font-size:12px;text-align:right;'>page <span class='page'></span> of <span class='topage'></span></div>";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接