如何使用iText7向新建PDF中添加HTML与纯文本内容
在iText7中结合纯文本与HTML内容生成PDF
要在iText7的PDF中同时添加纯文本和HTML内容,你需要用到pdfHTML组件(iText7官方的HTML转PDF工具),具体步骤如下:
1. 安装pdfHTML依赖
先确保项目中引入iText7.pdfHtml包,通过NuGet命令安装:
Install-Package iText7.pdfHtml
2. 修改代码整合纯文本与HTML内容
使用HtmlConverter.ConvertToElements()方法将HTML字符串转换为iText可识别的元素,再添加到Document中。同时修正原代码中资源释放的顺序问题(using块会自动处理资源,无需手动调用Close()):
public ActionResult CreatePdf() { byte[] pdfBytes; using (var stream = new MemoryStream()) using (var wri = new PdfWriter(stream)) using (var pdf = new PdfDocument(wri)) using (var doc = new Document(pdf)) { // 添加纯文本内容 doc.Add(new Paragraph("Working with iText7")); doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE)); PdfOutline root = pdf.GetOutlines(false); foreach (var item in col1) { doc.Add(new Paragraph(item.Name)); root.AddOutline(item.Name); doc.Add(new AreaBreak()); } // 解析并添加第一个HTML字符串内容 string htmlString1 = "<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>"; IList<IElement> htmlElements1 = HtmlConverter.ConvertToElements(htmlString1); foreach (var element in htmlElements1) { doc.Add((IBlockElement)element); } doc.Add(new AreaBreak()); // 可选:添加分页符分隔不同内容块 // 解析并添加第二个HTML字符串内容 string htmlString2 = "<p>My 2nd paragraph</p><hr><p>My 3rd paragraph</p>"; IList<IElement> htmlElements2 = HtmlConverter.ConvertToElements(htmlString2); foreach (var element in htmlElements2) { doc.Add((IBlockElement)element); } doc.Flush(); pdfBytes = stream.ToArray(); } return File(pdfBytes, "application/pdf", "test.pdf"); }
关键说明
HtmlConverter.ConvertToElements():将HTML字符串解析为iText的IElement集合,支持常见HTML标签(如<h1>、<p>、<hr>等)的渲染。- 类型转换:将
IElement强制转为IBlockElement,是因为Document.Add()仅接受块级元素,确保HTML内容能正确插入文档流。 - 资源管理:using语句会自动释放
PdfDocument和Document资源,无需手动调用Close()。
内容的提问来源于stack exchange,提问作者citm09
相关产品推荐
相关产品推荐

