我正在使用iText从我的HTML模板生成PDF文件。我有一个div
的列表,我想要显示,而不是尽可能分开。但是在使用XMLWorker
时,我无法找到控制此行为的方法。我该如何达到这个效果?
答案 0 :(得分:1)
您很幸运 - <div>
是可以应用page-break-inside: avoid
CSS样式的两个HTML标记之一。这是一个有效的测试用例,首先生成一些测试HTML:
public string GetHtml()
{
var html = new StringBuilder();
var repeatCount = 15;
for (int i = 0; i < repeatCount; ++i) { html.Append("<h1>h1</h1>"); }
var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vestibulum sollicitudin luctus. Curabitur at eros bibendum, porta risus a, luctus justo. Phasellus in libero vulputate, fermentum ante nec, mattis magna. Nunc viverra viverra sem, et pulvinar urna accumsan in. Quisque ultrices commodo mauris, et convallis magna. Duis consectetur nisi non ultrices dignissim. Aenean imperdiet consequat magna, ac ornare magna suscipit ac. Integer fermentum velit vitae porttitor vestibulum. Morbi iaculis sed massa nec ultricies. Aliquam efficitur finibus dolor, et vulputate turpis pretium vitae. In lobortis lacus diam, ut varius tellus varius sed. Integer pulvinar, massa quis feugiat pulvinar, tortor nisi bibendum libero, eu molestie est sapien quis odio. Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
html.Append(text);
for (int i = 0; i < repeatCount; ++i)
{
html.AppendFormat(
"<div style='page-break-inside:avoid;>{0}</div>",
text
);
}
return html.ToString();
}
其次,最简单的解析实现:
using (var html = new StringReader(GetHtml()))
{
using (FileStream stream = new FileStream(
OUTPUT_FILE,
FileMode.Create,
FileAccess.Write))
{
using (var document = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(
document, stream
);
document.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(
writer, document, html
);
}
}
}