HTML to Image .NET Reference

class HtmlToImageClient

All setter methods return HtmlToImageClient object unless specified otherwise.

Constructor

public HtmlToImageClient(string userName, string apiKey)
Constructor for the Pdfcrowd API client.
userName
Your username at Pdfcrowd.
apiKey
Your API key.

Conversion Format

public HtmlToImageClient setOutputFormat(string outputFormat)
The format of the output file.
outputFormat
Allowed values:
  • png
  • jpg
  • gif
  • tiff
  • bmp
  • ico
  • ppm
  • pgm
  • pbm
  • pnm
  • psb
  • pct
  • ras
  • tga
  • sgi
  • sun
  • webp
Default: png

Conversion Input

public byte[] convertUrl(string url)
Convert a web page.
url
The address of the web page to convert.
The supported protocols are http:// and https://.
Returns
  • byte[] - Byte array containing the conversion output.
public void convertUrlToStream(string url, Stream outStream)
Convert a web page and write the result to an output stream.
url
The address of the web page to convert.
The supported protocols are http:// and https://.
outStream
The output stream that will contain the conversion output.
public void convertUrlToFile(string url, string filePath)
Convert a web page and write the result to a local file.
url
The address of the web page to convert.
The supported protocols are http:// and https://.
filePath
The output file path.
public byte[] convertFile(string file)
Convert a local file.
file
The path to a local file to convert.
The file can be either a single file or an archive (.tar.gz, .tar.bz2, or .zip).
If the HTML document refers to local external assets (images, style sheets, javascript), zip the document together with the assets.
The file must exist and not be empty.
The file name must have a valid extension.
Returns
  • byte[] - Byte array containing the conversion output.
public void convertFileToStream(string file, Stream outStream)
Convert a local file and write the result to an output stream.
file
The path to a local file to convert.
The file can be either a single file or an archive (.tar.gz, .tar.bz2, or .zip).
If the HTML document refers to local external assets (images, style sheets, javascript), zip the document together with the assets.
The file must exist and not be empty.
The file name must have a valid extension.
outStream
The output stream that will contain the conversion output.
public void convertFileToFile(string file, string filePath)
Convert a local file and write the result to a local file.
file
The path to a local file to convert.
The file can be either a single file or an archive (.tar.gz, .tar.bz2, or .zip).
If the HTML document refers to local external assets (images, style sheets, javascript), zip the document together with the assets.
The file must exist and not be empty.
The file name must have a valid extension.
filePath
The output file path.
public byte[] convertString(string text)
Convert a string.
text
The string content to convert.
Returns
  • byte[] - Byte array containing the conversion output.
public void convertStringToStream(string text, Stream outStream)
Convert a string and write the output to an output stream.
text
The string content to convert.
outStream
The output stream that will contain the conversion output.
public void convertStringToFile(string text, string filePath)
Convert a string and write the output to a file.
text
The string content to convert.
filePath
The output file path.
public byte[] convertStream(Stream inStream)
Convert the contents of an input stream.
inStream
The input stream with source data.
The stream can contain either HTML code or an archive (.zip, .tar.gz, .tar.bz2).
The archive can contain HTML code and its external assets (images, style sheets, javascript).
Returns
  • byte[] - Byte array containing the conversion output.
public void convertStreamToStream(Stream inStream, Stream outStream)
Convert the contents of an input stream and write the result to an output stream.
inStream
The input stream with source data.
The stream can contain either HTML code or an archive (.zip, .tar.gz, .tar.bz2).
The archive can contain HTML code and its external assets (images, style sheets, javascript).
outStream
The output stream that will contain the conversion output.
public void convertStreamToFile(Stream inStream, string filePath)
Convert the contents of an input stream and write the result to a local file.
inStream
The input stream with source data.
The stream can contain either HTML code or an archive (.zip, .tar.gz, .tar.bz2).
The archive can contain HTML code and its external assets (images, style sheets, javascript).
filePath
The output file path.
public HtmlToImageClient setZipMainFilename(string filename)
Set the file name of the main HTML document stored in the input archive. If not specified, the first HTML file in the archive is used for conversion. Use this method if the input archive contains multiple HTML documents.
filename
The file name.

