使用MvcRazorToPdf显示页码

时间:2015-11-09 19:27:14

标签: c# itextsharp mvcrazortopdf

我正在尝试在我的项目中使用this包,并希望显示页码。 Document对象上有一个具有PageNumber但是的属性。我不知道如何从视图中访问它

当前代码:

PrintManager prntManager = new PrintManager();
var data = prntManager.ObjectToPdf(item, para);
byte[] pdf = null;

pdf = ControllerContext.GeneratePdf(prntManager.CreateController<PrintingController>(), data, prntManager.ReportToView(para.Export.Report.Code));   

HttpContext.Current.Response.AppendHeader("Export-Location", prntManager.GeneratePdf(pdf));

1 个答案:

答案 0 :(得分:2)

如果有人遇到同样的问题,我的解决方案是:

PrintManager prntManager = new PrintManager();
var data = prntManager.ObjectToPdf(item, para);
byte[] pdf = null;
var cfg = new Action<iTextSharp.text.pdf.PdfWriter,iTextSharp.text.Document>((writer, document) =>
{
    writer.PageEvent = new StandardPrintHelper();
    document.NewPage();
});

pdf = ControllerContext.GeneratePdf(prntManager.CreateController<PrintingController>(), data, prntManager.ReportToView(para.Export.Report.Code), cfg);   

HttpContext.Current.Response.AppendHeader("Export-Location",
    prntManager.GeneratePdf(pdf));

StandardPrintHelper:

public class StandardPrintHelper : iTextSharp.text.pdf.PdfPageEventHelper
{
    public override void OnEndPage(PdfWriter writer, Document document)
    {
        ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, new Phrase(writer.PageNumber.ToString()), 500, 140, 0);
    }
}