【问题标题】:Append HTML header to Spire PDF将 HTML 标题附加到 Spire PDF
【发布时间】:2019-04-25 10:21:57
【问题描述】:

我正在使用 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模板渲染到页眉和页脚?

【问题讨论】:

    标签: c# pdf spire


    【解决方案1】:

    Spire.PDF 提供了一个类 PdfHTMLTextElement,支持在 PDF 页面上呈现简单的 HTML 标签,包括 Font、B、I、U、Sub、Sup 和 BR。您可以使用以下代码 sn-p 将 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");
    

    【讨论】:

      猜你喜欢
      • 2011-02-13
      • 1970-01-01
      • 2015-06-19
      • 2010-12-09
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多