How to Use WkHtmlToPdf-DotNet for HTML to PDF Conversion

Aug 9, 2024 | Programming

Welcome to the world of WkHtmlToPdf-DotNet! This powerful .NET Core PInvoke wrapper for the native wkhtmltopdf library makes the process of converting HTML pages to PDFs as smooth as a well-oiled machine. With the ability to run on various platforms including Windows, Linux, and MacOSX, let’s delve into how you can harness its capabilities.

Step 1: Install the Library

To start using WkHtmlToPdf-DotNet, you need to install the library through NuGet. Just follow these simple instructions:

  • Open your Package Manager Console.
  • Run the command:
  • PM Install-Package Haukcode.WkHtmlToPdfDotNet

By using this NuGet package, you won’t need to manually add the native binaries to your project!

Step 2: Basic and Synchronized Converters

Now, let’s get to the fun part—using converters! There are two converters you can consider based on your application:

  • Basic Converter: Best for single-threaded applications. Here’s how you can create one:
  • var converter = new BasicConverter(new PdfTools());
  • Synchronized Converter: Ideal for multi-threaded applications and web servers. Tasks will be executed on a single thread. Here’s how to create it:
  • var converter = new SynchronizedConverter(new PdfTools());

Step 3: Define Your HTML Document

Next, you will need to define the HTML document you want to convert. Picture this as preparing an ingredient list before cooking. Here’s how you can do it:

var doc = new HtmlToPdfDocument()
{
    GlobalSettings = new GlobalSettings()
    {
        ColorMode = ColorMode.Color,
        Orientation = Orientation.Landscape,
        PaperSize = PaperKind.A4Plus,
    },
    Objects = new List()
    {
        new ObjectSettings()
        {
            PagesCount = true,
            HtmlContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
            WebSettings = new WebSettings()
            {
                DefaultEncoding = "utf-8"
            },
            HeaderSettings = new HeaderSettings()
            {
                FontSize = 9,
                Right = "Page [page] of [toPage]",
                Line = true,
                Spacing = 2.812
            }
        }
    }
};

Step 4: Convert the Document

Finally, it’s time to convert! Just like pressing the bake button once your cake batter is ready, here’s the code you need:

byte[] pdf = converter.Convert(doc);

If you want to save the file directly to disk instead, you can define the Out property in your document as shown below:

var doc = new HtmlToPdfDocument()
{
    GlobalSettings = new GlobalSettings()
    {
        ColorMode = ColorMode.Color,
        Orientation = Orientation.Portrait,
        PaperSize = PaperKind.A4,
        Margins = new MarginSettings() { Top = 10 },
        Out = "C:\\WkHtmlToPdf-DotNet\\src\\TestThreadSafe\\test.pdf",
    },
    Objects = new List()
    {
        new ObjectSettings()
        {
            Page = "http://google.com",
        },
    }
};

converter.Convert(doc);

Step 5: Dependency Injection

To ensure that the converter is ready for use throughout your application, register it as a singleton in your service configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
}

Step 6: Setting Up Docker

If you’re planning to use WkHtmlToPdf-DotNet inside a Docker container, you’ll need some extra preparation for a Linux setup. Imagine you are stocking your kitchen with the right tools before getting to work!

For Debian-based Linux distributions, include the following lines in your Dockerfile:

RUN apt update
RUN apt install -y libgdiplus
RUN ln -s /usr/lib/libgdiplus.so libx86_64-linux-gnu/libgdiplus.so
RUN apt-get install -y --no-install-recommends zlib1g fontconfig libfreetype6 libx11-6 libxext6 libxrender1 wget gdebi
RUN wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.5/wkhtmltox_0.12.5-1.stretch_amd64.deb
RUN gdebi --n wkhtmltox_0.12.5-1.stretch_amd64.deb
RUN apt install libssl1.1
RUN ln -s /usr/local/lib/libwkhtmltox.so /usr/lib/libwkhtmltox.so

Troubleshooting

If you run into any challenges while using WkHtmlToPdf-DotNet, consider the following tips:

  • Ensure all required libraries are installed correctly, especially when working with Docker containers.
  • Check that your HTML content is properly sanitized, as untrusted HTML may lead to severe security issues.
  • If the PDF outputs are not as expected, verify that the HTML and CSS are compatible and rendered correctly.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Final Words

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Recommendations

Never use wkhtmltopdf with untrusted HTML to prevent potential security vulnerabilities. Always sanitize user-supplied HTML content!

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox