Warm tip: This article is reproduced from stackoverflow.com, please click
c# css itext itext7 pdf-generation

How to add reference to external stylesheet using iText and htmltopdf

发布于 2020-05-06 11:56:45

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)
******Task.exe
******HTML (folder)
*********template.html
*********somestyle.css

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.

Questioner
joym8
Viewed
41
Alexey Subach 2020-02-21 04:38

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.