ChromiumHtmlToPdf

repository·master·Indexed 19 days ago

https://github.com/sicos1977/chromiumhtmltopdf

A cross-platform C# .NETStandard 2.0 library and .NET 8 console application for converting HTML content from files or URLs into PDF documents using Chromium-based browsers such as Google Chrome or Microsoft Edge. It supports asynchronous operations from version 4.0 onwards and provides a modern alternative to wkHtmlToPdf with improved HTML5 compatibility.

Tokens
13.1K
Snippets
9
Records
10
Agent score
17%

What's inside ChromiumHtmlToPdf

  1. Overview of ChromiumHtmlToPdf

    master

    ChromiumHtmlToPdf is a 100% managed C# .NETStandard 2.0 library and .NET 8 console application designed to convert HTML to PDF format. It achieves this by utilizing Google Chromium (specifically Google Chrome or Microsoft Edge).

    Key characteristics:

    • Cross-platform: Works on Windows, Linux, and macOS.
    • Async Support: From version 4.0 onwards, the library is fully asynchronous, though synchronous usage is still supported.
    • Modern HTML Support: Designed as a modern replacement for wkHtmlToPdf, offering better compatibility with HTML5.
  2. Manage Chromium Cache Directories for Multiple Instances

    master

    You cannot share a single cache directory between multiple Google Chrome or Microsoft Edge instances because the first instance will lock it.

    To run multiple instances efficiently, you should create a unique cache directory for each instance. A common pattern is to use a ConcurrentStack of unique instance IDs to pop a new ID for each running instance and push it back once the instance shuts down.

    public static class InstanceId
    {
        #region Fields
        private static readonly ConcurrentStack<string> ConcurrentStack;
        #endregion
    
        static InstanceId()
        {
            ConcurrentStack = new ConcurrentStack<string>();
    
            for(var i = 100000; i > 0; i--)
                ConcurrentStack.Push(i.ToString().PadLeft(6, '0'));
        }
    
        public static string Pop()
        {
            if (ConcurrentStack.TryPop(out var instanceId))
                return instanceId;
    
            throw new Exception("Instance id stack is empty");
        }
    
        public static void Push(string instanceId)
        {
            ConcurrentStack.Push(instanceId);
        }
    }
  3. Install ChromiumHtmlToPdf via NuGet

    master

    The easiest way to install the library is via NuGet. Note that the NuGet package is named ChromeHtmlToPdf due to naming availability.

    In Visual Studio's Package Manager Console, run:

    Install-Package ChromeHtmlToPdf
    Install-Package ChromeHtmlToPdf
  4. Configure Chromium arguments for Linux or Docker

    master

    The library automatically detects the operating system and sets the --no-sandbox flag on Linux by default. If you encounter conversion errors on Linux or in environments where the sandbox is restricted, you can manually ensure this flag is set using AddChromiumArgument.

    Additionally, when running in Docker containers on platforms like Google App Engine Flexible Environment or Heroku, the /dev/shm partition size is often too small (e.g., 64MB or 5MB), which can cause Chrome to crash. To prevent this, use the --disable-dev-shm-usage flag to instruct Chrome to use /tmp instead of /dev/shm.

    // Use if you encounter sandbox-related errors on Linux
    converter.AddChromiumArgument("--no-sandbox");
    
    // Use if Chrome crashes in Docker/Cloud environments due to small /dev/shm size
    converter.AddChromiumArgument("--disable-dev-shm-usage");
  5. Setup ChromiumHtmlToPdf in a Docker Container

    master

    To run this in a Docker container (e.g., Ubuntu-based), you need to install dependencies, Google Chrome Stable, and potentially a ChromeDriver.

    Note: The following example includes steps to install Chrome and clean up unnecessary packages to keep the image size down.

    # Suppress an apt-key warning about standard out not being a terminal. Use in this script is safe.
    ENV APT_KEY_DONT_WARN_ON_DANGEROUS_USAGE=DontWarn
    
    # export DEBIAN_FRONTEND="noninteractive"
    ENV DEBIAN_FRONTEND noninteractive
    
    # Install deps + add Chrome Stable + purge all the things
    RUN apt-get update && apt-get install -y \
    	apt-transport-https \
    	ca-certificates \
    	curl \
    	gnupg \
    	--no-install-recommends \
    	&& curl -sSL https://dl.google.com/linux/linux_signing_key.pub | apt-key add - \
    	&& echo "deb [arch=amd64] https://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list \
    	&& apt-get update && apt-get install -y \
    	google-chrome-stable \
    	--no-install-recommends \
    	&& apt-get purge --auto-remove -y curl gnupg \
    	&& rm -rf /var/lib/apt/lists/*
    
    # Chrome Driver
    RUN apt-get update && \
        apt-get install -y unzip && \
        wget https://chromedriver.storage.googleapis.com/2.31/chromedriver_linux64.zip && \
        unzip chromedriver_linux64.zip && \
        mv chromedriver /usr/bin && rm -f chromedriver_linux64.zip
  6. Convert a URL or file to PDF from C# code

    master

    You can use the Converter class to perform conversions. It supports both synchronous and asynchronous methods. You should pass a PageSettings object to control the output.

    Synchronous usage:

    var pageSettings = new PageSettings()
    using (var converter = new Converter())
    {
        converter.ConvertToPdf(new Uri("http://www.google.nl"), @"c:\google.pdf", pageSettings);
    }

    Asynchronous usage:

    var pageSettings = new PageSettings()
    using var converter = new Converter();
    await converter.ConvertToPdfAsync(new Uri("http://www.google.nl"), @"c:\google.pdf", pageSettings);
    var pageSettings = new PageSettings()
    using (var converter = new Converter())
    {
        converter.ConvertToPdf(new Uri("http://www.google.nl"), @"c:\google.pdf", pageSettings);
    }
  7. Enable Chromium debug logging

    master

    If Chromium exits unexpectedly without a meaningful error, you can enable debug logging by setting the EnableChromiumLogging property to true.

    • The output is saved to chrome_debug.log in the Chrome user data directory.
    • Logs are overwritten each time Chrome restarts.
    • Custom Log Location: If the environment variable CHROME_LOG_FILE is set, Chrome will write the debug log to that specific location instead of the default.
    public bool EnableChromiumLogging { get; set; }
  8. Configure Logging with ILogger

    master

    Since version 2.5.0, ChromiumHtmlToPdfLib uses the Microsoft ILogger interface. You can use any logging library that implements this interface.

    ChromiumHtmlToPdfLib also provides built-in loggers in the ChromiumHtmlToPdfLib.Logger namespace. For example, you can log to a stream or the console.

    var logger = !string.IsNullOrWhiteSpace(<some logfile>)
                    ? new ChromiumHtmlToPdfLib.Loggers.Stream(File.OpenWrite(<some logfile>))
                    : new ChromiumHtmlToPdfLib.Loggers.Console();
  9. Reference: Command Line Options

    master

    The following options are available for the ChromiumHtmlToPdf console application:

    | **Option**                       | **Description**                                                                                                                                                                                                                                                               |
    |----------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
    | `--input`                        | Required. The input content, URL, or file.                                                                                                                                                                                                                                     |
    | `--input-is-list`                 | Indicates `--input` is a list of URLs/files. Use `--output` for the location of converted files. Use `|` to specify an output file (e.g., `inputfile.html|myoutputfile.pdf`). Defaults to input file name if no output file is provided.             |
    | `--output`                       | Required. The output file.                                                                                                                                                                                                                                    |
    | `--browser`                      | Required. Specifies the browser to use (default: Chrome or Edge).                                                                                                                                                                                                         |
    | `--landscape`                      | (Default: false) Sets paper orientation to landscape.                                                                                                                                                                                                                       |
    | `--display-headerfooter`         | (Default: false) Displays header and footer.                                                                                                                                                                                                                  |
    | `--header-template`              | Specifies a custom HTML template for the header. Overrides all other --header-* options.                                                                                                                                                                                    |
    | `--footer-template`              | Specifies a custom HTML template for the footer. Overrides all other --footer-* options.                                                                                                                                                                                    |
    | `--header-left`                  | Text to print in the left corner of the header.                                                                                                                                                                                                              |
    | `--header-center`                | Text to print in the center of the header.                                                                                                                                                                                                                  |
    | `--header-right`                 | Text to print in the right corner of the header.                                                                                                                                                                                                            |
    | `--header-font-name`             | The font name to use for the header.                                                                                                                                                                                                                        |
    | `--header-font-size`            | The font size (in pt) to use for the header.                                                                                                                                                                                                                |
    | `--footer-left`                  | Text to print in the left corner of the footer.                                                                                                                                                                                                              |
    | `--footer-center`                | Text to print in the center of the footer.                                                                                                                                                                                                                  |
    | `--footer-right`                 | Text to print in the right corner of the footer.                                                                                                                                                                                                            |
    | `--footer-font-name`             | The font name to use for the footer.                                                                                                                                                                                                                        |
    | `--footer-font-size`            | The font size (in pt) to use for the footer.                                                                                                                                                                                                                |
    | `--print-background`             | (Default: false) Prints background graphics.                                                                                                                                                                                                                 |
    | `--scale`                        | (Default: 1) Specifies the webpage rendering scale.                                                                                                                                                                                                                          |
    | `--paper-format`                 | (Default: Letter) Specifies paper format, overriding `--paper-width` and `--paper-height`. Valid values: Letter, Legal, Tabloid, Ledger, A0-A6, FitPageToContent.                                                                                                 |
    | `--paper-width`                  | (Default: 8.5) Sets paper width in inches.                                                                                                                                                                                                                  |
    | `--paper-height`                 | (Default: 11) Sets paper height in inches.                                                                                                                                                                                                                 |
    | `--no-margins`                   | Removes margins by enabling Chromium's `--no-margins` parameter.                                                                                                                                                                                                           |
    | `--window-size`                  | (Default: HD_1366_768) Specifies window size, overriding `--window-width` and `--window-height`. Valid values: SVGA, WSVGA, XGA, WXGA, FHD, 4K_UHD, etc.                                                                                                   |
    | `--window-width`                 | (Default: 1366) Specifies window width in pixels.                                                                                                                                                                                                           |
    | `--window-height`                | (Default: 768) Specifies window height in pixels.                                                                                                                                                                                                           |
    | `--user-agent`                   | Overrides default user-agent string for Chromium.                                                                                                                                                                                                            |
    | `--margin-top`                   | (Default: 0.4) Top margin in inches.                                                                                                                                                                                                                        |
    | `--margin-bottom`                | (Default: 0.4) Bottom margin in inches.                                                                                                                                                                                                                    |
    | `--margin-left`                  | (Default: 0.4) Left margin in inches.                                                                                                                                                                                                                       |
    | `--margin-right`                 | (Default: 0.4) Right margin in inches.                                                                                                                                                                                                                     |
    | `--pageranges`                   | Specifies pages to print (e.g., '1-5, 8, 11-13').                                                                                                                                                                                                            |
    | `--chromium-location`            | Specifies Chrome/Edge location. Defaults to executable folder or registry.                                                                                                                                                                                               |
    | `--chromium-userprofile`         | Specifies location for Chromium user profile.                                                                                                                                                                                                              |
    | `--proxy-server`                 | Configures Chromium to use a custom proxy server.                                                                                                                                                                                                           |
    | `--proxy-bypass-list`             | Specifies hosts to bypass proxy. Requires `--proxy-server`. Format: `*.google.com;*foo.com;127.0.0.1:8080`.                                                                                                                                                            |
    | `--proxy-pac-url`                | Specifies PAC file URL for proxy (e.g., `http://wpad/windows.pac`).                                                                                                                                                                                                      |
    | `--user`                         | Runs browser under a specific user (used with `--password`).                                                                                                                                                                                                            |
    | `--password`                     | Specifies password for `--user`.                                                                                                                                                                                                                                        |
    | `--tempfolder`                   | Specifies folder for temporary files.                                                                                                                                                                                                                    |
    | `--multi-threading`              | (Default: false) Enables multi-threading (requires `--input-is-list`).                                                                                                                                                                                               |
    | `--max-concurrency-level`        | (Default: 0) Limits concurrency level for multi-threading.                                                                                                                                                                                                              |
    | `--wait-for-window-status`      | Waits for `window.status` to match a string before conversion.                                                                                                                                                                                                            |
    | `--wait-for-window-status-timeout`| (Default: 60000) Timeout for `--wait-for-window-status`.                                                                                                                                                                                                |
    | `--timeout`                      | Specifies timeout (ms) before aborting conversion.                                                                                                                                                                                                      |
    | `--media-load-timeout`           | Specifies timeout (ms) for media load after DOM content is loaded.                                                                                                                                                                                          | 
    | `--pre-wrap-file-extensions`     | Wraps files in HTML `<PRE>` tags.                                                                                                                                                                                                                          |
    | `--encoding`                     | Specifies encoding for `--input` file.                                                                                                                                                                                                                   |
    | `--image-resize`                 | (Default: false) Resizes images to fit page width.                                                                                                                                                                                                         |
    | `--image-rotate`                 | (Default: false) Rotates images per EXIF data.                                                                                                                                                                                                            |
    | `--image-load-timeout`           | (Default: 30000) Timeout for downloading images.                                                                                                                                                                                                          |
    | `--sanitize-html`                | (Default: false) Removes HTML elements that could lead to XSS.                                                                                                                                                                                          | 
    | `--logfile`                      | Specifies log file (wildcards: `{PID}`, `{DATE}`, `{TIME}`).                                                                                                                                                                                           |
    | `--run-javascript`               | Runs JavaScript after loading webpage but before PDF conversion.                                                                                                                                                                                          | 
    | `--url-blacklist`                | Blocks specified URLs (e.g., `*.google.com;*foo.com`).                                                                                                                                                                                                      |
    | `--snapshot`                      | Saves webpage snapshot as `.mhtml` alongside `.pdf`.                                                                                                                                                                                                         |
    | `--log-network-traffic`          | Enables logging of network traffic.                                                                                                                                                                                                                       |
    | `--disk-cache-disabled`         | (Default: false) Disables disk cache.                                                                                                                                                                                                                   |
    | `--disk-cache-directory`         | Specifies directory for disk cache.                                                                                                                                                                                                                       |
    | `--disk-cache-size`              | Specifies size of disk cache (MB).                                                                                                                                                                                                                       |
    | `--web-socket-timeout`           | Specifies WebSocket timeout (ms).                                                                                                                                                                                                                       |
    | `--wait-for-network-idle`        | Waits until network is idle before conversion.                                                                                                                                                                                                                         |
    | `--help`                         | Displays help information.                                                                                                                                                                                                                                                                                                                            |
    | `--version`                      | Displays version information.                                                                                                                                                                                                                                                                                                                          |
    | `--no-sandbox`                   | Never use a sandbox.                                                                                                                                                                                                                                                                                                                    |
    | `-enable-chromium-logging`       | Enables Chromium logging; The output will be saved to the file chrome_debug.log in Chrome's user data directory. Logs are overwritten each time you restart Chromium.                                                                                                                                                                                                      |
    | `--disable-gpu`                   | Passes --disable-gpu to Chromium. This should be useful on common server hardware.                                                                                                                                                                                                                                     |
    | `--ignore-certificate-errors`   | Passes --ignore-certificate-errors to Chromium. Useful when generating from internal web server.                                                                                                                                                                                              |
    | `--disable-crash-reporter`       | Passes --disable-crash-reporter and --no-crashpad to Chromium.                                                                                                                                                                                                                                     |
    | `--request-headers`              | Specifies request headers to send with all requests. Format: `Header1:Value1,Header2:Value2`. Example: `Authorization:Bearer token123,X-Custom-Header:CustomValue`. Note: Headers are automatically propagated to all resource requests (CSS, JS, images, etc.) when URL blacklisting is enabled. |
  10. Convert HTML to PDF via Command Line

    master

    The ChromiumHtmlToPdfConsole application allows for conversions via the CLI.

    Basic usage:

    ChromiumHtmlToPdfConsole --input https://www.google.com --output c:\google.pdf

    Exit Codes:

    • 0: Successful
    • 1: An error occurred
    ChromiumHtmlToPdfConsole --input https://www.google.com --output c:\google.pdf