HTML Converter Base Tags

You are not limited to converting HTML from a URL, a local directory, or an HTML string. You can also combine all three if you convert using base tags.

If combining local HTML resources with web resources (i.e. URL) you must use a base tag.

The Converter.Convert method is overloaded to allow specifying a base URL.

public static void Convert(string inputHtml, string
  outputPath, [Uri basePath = null], [ConversionOptions
  conversionOptions = null])
    
public static Byte[] Convert(string inputHtml, [Uri 
  basePath = null], [ConversionOptions 
  conversionOptions = null])

The Converter.ConvertAsync method is also overloaded to allow specifying a base URL.

public static Task<bool> ConvertAsync(string inputHtml,
  string outputPath, [Uri basePath = null],
  [ConversionOptions conversionOptions = null])
    
public static Task<Byte[]> ConvertAsync(string inputHtml,
  [Uri basePath = null], [ConversionOptions
  conversionOptions = null])

The overloaded Converter functions that take a URL as input do not allow specifying a base path. A workaround is to first load the HTML file as a string or specify the base path in the HTML's header (see below).

Image from URL and HTML

In this example the HTML is a string with a relative path to an image. The images resides on an external website.

public static void ImageRun()
{
	Uri baseUrl = new Uri("https://www.dynamicpdf.com/");
    string html = "<body><p>This is local HTML string.</p>"
        + "<img src=\"./images/logo.png\"></body>";
	Converter.Convert(html, outputPath), baseUrl);
}

Image From URL and Local File

Recall that when converting using a URI, there is no option for specifying a base path in the Convert method. The following two examples illustrate first reading the file as a string and using the string as the method's input. The second example illustrates using the HTML base tag.

Reading File Content

The following example illustrates reading an HTML file into a string and using it with a base path. Note that the HTML does not specify a basepath.

<html>
<body>
    <p>This is local HTML string.</p>
    <img src="./images/logo.png">
</body>
</html>
public static void ImageFileHtmlRun()
{
    Uri baseUrl = new Uri("https://www.dynamicpdf.com/");
    string html = File.ReadAllText("simple.html");
    Converter.Convert(html, outputPath, baseUrl);
}

Using base HTML Tag

Another option for resolving relative paths is to specify the base reference in the HTML file's header. The following example illustrates.

<html>
<head>
    <base href="https://www.dynamicpdf.com/" target="_blank">
</head>
<body>
    <p>This is local HTML string.</p>
    <img src="./images/logo.png">
</body>
</html>
public static void FromFile()
{
    Uri uri = new Uri(new Uri("file://"), "simple2.html"));
    Converter.Convert(uri,outputPath);
}

See HTML Converter Local Resources for more examples using a base path.