【教程】PDF組件Spire.PDF 教程:如何在C#,VB.NET中將HTML樣式化文本插入PDF

Spire.PDF支持經過使用PdfHTMLTextElement類在PDF文檔中呈現簡單的HTML字符串。該類支持一組基本的HTML標籤,包括Font,B,I,U,Sub,Sup和BR。對於使用CSS的複雜HTML呈現,請檢查將HTML字符串轉換爲PDF。html

詳細步驟:佈局

Step 1: 建立一個新的PDF文檔,添加一個頁面。3d

PdfDocument doc = new PdfDocument();
PdfNewPage page = doc.Pages.Add() as PdfNewPage;

Step 2: 定義HTML字符串。orm

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文本。htm

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文本在內容超過一頁時會分解成多個頁面。blog

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");

輸出:字符串

圖片1

完整代碼:get

[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")

點擊下載Spire.PDF

相關文章
相關標籤/搜索