I have a method to generate PDFs using hkhtmltopdf:
public string GeneratePdf(string pdfOutputLocation, string outputFilenamePrefix, string[] urls,
string[] options,
string pdfHtmlToPdfExePath)
{
string urlsSeparatedBySpaces = string.Empty;
try
{
//Determine inputs
if ((urls == null) || (urls.Length == 0))
throw new Exception("No input URLs provided for HtmlToPdf");
else
urlsSeparatedBySpaces = String.Join(" ", urls); //Concatenate URLs
//string outputFolder = pdfOutputLocation;
string outputFilename = outputFilenamePrefix + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fff") + ".PDF"; // assemble destination PDF file name
var p = new System.Diagnostics.Process();
p.StartInfo.FileName = pdfHtmlToPdfExePath;
p.StartInfo.Arguments = ((options == null) ? "" : String.Join(" ", options)) + " " + urlsSeparatedBySpaces + " " + outputFilename;
p.StartInfo.UseShellExecute = false; // needs to be false in order to redirect output
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true; // redirect all 3, as it should be all 3 or none
p.StartInfo.WorkingDirectory = string.Concat(HttpContext.Current.Server.MapPath(""), "\\", pdfOutputLocation, "\\");
p.Start();
// read the output here...
var output = p.StandardOutput.ReadToEnd();
var errorOutput = p.StandardError.ReadToEnd();
// ...then wait n milliseconds for exit (as after exit, it can't read the output)
p.WaitForExit(600000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
// if 0 or 2, it worked so return path of pdf
if ((returnCode == 0) || (returnCode == 2))
{
linkPdfDownload = pathPdf + outputFilename;
return outputFilename;
}
else
throw new Exception(errorOutput);
}
catch (Exception ex)
{
throw new Exception("Problem generating PDF from HTML, URLs: " + urlsSeparatedBySpaces + ", outputFilename: " + outputFilenamePrefix, ex);
}
}
This method is OK and generates me the PDFs I need. But now I need to add a footer to all the pages of my PDF, so I found this question and tried to do it. The code above is calling the following command line:
wkhtmltopdf.exe -T 50mm --footer-html http://localhost:5001/HTML/cabecalho.html http://localhost:5001/HTML/arquivo56784325.html Modelo__2013-10-31-01-53-46-757.PDF
If I call this from the code above, it runs forever and when I stop the process, a malformed PDF is generated(without the HTML applied) in the folder. Otherwise, if I call that command directly from command line, it generates the correct PDF in less than 10 secs for me.
What am I possibly doing wrong in that method? Thank you very much.