Arti
Arti

Reputation: 3071

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

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.

Upvotes: 9

Views: 20650

Answers (1)

Andrey Burykin
Andrey Burykin

Reputation: 728

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!

Upvotes: 4

Related Questions