Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 249
Arti Avatar asked Jul 07 '15 07:07

Arti


1 Answers

You can include your 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 stylesheet and it will be work!

like image 59
Andrey Burykin Avatar answered Sep 22 '22 08:09

Andrey Burykin