Image Output

public HtmlToImageClient setScreenshotWidth(int width)
Set the output image width in pixels.
width
The value must be in the range 96-65000.
Default: 1024
Example:
  • Full HD width.
    setScreenshotWidth(1920)
public HtmlToImageClient setScreenshotHeight(int height)
Set the output image height in pixels. If it is not specified, actual document height is used.
height
Must be a positive integer number.
Example:
  • Full HD height.
    setScreenshotHeight(1080)
public HtmlToImageClient setScaleFactor(int factor)
Set the scaling factor (zoom) for the output image.
factor
The percentage value.
Must be a positive integer number.
Default: 100
Example:
  • setScaleFactor(50)
public HtmlToImageClient setBackgroundColor(string color)
The output image background color.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
color
The value must be in RRGGBB or RRGGBBAA hexadecimal format.
Examples:
  • red color
    setBackgroundColor("FF0000")
  • fully transparent background
    setBackgroundColor("00000000")
  • green color with 50% opacity
    setBackgroundColor("00ff0080")
  • green color
    setBackgroundColor("00ff00")

General Options

public HtmlToImageClient setUsePrintMedia(bool value)
Use the print version of the page if available (@media print).
value
Set to true to use the print version of the page.
Default: false
public HtmlToImageClient setNoBackground(bool value)
Do not print the background graphics.
value
Set to true to disable the background graphics.
Default: false
public HtmlToImageClient setDisableJavascript(bool value)
Do not execute JavaScript.
value
Set to true to disable JavaScript in web pages.
Default: false
public HtmlToImageClient setDisableImageLoading(bool value)
Do not load images.
value
Set to true to disable loading of images.
Default: false
public HtmlToImageClient setDisableRemoteFonts(bool value)
Disable loading fonts from remote sources.
value
Set to true disable loading remote fonts.
Default: false
public HtmlToImageClient setUseMobileUserAgent(bool value)
Use a mobile user agent.
Availability: API client >= 5.3.0, converter >= 20.10. See versioning.
value
Set to true to use a mobile user agent.
Default: false
public HtmlToImageClient setLoadIframes(string iframes)
Specifies how iframes are handled.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
iframes
Allowed values:
  • all
    All iframes are loaded.
  • same-origin
    Only iframes with the same origin as the main page are loaded.
  • none
    Iframe loading is disabled.
Default: all
public HtmlToImageClient setBlockAds(bool value)
Try to block ads. Enabling this option can produce smaller output and speed up the conversion.
value
Set to true to block ads in web pages.
Default: false
public HtmlToImageClient setDefaultEncoding(string encoding)
Set the default HTML content text encoding.
encoding
The text encoding of the HTML content.
Default: auto detect
Examples:
  • Set to use Latin-2 encoding.
    setDefaultEncoding("iso8859-2")
  • Set to use UTF-8 encoding.
    setDefaultEncoding("utf-8")
public HtmlToImageClient setLocale(string locale)
Set the locale for the conversion. This may affect the output format of dates, times and numbers.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
locale
The locale code according to ISO 639.
Default: en-US
Example:
  • Set to use Japanese locale.
    setLocale("ja-JP")
public HtmlToImageClient setHttpAuth(string userName, string password)
Set credentials to access HTTP base authentication protected websites.
userName
Set the HTTP authentication user name.
password
Set the HTTP authentication password.
public HtmlToImageClient setCookies(string cookies)
Set cookies that are sent in Pdfcrowd HTTP requests.
cookies
The cookie string.
Example:
  • setCookies("session=6d7184b3bf35;token=2710")
