is it possible to get a pdf stream created by wkhtmltopdf from any html file and popup a download dialog in IE/Firefox/Chrome etc.?
At the moment I get my outputstre
My take on this based on @Nenotlep answer. This is only the pdf generation part.
I am using async. I created a new StreamWriter because wkhtmltopdf is expecting utf-8 by default but it is set to something else when the process starts.
I removed p.WaitForExit(...) since I wasn't handling if it fails and it would hang anyway on await tStandardOutput
. If timeout is needed, then you would have to call Wait on the different tasks with a cancellationtoken or timeout and handle accordingly.
public static async Task GeneratePdf(string html, Size pageSize)
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = @"C:\PROGRA~1\WKHTML~1\wkhtmltopdf.exe",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
Arguments = "-q -n --disable-smart-shrinking "
+ (pageSize.IsEmpty ? "" : "--page-width " + pageSize.Width
+ "mm --page-height " + pageSize.Height + "mm") + " - -";
};
using (var p = Process.Start(psi))
using (var pdfSream = new MemoryStream())
using (var utf8Writer = new StreamWriter(p.StandardInput.BaseStream,
Encoding.UTF8))
{
await utf8Writer.WriteAsync(html);
utf8Writer.Close();
var tStdOut = p.StandardOutput.BaseStream.CopyToAsync(pdfSream);
var tStdError = p.StandardError.ReadToEndAsync();
await tStandardOutput;
string errors = await tStandardError;
if (!string.IsNullOrEmpty(errors))
{
//deal with errors
}
return pdfSream.ToArray();
}
}
Things I haven't included in there but could be useful as a reference: