Create PDF from HTML using TheArtOfDev.HtmlRenderer.PdfSharp

31.8k Views Asked by At

I need to convert a well-formatted HTML string to a PDF document.

I found this DLL that should do what I need, but it isn't working fine on formatting.

That's the HTML code I'm trying to convert, and viewing it on browser works fine (I've used Bootstrap CSS, that's been correctly referenced as cdn).

enter image description here

But once converted to PDF this is the result: enter image description here

And that's the code I'm using to convert it:

        string html = "";

        if (File.Exists(pathIN))
        {
            html = File.ReadAllText(pathIN);
        }

        PdfDocument pdfDocument = new PdfDocument();
        PdfDocument pdf = PdfGenerator.GeneratePdf(html, PageSize.A4, 60);
        pdf.Save(pathOUT);

Does anyone have any suggestion?

4

There are 4 best solutions below

1
On BEST ANSWER

Try using https://wkhtmltopdf.org, works well for bootstrap pages.

0
On

To avoid useless effort to other people, it doesn't work for Bootstrap like the Table even using display: inline-block to define the width. Right side of table is always trimmed, the size unfitting the letter size in my case.

pls see the snapshot in browser and after rendered to pdf for for the Table

0
On

I know its a little late but this can help someone The problem with bootstrap is that to align the columns use float: left and pdfsharp cannot read this property instead use display: inline-block and define the width in pixels.

0
On

I also had issues with this when using HtmlRenderer/PdfSharp with Bootstrap controlling the layout.

Although it goes against the grain, I resorted to using tables for the layout. Given that the destination (pdf) was a obviously a fixed width, being responsive was not a requirement.