8

I would like to know if there is any way by which I can

Create PDF from HTML snippet using PdfSharp having external CSS classes included in the HTML.

I have found a way to generate a pdf file using HTML content but my css classes are not getting applied to the PDF.

Here is how I am doing it for simple html string:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.Drawing;
using TheArtOfDev.HtmlRenderer.PdfSharp;
using PdfSharp;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        PdfDocument pdf = PdfGenerator.GeneratePdf("<h1>tests</h1><p>test para</p>", PageSize.A4,20,null,null,null);
        pdf.Save(@"C\testPDF.pdf");

    }
}

ANd this is how it is generated: enter image description here

But what I want is to include HTML string like this:

<h1>tests</h1><p class='para1'>test para</p>

Is there any way to achieve this? Using different library is not an issue only thing is that the used library should be an open source.

Arti
  • 2,993
  • 11
  • 68
  • 121

1 Answers1

4

You can include intended style into head section and it will be rendered right:

    var testHtml = @"<head>
        <style>
            .test {
                background-color: linen;
                color: maroon;
            }
        </style>
    </head>
    <body class=""test"">
        <p>
            <h1>Hello World</h1>
            This is html rendered text with css and image.
        </p>
        <p>
            <img src=""http://fc62.deviantart.com/fs11/i/2006/236/d/e/The_Planet_Express_Ship_by_gasclown.jpg"" height=""100"" width=""100"">
        </p>
    </body>";

More over - you can just add url to a stylesheet and it works well!

Andrey Burykin
  • 700
  • 11
  • 23
  • 2
    I have a problem with this. When I delete css from the head, the pdf is being printed, but with the styles, the pdf looks like a white page :/ – DiSaSteR Jul 19 '17 at 10:57
  • @DiSaSteR If I understand right you want to show pdf with style but print it without style? In this case after css deleted you need to rebuild pdf and then print. May be you can share simple example with issue then I will help you. – Andrey Burykin Jul 19 '17 at 13:02