Skip to main content

CSS and JavaScript

Version: 3.0

CSS and JavaScript

DynamicPDF HTML Converter supports embedded and external CSS and JavaScript. Use CSS and JavaScript within HTML as you would any other web page.

Embedding CSS and JavaScript​

The following example illustrates embedding CSS and JavaScript in an HTML string. DynamicPDF HTML Converter seamlessly handles both HTML strings.

static string samplePageWithCss = "<!DOCTYPE html><html><head ><style>"
+ "body {background-color: lightblue;}"
+ "h1 {color: white; text-align: center;} p "
+ "{font-family: verdana;font - size: 20px;}</style>"
+ "</head><body><h1>My First CSS Example</h1>"
+ "<p>This is a paragraph.</p></body></html>";

static string samplePageWithJavaScript = "<!DOCTYPE html><html><body>"
+ "<h2>My First Web Page</h2>"
+ "<p>My First Paragraph.</p><p id=\"demo\"></p>"
+ "<script>document.getElementById(\"demo\")"
+ ".innerHTML = 5 + 6;</script></body></html>";

public static void Run()
{
Converter.Convert(samplePageWithCss, Util.GetPath("Output/cssExample.pdf"));
Converter.Convert(samplePageWithJavaScript, Util.GetPath("Output/jscriptExample.pdf"));
}
Private Shared samplePageWithCss As String = "<!DOCTYPE html><html><head ><style>" _
& "body {background-color: lightblue;}" _
& "h1 {color: white; text-align: center;} p " _
& "{font-family: verdana;font-size: 20px;}</style>" _
& "</head><body><h1>My First CSS Example</h1>" _
& "<p>This is a paragraph.</p></body></html>"

Private Shared samplePageWithJavaScript As String = "<!DOCTYPE html><html><body>" _
& "<h2>My First Web Page</h2>" _
& "<p>My First Paragraph.</p><p id=""demo""></p>" _
& "<script>document.getElementById(""demo"")" _
& ".innerHTML = 5 + 6;</script></body></html>"

Public Shared Sub Run()
Converter.Convert(samplePageWithCss, Util.GetPath("Output/cssExample.pdf"))
Converter.Convert(samplePageWithJavaScript, Util.GetPath("Output/jscriptExample.pdf"))
End Sub

[JavaScriptConversion.cs](https://github.com/DynamicPDF/html-converter-dotnet-core/blob/master/html-converter-dotnet-core-cs/JavaScriptConversion.cs){#gitlink-id target=_blank}


[JavaScriptCssConversion.vb](https://github.com/DynamicPDF/html-converter-dotnet-core/blob/master/html-converter-dotnet-core-vb/JavaScriptCssConversion.vb){#gitlink-id target=_blank}

External CSS and JavaScript Files​

DynamicPDF HTML Converter also supports HTML using external files. For example, suppose you have the following HTML file on your local system.

<!DOCTYPE html><html><head>
<link rel="stylesheet" href="../styles.css"/>
</head><body><h1>My First CSS Example</h1>
<p>This is a paragraph.</p></body></html>

DynamicPDF HTML Converter resolves the CSS and applies it to the HTML document's styling before converting into a PDF.

info

HTML strings with a relative path to a CSS/JavaScript path must use a base path to resolve and apply the file's formatting. See the HTML Converter Base Tags topic for more details.