Skip to main content

Create PDF in C# from HTML File

Create PDF in C# from HTML FilePhoto From pexels

Originally Posted On: https://ironpdf.com/docs/questions/csharp-html-to-pdf-example-file-and-code/

 

IronPDF converts HTML to PDF documents programmatically.

How to Create a PDF in C# – HTML to PDF Example

A simple example of this technique can be downloaded and viewed.

The source code for this entire article is available for C# as a C# HTML to PDF Project Source Code Download.

5

The following tutorial will walk you though the process of creating and generating a PDF using IronPDF. It covers the basics as well as many advanced C# PDF topics.

HTML to PDF Walkthrough

This demo walks you through examples on how to use IronPdf. Please feel free to request any additional use case demos.

Demo consists of Hello World, RenderHtmlAsPdf and RenderUrlAsPdf examples. All the examples could be found under corresponding projects under IronPDFDemo solution.

Step 1: Installation

You can install IronPdf either via NuGet. The package name is IronPDF.

Or you can use direct link to download the library.

Step 2: Hello World

Once you have IronPDF installed and referenced in you project you can start using it right away by typing a couple of strings:

  1. var htmlToPdf = new HtmlToPdf(); // new instance of HtmlToPdf

Copy code to clipboardVB  C#

then if you need to turn html into pdf

  1. // html to turn into pdf
  2. var html = @”<h1>Hello World!</h1><br><p>This is IronPdf.</p>”;
  3. // turn html to pdf
  4. var pdf = htmlToPdf.RenderHtmlAsPdf(html);
  5. // save resulting pdf into file
  6. pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), “HtmlToPdf.Pdf”));

Copy code to clipboardVB  C#

or if you want to turn web page into pdf

  1. // uri of the page to turn into pdf
  2. var uri = new Uri(“http://www.google.com/ncr”);
  3. // turn page into pdf
  4. pdf = htmlToPdf.RenderUrlAsPdf(uri);
  5. // save resulting pdf into file
  6. pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), “UrlToPdf.Pdf”));

Copy code to clipboardVB  C#

and that is it!

Corresponding results are:

1

2

Please find the code sample under IronPDFDemo.HelloWorld project.

Step 3: RenderHtmlAsPdfExample 1

Let us now get into more real life examples. Let us imagine that we have an Invoice in the form of html that we need to turn into pdf. Here is how we do that.

Note: You can find invoice html under IronPDFDemo.DemoWebSite project (~/Static/TestInvoice1.html). Please note that invoice has custom css for “print” media type.

The source invoice looks like this in browser:

4

To turn this into a pdf , we are using almost the same code as our HelloWorld example above, the difference being that we are reading html from file:

  1. // read html from file
  2. var html = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), “TestInvoice1.html”));
  3. var htmlToPdf = new HtmlToPdf();
  4. var pdf = htmlToPdf.RenderHtmlAsPdf(html);
  5. pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), “HtmlToPdfExample1.Pdf”));

Copy code to clipboardVB  C#

Result is:

5

Looks great! Please find the code sample under IronPDFDemo.RenderHtmlAdPdfDemo project.

Also view this question on How to use HTML documents or Strings with Byte Arrays in IronPDF

Example 2

Now let us imagine that we need to bring some customization into the resulting pdf from Example 1. For example: add custom margins, add a header with a document title, footer with a creation date & pages, and add some custom css for “print” media type that our invoice has. To do this we specify an instance of PdfPrintOptions that we pass into the HtmlToPdf constructor.

  1. var pdfPrintOptions= new PdfPrintOptions()
  2. {
  3. MarginTop = 50,
  4. MarginBottom = 50,
  5. Header = new SimpleHeaderFooter()
  6. {
  7. CenterText = “{pdf-title}”,
  8. DrawDividerLine = true,
  9. FontSize = 16
  10. },
  11. Footer = new SimpleHeaderFooter()
  12. {
  13. LeftText = “{date} {time}”,
  14. RightText = “Page {page} of {total-pages}”,
  15. DrawDividerLine = true,
  16. FontSize = 14
  17. },
  18. CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
  19. };
  20. var htmlToPdf = new HtmlToPdf(pdfPrintOptions);

