Spire.PDF支持通过使用PdfHTMLTextElement类在PDF文档中呈现简单的HTML字符串。该类支持一组基本的HTML标签,包括Font,B,I,U,Sub,Sup和BR。对于使用CSS的复杂HTML呈现,请检查将HTML字符串转换为PDF。
详细步骤:
Step 1: 创建一个新的PDF文档,添加一个页面。
PdfDocument doc = new PdfDocument();
PdfNewPage page = doc.Pages.Add() as PdfNewPage;
Step 2: 定义HTML字符串。
string htmlText= "This demo shows how we can insert <u><i>HTML styled text</i></u> to PDF using "
+ "<font color='#FF4500'>Spire.PDF for .NET</font>. ";
Step 3: 渲染HTML文本。
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 5);
PdfBrush brush = PdfBrushes.Black;
PdfHTMLTextElement richTextElement = new PdfHTMLTextElement(htmlText, font, brush);
richTextElement.TextAlign = TextAlign.Left;
Step 4: 格式化页面布局,以使HTML文本在内容超过一页时会分解成多个页面。
PdfMetafileLayoutFormat format = new PdfMetafileLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
format.Break = PdfLayoutBreakType.FitPage;
Step 5: 在页面上绘制HTML字符串。
richTextElement.Draw(page, new RectangleF(0, 20, page.GetClientSize().Width, page.GetClientSize().Height), format);
Step 6: 保存文档。
doc.SaveToFile("Output.pdf");
输出:
完整代码:
[C#]
//Create a Pdf document
PdfDocument doc = new PdfDocument();
//Add a new page
PdfNewPage page = doc.Pages.Add() as PdfNewPage;
//HTML string
string htmlText= "This demo shows how we can insert <u><i>HTML styled text</i></u> to PDF using "
+ "<font color='#FF4500'>Spire.PDF for .NET</font>. ";
//Render HTML text
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 5);
PdfBrush brush = PdfBrushes.Black;
PdfHTMLTextElement richTextElement = new PdfHTMLTextElement(htmlText, font, brush);
richTextElement.TextAlign = TextAlign.Left;
//Format Layout
PdfMetafileLayoutFormat format = new PdfMetafileLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
format.Break = PdfLayoutBreakType.FitPage;
//Draw htmlString
richTextElement.Draw(page, new RectangleF(0, 20, page.GetClientSize().Width, page.GetClientSize().Height), format);
doc.SaveToFile("Output.pdf");
[VB.NET]
'Create a Pdf document
Dim doc As New PdfDocument()
'Add a new page
Dim page As PdfNewPage = TryCast(doc.Pages.Add(), PdfNewPage)
'HTML string
Dim htmlText As String = "This demo shows how we can insert <u><i>HTML styled text</i></u> to PDF using "
& "<font color='#FF4500'>Spire.PDF for .NET</font>. "
'Render HTML text
Dim font As New PdfFont(PdfFontFamily.Helvetica, 5)
Dim brush As PdfBrush = PdfBrushes.Black
Dim richTextElement As New PdfHTMLTextElement(htmlText, font, brush)
richTextElement.TextAlign = TextAlign.Left
'Format Layout
Dim format As New PdfMetafileLayoutFormat()
format.Layout = PdfLayoutType.Paginate
format.Break = PdfLayoutBreakType.FitPage
'Draw htmlString
richTextElement.Draw(page, New RectangleF(0, 20, page.GetClientSize().Width, page.GetClientSize().Height), format)
doc.SaveToFile("Output.pdf")