public HtmlToImageClient setVerifySslCertificates(bool value)
Do not allow insecure HTTPS connections.
value
Set to true to enable SSL certificate verification.
Default: false
public HtmlToImageClient setFailOnMainUrlError(bool failOnError)
Abort the conversion if the main URL HTTP status code is greater than or equal to 400.
failOnError
Set to true to abort the conversion.
Default: false
public HtmlToImageClient setFailOnAnyUrlError(bool failOnError)
Abort the conversion if any of the sub-request HTTP status code is greater than or equal to 400 or if some sub-requests are still pending. See details in a debug log.
failOnError
Set to true to abort the conversion.
Default: false
public HtmlToImageClient setNoXpdfcrowdHeader(bool value)
Do not send the X-Pdfcrowd HTTP header in Pdfcrowd HTTP requests.
value
Set to true to disable sending X-Pdfcrowd HTTP header.
Default: false
public HtmlToImageClient setCustomCss(string css)
Apply custom CSS to the input HTML document. It allows you to modify the visual appearance and layout of your HTML content dynamically. Tip: Using !important in custom CSS provides a way to prioritize and override conflicting styles.
Availability: API client >= 5.14.0, converter >= 20.10. See versioning.
css
A string containing valid CSS.
Examples:
  • Set the page background color to gray.
    setCustomCss("body { background-color: gray; }")
  • Do not show nav HTML elements and the element with ad-block ID in the output PDF.
    setCustomCss("nav, #ad-block { display: none !important; }")
public HtmlToImageClient setCustomJavascript(string javascript)
Run a custom JavaScript after the document is loaded and ready to print. The script is intended for post-load DOM manipulation (add/remove elements, update CSS, ...). In addition to the standard browser APIs, the custom JavaScript code can use helper functions from our JavaScript library.
javascript
A string containing a JavaScript code.
Example:
  • Set the page background color to gray.
    setCustomJavascript("document.body.style.setProperty('background-color', 'gray', 'important')")
public HtmlToImageClient setOnLoadJavascript(string javascript)
Run a custom JavaScript right after the document is loaded. The script is intended for early DOM manipulation (add/remove elements, update CSS, ...). In addition to the standard browser APIs, the custom JavaScript code can use helper functions from our JavaScript library.
javascript
A string containing a JavaScript code.
Example:
  • Set the page background color to gray.
    setOnLoadJavascript("document.body.style.setProperty('background-color', 'gray', 'important')")
public HtmlToImageClient setCustomHttpHeader(string header)
Set a custom HTTP header that is sent in Pdfcrowd HTTP requests.
header
A string containing the header name and value separated by a colon.
Example:
  • setCustomHttpHeader("X-My-Client-ID:k2017-12345")
public HtmlToImageClient setJavascriptDelay(int delay)
Wait the specified number of milliseconds to finish all JavaScript after the document is loaded. Your API license defines the maximum wait time by "Max Delay" parameter.
delay
The number of milliseconds to wait.
Must be a positive integer number or 0.
Default: 200
Example:
  • Wait for 2 seconds.
    setJavascriptDelay(2000)
public HtmlToImageClient setElementToConvert(string selectors)
Convert only the specified element from the main document and its children. The element is specified by one or more CSS selectors. If the element is not found, the conversion fails. If multiple elements are found, the first one is used.
selectors
One or more CSS selectors separated by commas.
Examples:
  • The first element with the id main-content is converted.
    setElementToConvert("#main-content")
  • The first element with the class name main-content is converted.
    setElementToConvert(".main-content")
  • The first element with the tag name table is converted.
    setElementToConvert("table")
  • The first element with the tag name table or with the id main-content is converted.
    setElementToConvert("table, #main-content")
  • The first element <p class="article"> within <div class="user-panel main"> is converted.
    setElementToConvert("div.user-panel.main p.article")
public HtmlToImageClient setElementToConvertMode(string mode)
Specify the DOM handling when only a part of the document is converted. This can affect the CSS rules used.
mode
Allowed values:
  • cut-out
    The element and its children are cut out of the document.
  • remove-siblings
    All element's siblings are removed.
  • hide-siblings
    All element's siblings are hidden.
