HTML to PDF

Posted by Joe Enos on March 20, 2021 · 4 mins read

This uses the free and awesome wkhtmltopdf command line tool to convert HTML to PDF, using .NET’s built-in command-line functionality.

using System.Diagnostics;
using System.IO;

class Program
{
const string EXE = @"C:\wkhtmltopdf\wkhtmltopdf.exe";

static void Main(string[] args)
{
string html = "Hello World!";
byte[] pdf = CreatePDF(html);
string file = Path.GetTempFileName() + ".pdf";
File.WriteAllBytes(file, pdf);
Process.Start(file);
}

static byte[] CreatePDF(string html)
{
string tempHTML = Path.GetTempFileName() + ".html";
File.WriteAllText(tempHTML, html);

string tempPDF = Path.GetTempFileName() + ".pdf";

var process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
FileName = EXE,
Arguments = string.Format("\"{0}\" \"{1}\"", tempHTML, tempPDF)
},
EnableRaisingEvents = true
};
process.OutputDataReceived += (sender, e) =>
{
Debug.Write(e.Data);
};
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
process.CancelOutputRead();
byte[] result = File.ReadAllBytes(tempPDF);
File.Delete(tempHTML);
File.Delete(tempPDF);
return result;
}
}