2

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.

1 Answer 1

1

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'>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.