Home » c# » c# – How to add reference to external stylesheet using iText and htmltopdf

c# – How to add reference to external stylesheet using iText and htmltopdf

Posted by: admin February 21, 2020 Leave a comment


I have a console app that generates a PDF from HTML. HTML looks like this:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head>
    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="html\somestyle.css" /> </head>

If I include the styles directly in the HTML, using <style> tag, then they show up in the PDF. But I need to use external stylesheet.

The folder structure is like this:

***Task_ABC (folder)
******HTML (folder)

The console app is scheduled via Windows Task Scheduler.

If I run the app from command prompt manually, the html\\sometyle.css syntax works and styles show up in PDF.

But when Task Scheduler runs it, styles don’t show up in PDF.

I have tried somestyle.css as well as html/somestyle.css syntax and they don’t work.

How to&Answers:

If you pass the HTML as a file stream to HtmlConverter instead of passing it as a file then the resources will be resolved against the current working directory. This may be the cause of the problem in processing your file in another environnment.

You can set the baseUri, i.e. the uri which all the resources in HTML will be resolved against in ConverterProperties:

HtmlConverter.convertToPdf(fileInputStream, fileOutputStream, new ConverterProperties().setBaseUri(baseUri));

The baseUri should point to the directory containing your html directory. You can also freely use html/somestyle.css link syntax, not necessary to use Windows-style path.