我正在尝试将页眉/页脚添加到PDF,其内容由XMLWorkerHelper生成。不确定这是否是放置问题,但我看不到页眉/页脚。
这是在使用来自Nuget的iTextSharp和XmlWorker软件包ver 5.4.4的ASP.NET MVC应用程序中。
生成PDF的代码如下:
private byte[] ParseXmlToPdf(string html)
{
XhtmlToListHelper xhtmlHelper = new XhtmlToListHelper();
Document document = new Document(PageSize.A4, 30, 30, 90, 90);
MemoryStream msOutput = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
writer.PageEvent = new TextSharpPageEventHelper();
document.Open();
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/themes/mytheme.css"), true);
var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
var worker = new XMLWorker(pipeline, true);
var parser = new XMLParser();
parser.AddListener(worker);
using (TextReader sr = new StringReader(html))
{
parser.Parse(sr);
}
//string text = "Some Random Text";
//for (int k = 0; k < 8; ++k)
//{
// text += " " + text;
// Paragraph p = new Paragraph(text);
// p.SpacingBefore = 8f;
// document.Add(p);
//}
worker.Close();
document.Close();
return msOutput.ToArray();
}
现在不使用这三行
using (TextReader sr = new StringReader(html))
{
parser.Parse(sr);
}
如果我将它们注释掉并取消注释代码以添加随机段落文本(在上面的示例中注释),我会看到页眉/页脚以及随机文本。
我做错了什么?
EventHandler如下:
public class TextSharpPageEventHelper : PdfPageEventHelper
{
public Image ImageHeader { get; set; }
public override void OnEndPage(PdfWriter writer, Document document)
{
float cellHeight = document.TopMargin;
Rectangle page = document.PageSize;
PdfPTable head = new PdfPTable(2);
head.TotalWidth = page.Width;
PdfPCell c = new PdfPCell(ImageHeader, true);
c.HorizontalAlignment = Element.ALIGN_RIGHT;
c.FixedHeight = cellHeight;
c.Border = PdfPCell.NO_BORDER;
head.AddCell(c);
c = new PdfPCell(new Phrase(
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " GMT",
new Font(Font.FontFamily.COURIER, 8)
));
c.Border = PdfPCell.TOP_BORDER | PdfPCell.RIGHT_BORDER | PdfPCell.BOTTOM_BORDER | PdfPCell.LEFT_BORDER;
c.VerticalAlignment = Element.ALIGN_BOTTOM;
c.FixedHeight = cellHeight;
head.AddCell(c);
head.WriteSelectedRows(
0, -1, // first/last row; -1 flags all write all rows
0, // left offset
// ** bottom** yPos of the table
page.Height - cellHeight + head.TotalHeight,
writer.DirectContent
);
}
}
答案 0 :(得分:0)
感到愤怒和愚蠢,因为我已经失去了超过两个小时的生命到Windows 8.1!显然,内置的PDF阅读器应用程序不足以显示“标题”/“页脚”。安装福昕阅读器并打开输出,它显示标题好吧!
我想我也应该尝试使用Adobe Reader !!!
更新:
我尝试在Adobe Acrobat阅读器中打开生成的PDF,最后看到了一些错误。这让我更仔细地查看了发送给XMLWorkerHelper的HTML。 HTML的结构在<div>
内部有<table>
s,这使得生成的PDF瘫痪。我清理了HTML以确保<table>
内的<table>
,然后所有读者都清楚地看到了PDF。
长话短说,上面的代码很好,但如果您正在测试PDF的正确性,请至少使用Adobe Acrobat Reader。其他读者的表现不可预测,如报告错误或错误呈现PDF。