Skip to main content

Using CSS Stylesheet when processing HTML

· 3 min read
James A. Brannan

One question we get asked here at DynamicPDF is how to use a CSS stylesheet when using the html input with the pdf endpoint to convert HTML to PDF. Here is a simple way to accomplish this task.

Using the html input type with the pdf endpoint is straightforward.

You can also use HTML with a linked CSS stylesheet if the stylesheet is publicly available via HTTP. For example, the following instructions JSON specifies a simple HTML string that references an external stylesheet using the basePath JSON element.

"inputs": [
"type": "html",
"basePath": "",
"htmlString": "<html><head><link rel="stylesheet" href="./mystyle.css"></head><body><p>Test</p></body></html>"

Although an embedded CSS stylesheet must be accessible via HTTP - like in the previous example - an easy workaround for a CSS only available locally is to replace the <link> tag content with the stylesheet's content. The following example illustrates.

tempHtml = File.ReadAllText(basePath + "example.html");
tempCss = File.ReadAllText(basePath + "example.css");

StringBuilder sb = new StringBuilder();
sb.Append(tempHtml.Substring(0, tempHtml.IndexOf("<link")));
sb.Append("<style>" + tempCss + "</style>");

tempHtml = tempHtml.Substring(tempHtml.IndexOf("<link"));
sb.Append(tempHtml.Substring(tempHtml.IndexOf("/>") + 2));

HtmlResource resource = new HtmlResource(sb.ToString());
pdf.AddHtml(resource, null, PageSize.Letter, PageOrientation.Portrait, 1F);
Source: PdfHtmlCssWorkAroundExample

Use simple string manipulation to replace/insert the relative link to the local CSS with the CSS file's content.