Copy code to clipboardVB  C#

Tip: Instead of passing options as a parameter for constructor, you can set the corresponding field for a HtmlToPdf instance:

  1. var htmlToPdf = new HtmlToPdf();
  2. htmlToPdf.PrintOptions = pdfPrintOptions;

Copy code to clipboardVB  C#

Note: Header and footer features mail merge functionality, meaning that all the merge fields ({page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title}) can be populated with corresponding data.

The rest of the code is the same as Example 1. Result is:

6

Custom margins, headers, footers, custom css for “print” media type are now in place. Please find the code sample under IronPDFDemo.RenderHtmlAdPdfDemo project. More settings can be found here in the IronPDF object reference.

Step 4: RenderUrlAsPdfSet up

To run samples from this section you need to host the IronPDFDemo.DemoWebSite locally. To do that in IIS Express:

  1. Navigate to DemoWebSite
  2. Right click -> Set as StartUp Project
  3. Start without debugging (Ctrl+F5)
  4. Navigate to your {baseurl}/Static/TestInvoice1.html to make sure it is working. In our case url this is http://localhost:51169/Static/TestInvoice1.html (will be the same for you if you do not change corresponding project settings).
Example 1

Now let us imagine that we need to turn our hosted DemoWebSite invoice into a pdf. To do that we are using almost the same code as for HelloWorld example, the difference is that we are using a different url:

  1. var uri = new Uri(“http://localhost:51169/Static/TestInvoice1.html”);
  2. var urlToPdf = new HtmlToPdf();
  3. var pdf = urlToPdf.RenderUrlAsPdf(uri);
  4. pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), “UrlToPdfExample1.Pdf”));

Copy code to clipboardVB  C#

Result is:

7

This is great and it looks as expected. Please find the code sample inside IronPDFDemo.RenderUrlAsPdfDemo project.

Example 2

Now let us imagine that we have our invoice hidden behind some basic user authentication. We need to turn it into pdf with some customization: custom margins, header with document title, footer with creation date and pages, and custom css for “print” media type. The url for the invoice is at http://localhost:51169/Invoice.

Accessing http://localhost:51169/Invoice results in “Authentication required” form:

8

Note: Credentials are “testUser”/”testPassword”.

So how can we bypass authentication? By setting our HttpLoginCredentials:

  1. var uri = new Uri(“http://localhost:51169/Invoice”);
  2. var urlToPdf = new HtmlToPdf
  3. {
  4. PrintOptions = new PdfPrintOptions()
  5. {
  6. MarginTop = 50,
  7. MarginBottom = 50,
  8. Header = new SimpleHeaderFooter()
  9. {
  10. CenterText = “{pdf-title}”,
  11. DrawDividerLine = true,
  12. FontSize = 16
  13. },
  14. Footer = new SimpleHeaderFooter()
  15. {
  16. LeftText = “{date} {time}”,
  17. RightText = “Page {page} of {total-pages}”,
  18. DrawDividerLine = true,
  19. FontSize = 14
  20. },
  21. CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
  22. },
  23. // setting login credentials to bypass basic authentication
  24. LoginCredentials = new HttpLoginCredentials()
  25. {
  26. NetworkUsername = “testUser”,
  27. NetworkPassword = “testPassword”
  28. }
  29. };
  30. var pdf = urlToPdf.RenderUrlAsPdf(uri);
  31. pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), “UrlToPdfExample2.Pdf”));

Copy code to clipboardVB  C#

Note: We are using the same customization as for the HtmlToPdf Example2.

Result is:

9

Everything is in place. Please find a code sample under IronPDFDemo.RenderUrlAsPdfDemo project. If you are wondering how the result would look without HttpLoginCredentials, here you are:

10

 

Data & News supplied by www.cloudquote.io
Stock quotes supplied by Barchart
Quotes delayed at least 20 minutes.
By accessing this page, you agree to the following
Privacy Policy and Terms and Conditions.