HTML to PDF in a .NET Docker container, with no apt-get
Disclosure: I work on SelectPdf, the library used in this article. It's a commercial library with a free Community Edition; both are covered at the end. If you've ever generated PDFs from HTML in a Linux container, you probably know the drill: a headless browser needs a long list of shared libraries, so the Dockerfile grows an apt-get install line with twenty-odd packages, then fonts, then…
In this article, a .NET Docker container is created to convert web pages and HTML content to PDF format without the need for apt-get or any additional package installations. The project utilizes the SelectPdf library, specifically the SelectPdf.Universal package, which includes the Chromium rendering engine and all necessary components within a NuGet package. This approach simplifies the Dockerfile and avoids dependency issues that may arise from updating base images.
The API consists of two endpoints: GET /pdf?url=…, which returns any web page as a PDF, and POST /pdf with an HTML body, which returns that HTML as a PDF. The project is built using a minimal ASP.NET Core service with just the required packages, and the native engine package is included to handle the rendering process headlessly, eliminating the need for additional fonts or libraries.
The Dockerfile employs a multi-stage build process, utilizing the official .NET SDK and runtime images. It does not include any apt-get or additional steps, ensuring a clean and minimal container image. No display server or extra resources are required, as the rendering occurs within the container itself. The resulting Docker image is lightweight and runs as a non-root user, making it secure and efficient.
No additional fonts are needed for common languages, as the library includes the Liberation fonts that support Latin, Greek, and Cyrillic text. For other languages such as Chinese, Japanese, Korean, Arabic, Hebrew, Hindi, Thai, and emoji support, the SelectPdf.Universal.Fonts package is available and adds the necessary Noto fonts during the build process. This ensures proper rendering of text in various languages without installing any external fonts in the container image.
The container is built and run using simple `docker build` and `docker run` commands, with no extra flags or configurations needed. It can run on any base image with a glibc-based runtime, such as Debian, Ubuntu, or Amazon Linux, providing cross-platform compatibility. The container is designed to handle high loads efficiently, requiring at least 1 core and 2 GB of RAM, with 2+ cores recommended for optimal performance.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.