文檔首頁>>Spire.PDF教程-文檔操作>>【教程】Spire.PDF 教程:如何在C#,VB.NET中將HTML樣式化文本插入PDF
【教程】Spire.PDF 教程:如何在C#,VB.NET中將HTML樣式化文本插入PDF
Spire.PDF支持通過使用PdfHTMLTextElement類在PDF文檔中呈現(xiàn)簡單的HTML字符串。該類支持一組基本的HTML標(biāo)簽,包括Font,B,I,U,Sub,Sup和BR。對于使用CSS的復(fù)雜HTML呈現(xiàn),請檢查將HTML字符串轉(zhuǎn)換為PDF。
詳細(xì)步驟:
Step 1: 創(chuàng)建一個新的PDF文檔,添加一個頁面。
PdfDocument doc = new PdfDocument(); PdfNewPage page = doc.Pages.Add() as PdfNewPage;
Step 2: 定義HTML字符串。
string htmlText= "This demo shows how we can insert HTML styled text to PDF using " + "Spire.PDF for .NET. ";
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文本在內(nèi)容超過一頁時會分解成多個頁面。
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 HTML styled text to PDF using " + "Spire.PDF for .NET. "; //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 HTML styled text to PDF using " & "Spire.PDF for .NET. " '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")