Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS styles not being applied to PDF with iTextSharp

I am attempting to convert a portion of my webpage to pdf using iTextSharp, and while the pdf generation is working correctly, none of the css styles are being applied. I've tried applying the styles one at a time, but that doesn't seem to work. This is what I've come up with so far:

//Get the portion of the page to convert.
StringBuilder sb = new StringBuilder();
print_div.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
string html = sb.ToString();

//Generate a random filename to use for the pdf
Guid random_guid;
random_guid = Guid.NewGuid();
string fileName = random_guid.ToString() + ".pdf";
string filename_with_folder = @"pdf\sl_" + fileName;
string fullFilePath = System.IO.Path.Combine(Request.PhysicalApplicationPath, filename_with_folder);

using (Document doc = new Document())
{
    // Create the pdf
    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
    doc.Open();
    try
    {
        //Set the font size for all elements
        StyleSheet styles = new StyleSheet();
        styles.LoadStyle("body", "fontsize", "8px");

        //Write the content to the pdf document
        StringReader sr = new StringReader(html);
        XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, sr);
    }
    catch (Exception ex)
    {
    }
    doc.Close();
}

Am I missing something? I started off using HTMLWorker and have switched to XMLWorker, but I think I'm just confusing myself now. Help would be appreciated.

ATTEMP #2

Thanks for the reply! This is what I've come up with, but it isn't working. My content doesn't appear in the pdf at all now, and I'm not sure why. Any thoughts?

using (Document doc = new Document())
{
    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
    doc.Open();

    // CSS
    var cssResolver = new StyleAttrCSSResolver();
    var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("~/css/print.css"), FileMode.Open));
    cssResolver.AddCss(cssFile);

    // HTML
    CssAppliers ca = new CssAppliersImpl();
    HtmlPipelineContext hpc = new HtmlPipelineContext(ca);
    hpc.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

    // PIPELINES
    PdfWriterPipeline pdf = new PdfWriterPipeline(doc, writer);
    HtmlPipeline htmlPipe = new HtmlPipeline(hpc, pdf);
    CssResolverPipeline css = new CssResolverPipeline(cssResolver, htmlPipe);

    XMLWorker worker = new XMLWorker(css, true);
    XMLParser p = new XMLParser(worker);
    StringReader sr = new StringReader(html);
    p.Parse(sr);
    doc.Close();
}

Am I close, or am I missing the point completely?

like image 833
Broodmdh Avatar asked Aug 08 '13 17:08

Broodmdh


1 Answers

In order to use stylesheets to create a PDF file with XmlWorker you can try this example code that returns a byte array.



        byte[] bytesArray = null;
        using (var ms = new MemoryStream())
        {
            using (var document = new Document())
            {
                using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
                {
                    document.Open();
                    using (var strReader = new StringReader(html))
                    {
                        //Set factories
                        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                        htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                        //Set css
                        ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                        cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath("~/Content/bootstrap.min.css"), true);
                        //Export
                        IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
                        var worker = new XMLWorker(pipeline, true);
                        var xmlParse = new XMLParser(true, worker);
                        xmlParse.Parse(strReader);
                        xmlParse.Flush();
                    }
                    document.Close();
                }
            }
            bytesArray = ms.ToArray();
        }
        return bytesArray;
like image 55
Agus Rdz Avatar answered Nov 15 '22 00:11

Agus Rdz