我正在使用Spire PDF将HTML模板转换为PDF文件。这是相同的示例代码:
class Program
{
static void Main(string[] args)
{
//Create a pdf document.
PdfDocument doc = new PdfDocument();
PdfPageSettings setting = new PdfPageSettings();
setting.Size = new SizeF(1000,1000);
setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);
PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
htmlLayoutFormat.IsWaiting = true;
String url = "https://www.wikipedia.org/";
Thread thread = new Thread(() =>
{ doc.LoadFromHTML(url, false, false, false, setting,htmlLayoutFormat); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
//Save pdf file.
doc.SaveToFile("output-wiki.pdf");
doc.Close();
//Launching the Pdf file.
System.Diagnostics.Process.Start("output-wiki.pdf");
}
}
这可以按预期工作,但是现在我想在所有页面上添加页眉和页脚。虽然可以使用SprirePdf添加页眉和页脚,但是我的要求是将HTML模板添加到我无法实现的页眉中。有什么方法可以将HTML模板呈现到页眉和页脚?
答案 0 :(得分:0)
Spire.PDF提供了PdfHTMLTextElement类,该类支持在PDF页面上呈现简单的HTML标签,包括Font,B,I,U,Sub,Sup和BR。您可以使用以下代码段将HTML附加到现有PDF文档的标题空间中。据我所知,无法使用Spire.PDF将复杂的HTML仅呈现为文档的一部分。
//load an existing pdf document
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
//loop through the pages
for (int i = 0; i < doc.Pages.Count; i++)
{
//get the specfic page
PdfPageBase page = doc.Pages[i];
//define HTML string
string htmlText = "<b>XXX lnc.</b><br/><i>Tel:889 974 544</i><br/><font color='#FF4500'>Website:www.xxx.com</font>";
//render HTML text
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 12);
PdfBrush brush = PdfBrushes.Black;
PdfHTMLTextElement richTextElement = new PdfHTMLTextElement(htmlText, font, brush);
richTextElement.TextAlign = TextAlign.Left;
//draw html string at the top white space
richTextElement.Draw(page.Canvas, new RectangleF(70, 20, page.GetClientSize().Width - 140, page.GetClientSize().Height - 20));
}
//save to file
doc.SaveToFile("output.pdf");