【发布时间】:2022-01-21 08:14:53
【问题描述】:
-
使用 itext7 (7.2.0) AND itext7.pdfhtml (4.0.0) AND .Net Core 5.0
-
将 itext5 报告转换为 itext7
-
使用 html 样式“page-break-before: always;”强制分页时出现错误
public FileResult PrintHtmlToPDFPageBreak() { StringBuilder sbBody = new StringBuilder(); sbBody.Append("<html>"); sbBody.Append("<body>"); sbBody.Append("<p>This is first page</p>"); sbBody.Append("<div style='page-break-before: always;'></div>"); sbBody.Append("<p>This is second page</p>"); sbBody.Append("</body>"); sbBody.Append("</html>"); string htmlContent = sbBody.ToString(); bool isPortrait = true; string reportTitle = "Testing iText7 in .Net5"; //generate the byte array for the Pdf byte[] pdfContent = null; //Create a System.IO.MemoryStream object using (MemoryStream memoryStream = new MemoryStream()) { //Initialize PDF writer PdfWriter pdfWriter = new PdfWriter(memoryStream); //Initialize PDF document PdfDocument pdfDocument = new PdfDocument(pdfWriter); //Initialize document Document document = (isPortrait ? new Document(pdfDocument, PageSize.LETTER) : new Document(pdfDocument, PageSize.LETTER.Rotate())); var headerHeight = String.IsNullOrEmpty(reportTitle) ? 70f : 120f; document.SetMargins(headerHeight, 10f, 56f, 10f); //top, right, bottom, left #region HTML to PDF //Convert to Elements ConverterProperties converterProperties = new ConverterProperties(); IList<IElement> elements = HtmlConverter.ConvertToElements(htmlContent, converterProperties); foreach (var element in elements) document.Add((IBlockElement)element); #endregion //Close the Document document.Close(); pdfContent = memoryStream.ToArray(); //Close the MemoryStream memoryStream.Close(); } //return the byte array in the form of FileContentResult for browser download var fileName = "ConvertHtmlToPDF.pdf"; return File(pdfContent, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName); }
【问题讨论】:
标签: c# html pdf itext7 page-break