Home > Uncategorized > Generate a #PDF from #HTML on Raspberry PI (.NET Core)

Generate a #PDF from #HTML on Raspberry PI (.NET Core)

TL; DR; Here is the github repo: https://github.com/infiniteloopltd/hello-world-pi/blob/master/program.cs

This was an academic exercise for me, but in case you ever wanted to generate PDFs on a Raspberry pi, here is some code to do so in C# (.NET Core).

The core of the operation is wkhtmltopdf, which you can install on Raspberry pi (ubuntu), by simply typing

"apt-get wkhtmltopdf"

Then I created a C# app, based on the code from WkHtmlDriver that simply opens the executable, and redirects the standard input / output and error streams to the host application, and feeds it HTML to be encoded, and captures the output stream.

The code then converts the output stream to a byte array, and then dumps this to disk.

Here’s the final code:

var proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "wkhtmltopdf",
            Arguments = "-q - -",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            RedirectStandardInput = true,
            CreateNoWindow = true
using(var sIn = proc.StandardInput) {
    sIn.WriteLine("hello world");
var ms = new MemoryStream();
var sOut = proc.StandardOutput.BaseStream;
if (ms.Length == 0) {
    string error = proc.StandardError.ReadToEnd();
    throw new Exception(error);
Console.WriteLine(ms.Length + " bytes written");
File.WriteAllBytes("hello.pdf", ms.ToArray());

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

<span>%d</span> bloggers like this: