32

I am looking to use HtmlRenderer to convert an HTML file to a PDF file. I have seen it being mentioned on several sites that it is possible. However, I don't seem to be able to find any basic sample code to do this.

I have added the following NuGet package.

Install-Package HtmlRenderer.PdfSharp

That's about as far I have got. Any help will be greatly appreciated.

slayernoah
  • 4,382
  • 11
  • 42
  • 73
  • 4
    How is this a duplicate of the http://stackoverflow.com/questions/40429220? That question is for Aspose and this is for PDFSharp – slayernoah Nov 04 '16 at 21:03
  • Thanks for asking this question. I looked at the PdfSharp documentation and couldn't see how to convert from Html. Unfortunately, the quality of the PDF produced wasn't great. – Savage Apr 07 '17 at 08:45
  • 1
    To be very clear, this is a community library, not one directly associated with the developers who made PdfSharp. You won't find docs for it on the PdfSharp website. – Lucas Leblanc Dec 12 '18 at 22:45
  • 1
    How is this too broad? I have a HTML file. I want to convert it to a PDF file using PDFSharp. This is very specific. – slayernoah Mar 13 '19 at 21:59

1 Answers1

43

Found a solution:

using TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator;

string html = File.ReadAllText("input.htm");
PdfDocument pdf = PdfGenerator.GeneratePdf(html, PageSize.Letter);
pdf.Save("document.pdf");
Piotr Kula
  • 9,597
  • 8
  • 59
  • 85
slayernoah
  • 4,382
  • 11
  • 42
  • 73
  • 1
    Doesn't work on headless mono servers due to lack of x11 server – marknuzz Jul 29 '17 at 00:27
  • 7
    To clarify, `PdfSharp.Pdf.PdfDocument pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf` – Mmm Jun 29 '18 at 21:58
  • 2
    As per the question package "HtmlRenderer.PdfSharp" which depends on "PdfSharp" needs to be installed, the Htmlrenderer package does in fact have a pdf generator. – War Aug 10 '18 at 10:42
  • @slayernoah can you help me in css data property of this function – vibs2006 Jan 07 '20 at 08:38
  • 1
    This package is not compatible with .net core. – Ali Rasouli Sep 12 '20 at 13:28
  • 3
    I tried this on some fairly basic HTML that contained some tables and it created a PDF with errors in it, with most of the pages being blank. – Phil Rogers Jan 11 '21 at 09:17
  • @AliRasouli ‘Polybioz.HtmlRenderer.PdfSharp.Core’ is compatible with .net core. Have tested in 6.0. – clamchoda Dec 05 '22 at 05:05