Hariharan S
Hariharan S

Reputation: 29

CSS does not apply while converting HTML to PDF using iTextSharp XMLWorker

I am currently working on a POC to demonstrate conversion of HTML to PDF using iTextSharp XMLWorker class.

  1. The CSS file is linked to HTML file using link tag.
  2. The path of CSS file is a file server path. Its the same directory as the HTML file.

I use the below function to perform the operation. The PDF file gets generated but the CSS file is not applied.

public void Html2Pdf(FileStream inputHtml, Document doc, PdfWriter pdfWriter)
{
   var cssFiles = new CssFilesImpl();
   cssFiles.Add(XMLWorkerHelper.GetCSS(new FileStream(@"C:\Test_HTML2PDF\Test.css",FileMode.Open)));
   var cssResolver = new StyleAttrCSSResolver(cssFiles);

   var htmlContext = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
   htmlContext.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory());

   htmlContext.SetPageSize(new Rectangle(doc.Left, doc.Bottom, doc.Right, doc.Top));

   // Pipelines

   var pdf = new PdfWriterPipeline(doc, pdfWriter);
        var html = new HtmlPipeline(htmlContext, pdf);
        var css = new CssResolverPipeline(cssResolver, html);

   var worker = new XMLWorker(css, true);
   var parser = new XMLParser(worker, Encoding.UTF8);
   parser.Parse(inputHtml, Encoding.UTF8);     
}

Kindly share your inputs / observations on what i have missed and what could be done address this issue.

Upvotes: 2

Views: 6719

Answers (1)

Arman H
Arman H

Reputation: 5618

HTML-to-PDF converters are notoriously bad with finding relative paths to assets. Try linking your stylesheet using an absolute URL instead, e.g.:

<link href='http://localhost/css/style.css'>

Upvotes: 1

Related Questions