Append HTML header to Spire PDF

1.5k Views Asked by At

I am using Spire PDF to convert my HTML template to PDF file. Here is the sample code for the same:

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

This is working as expected but now I want to add Header and Footer to all the pages. Though adding header and footer is possible using SprirePdf but my requirement is to add HTML template to the Header which I am not able to achieve. Is there any way to render html template to Header and footer?

1

There are 1 best solutions below

0
vaalex On

Spire.PDF provides a class PdfHTMLTextElement supporting to render simple HTML tags including Font, B, I, U, Sub, Sup and BR on a PDF page. You can append HTML to header space in an existing PDF document using the following code snippet. As far as I know, there is no way to render complicated HTML only as a part of the document by using Spire.PDF.

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