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
}
};
proc.Start();
using(var sIn = proc.StandardInput) {
sIn.WriteLine("hello world");
}
var ms = new MemoryStream();
var sOut = proc.StandardOutput.BaseStream;
sOut.CopyTo(ms);
if (ms.Length == 0) {
string error = proc.StandardError.ReadToEnd();
throw new Exception(error);
}
proc.WaitForExit();
Console.WriteLine(ms.Length + " bytes written");
File.WriteAllBytes("hello.pdf", ms.ToArray());
Categories: Uncategorized
Comments (0)
Trackbacks (0)
Leave a comment
Trackback