Default: cut-out
public HtmlToImageClient setWaitForElement(string selectors)
Wait for the specified element in a source document. The element is specified by one or more CSS selectors. The element is searched for in the main document and all iframes. If the element is not found, the conversion fails. Your API license defines the maximum wait time by "Max Delay" parameter.
selectors
One or more CSS selectors separated by commas.
Examples:
  • Wait until an element with the id main-content is found.
    setWaitForElement("#main-content")
  • Wait until an element with the class name main-content is found.
    setWaitForElement(".main-content")
  • Wait until an element with the tag name table is found.
    setWaitForElement("table")
  • Wait until an element with the tag name table or with the id main-content is found.
    setWaitForElement("table, #main-content")
  • Wait until <p class="article"> is found within <div class="user-panel main">.
    setWaitForElement("div.user-panel.main p.article")
public HtmlToImageClient setAutoDetectElementToConvert(bool value)
The main HTML element for conversion is detected automatically.
Availability: API client >= 5.5.0, converter >= 20.10. See versioning.
value
Set to true to detect the main element.
Default: false
public HtmlToImageClient setReadabilityEnhancements(string enhancements)
The input HTML is automatically enhanced to improve the readability.
Availability: API client >= 5.5.0, converter >= 20.10. See versioning.
enhancements
Allowed values:
  • none
    No enhancements are used.
  • readability-v1
    Version 1 of the enhancements is used.
  • readability-v2
    Version 2 of the enhancements is used.
  • readability-v3
    Version 3 of the enhancements is used.
  • readability-v4
    Version 4 of the enhancements is used.
Default: none

Data

Methods related to HTML template rendering.

public HtmlToImageClient setDataString(string dataString)
Set the input data for template rendering. The data format can be JSON, XML, YAML or CSV.
dataString
The input data string.
Example:
  • JSON data.
    setDataString("{"recipient": "Anna May", "sender": "John Doe"}")
public HtmlToImageClient setDataFile(string dataFile)
Load the input data for template rendering from the specified file. The data format can be JSON, XML, YAML or CSV.
dataFile
The file path to a local file containing the input data.
Example:
  • setDataFile("/home/user/john/data.json")
public HtmlToImageClient setDataFormat(string dataFormat)
Specify the input data format.
dataFormat
The data format.
Allowed values:
  • auto
    the data format is auto detected
  • json
  • xml
  • yaml
  • csv
Default: auto
public HtmlToImageClient setDataEncoding(string encoding)
Set the encoding of the data file set by setDataFile.
encoding
The data file encoding.
Default: utf-8
Example:
  • Set to use Latin-2 encoding.
    setDataEncoding("iso8859-2")
public HtmlToImageClient setDataIgnoreUndefined(bool value)
Ignore undefined variables in the HTML template. The default mode is strict so any undefined variable causes the conversion to fail. You can use {% if variable is defined %} to check if the variable is defined.
value
Set to true to ignore undefined variables.
Default: false
public HtmlToImageClient setDataAutoEscape(bool value)
Auto escape HTML symbols in the input data before placing them into the output.
value
Set to true to turn auto escaping on.
Default: false
public HtmlToImageClient setDataTrimBlocks(bool value)
Auto trim whitespace around each template command block.
value
Set to true to turn auto trimming on.
Default: false
public HtmlToImageClient setDataOptions(string options)
Set the advanced data options:
  • csv_delimiter - The CSV data delimiter, the default is ,.
  • xml_remove_root - Remove the root XML element from the input data.
  • data_root - The name of the root element inserted into the input data without a root node (e.g. CSV), the default is data.
options
Comma separated list of options.
Examples:
  • Use semicolon to separate CSV data.
    setDataOptions("csv_delimiter=;")
  • Name the root of data rows and use the name in the template loop {% for row in rows %}...{% endfor %}.
    setDataOptions("data_root=rows")
  • Remove XML root so it the HTML template can be more simple.
    setDataOptions("xml_remove_root=1")

Miscellaneous

public HtmlToImageClient setDebugLog(bool value)
Turn on the debug logging. Details about the conversion are stored in the debug log. The URL of the log can be obtained from the getDebugLogUrl method or available in conversion statistics.
value
Set to true to enable the debug logging.
Default: false
public string getDebugLogUrl()
Get the URL of the debug log for the last conversion.
Returns
  • string - The link to the debug log.
public int getRemainingCreditCount()
Get the number of conversion credits available in your account.
This method can only be called after a call to one of the convertXtoY methods.
The returned value can differ from the actual count if you run parallel conversions.
The special value 999999 is returned if the information is not available.
Returns
  • int - The number of credits.
public int getConsumedCreditCount()
Get the number of credits consumed by the last conversion.
Returns
  • int - The number of credits.
public string getJobId()
Get the job id.
Returns
  • string - The unique job identifier.
public int getOutputSize()
Get the size of the output in bytes.
Returns
  • int - The count of bytes.
public string getVersion()
Get the version details.
Returns
  • string - API version, converter version, and client version.
public HtmlToImageClient setTag(string tag)
Tag the conversion with a custom value. The tag is used in conversion statistics. A value longer than 32 characters is cut off.
tag
A string with the custom tag.
Example:
  • setTag("client-1234")
public HtmlToImageClient setHttpProxy(string proxy)
A proxy server used by Pdfcrowd conversion process for accessing the source URLs with HTTP scheme. It can help to circumvent regional restrictions or provide limited access to your intranet.
proxy
The value must have format DOMAIN_OR_IP_ADDRESS:PORT.
Examples:
  • setHttpProxy("myproxy.com:8080")
  • setHttpProxy("113.25.84.10:33333")
public HtmlToImageClient setHttpsProxy(string proxy)
A proxy server used by Pdfcrowd conversion process for accessing the source URLs with HTTPS scheme. It can help to circumvent regional restrictions or provide limited access to your intranet.
proxy
The value must have format DOMAIN_OR_IP_ADDRESS:PORT.
Examples:
  • setHttpsProxy("myproxy.com:443")
  • setHttpsProxy("113.25.84.10:44333")
public HtmlToImageClient setClientCertificate(string certificate)
A client certificate to authenticate Pdfcrowd converter on your web server. The certificate is used for two-way SSL/TLS authentication and adds extra security.
certificate
The file must be in PKCS12 format.
The file must exist and not be empty.
Example:
  • setClientCertificate("/home/user/john/pdfcrowd.crt")
public HtmlToImageClient setClientCertificatePassword(string password)
A password for PKCS12 file with a client certificate if it is needed.
password
Example:
  • setClientCertificatePassword("123456")

Tweaks

Expert options for fine-tuning output.

public HtmlToImageClient setMaxLoadingTime(int maxTime)
Set the maximum time to load the page and its resources. After this time, all requests will be considered successful. This can be useful to ensure that the conversion does not timeout. Use this method if there is no other way to fix page loading.
Availability: API client >= 5.15.0, converter >= 20.10. See versioning.
maxTime
The number of seconds to wait.
The value must be in the range 10-30.

API Client Options

public HtmlToImageClient setConverterVersion(string version)
Set the converter version. Different versions may produce different output. Choose which one provides the best output for your case.
Availability: API client >= 5.0.0. See versioning.
version
The version identifier.
Allowed values:
  • latest
    The latest converter version.
  • 20.10
    Version 20.10.
  • 18.10
    Version 18.10.
Default: 20.10
public HtmlToImageClient setUseHttp(bool value)
Specifies if the client communicates over HTTP or HTTPS with Pdfcrowd API.
value
Set to true to use HTTP.
Default: false

Warning

Using HTTP is insecure as data sent over HTTP is not encrypted. Enable this option only if you know what you are doing.

public HtmlToImageClient setUserAgent(string agent)
Set a custom user agent HTTP header. It can be useful if you are behind a proxy or a firewall.
agent
The user agent string.
Default: pdfcrowd_dotnet_client/5.18.1 (https://pdfcrowd.com)
public HtmlToImageClient setProxy(string host, int port, string userName, string password)
Specifies an HTTP proxy that the API client library will use to connect to the internet.
host
The proxy hostname.
port
The proxy port.
userName
The username.
password
The password.
public HtmlToImageClient setRetryCount(int count)
Specifies the number of automatic retries when the 502 or 503 HTTP status code is received. The status code indicates a temporary network issue. This feature can be disabled by setting to 0.
count
Number of retries.
Default: 1
Example:
  • setRetryCount(3)