我正在使用 itext7 版本 7.1.2 和 itext7.pdfhtml 版本 2.0.2 从一些包含不得跨页面中断的元素(例如图形及其随附文本)的 HTML 生成 PDF。
我尝试过使用显式分页符(正如在我们的旧版 iTextSharp 解决方案中成功使用的那样(使用page-break-before: always
在任何包含不应分离的元素的元素上))但这些根本不起作用,所以尝试使用更优选的page-break-inside: avoid
作为包含我不想跨多个页面的元素的元素的样式。这是代码的简化版本,它将内联 HTML 作为 PDF 在“我的文档”路径中输出...
using iText.Html2pdf;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using System;
using System.Linq;
namespace IText7Html2PdfPageBreakTester
{
internal class Program
{
private static void Main(string[] args)
{
var html = @"<html>
<head>
</head>
<body>
<div style=""font-size: 60pt"">
Some Initial Text.
</div>
<div style=""page-break-inside: avoid; font-size: 120pt"">
This text should all be on the same page.
</div>
</body>
</html>";
var pdfFilePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Example PDF.pdf");
Console.WriteLine($"Converting example HTML to PDF and writing the PDF to: \"{pdfFilePath}\".");
using (var pdfWriter = new PdfWriter(pdfFilePath))
{
using (var pdfDocument = new PdfDocument(pdfWriter))
{
var converterProperties = new ConverterProperties();
pdfDocument.SetDefaultPageSize(PageSize.A4);
using (var document = new Document(pdfDocument))
{
//NOTE: If this line is commented then the "page-break-inside: avoid" style behaves as expected.
document.SetMargins(40, 40, 40, 40);
foreach (var element in HtmlConverter.ConvertToElements(html, converterProperties).OfType<IBlockElement>())
document.Add(element);
}
}
}
Console.WriteLine($"PDF written to: \"{pdfFilePath}\".");
}
}
}
请注意,如果文档上没有设置边距,我就能够实现所需的行为;但是,业务要求在文档上设置边距,因此我如何既设置这些边距又保留page-break-inside: avoid
行为?
我也尝试过创建自定义ITagWorker
解释一个习俗<pageBreak/>
我尝试使用元素作为解决方法,但没有运气得到ProcessorContext.GetPdfDocument().AddNewPage()
实际添加页面的方法。
补充: 如果你替换html
变量具有以下内容,您可以看到两者都不是page-break-before: always
nor page-break-after: always
无论文档中是否设置了边距,都会按预期工作。
var html = @"<html>
<head>
</head>
<body>
<div style=""page-break-after: always"">
Some Initial Text.
</div>
<div>
This text should be on a new page.
</div>
<div style=""page-break-before: always; font-size: 60pt"">
This text should be on a further new page.
</div>
<div style=""page-break-inside: avoid; font-size: 120pt"">
This text should all be on the same page.
</div>
</body>
</html>";