我有一种使用 hkhtmltopdf 生成 PDF 的方法:
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);
}
}
这种方法没问题,可以生成我需要的 PDF。但是现在我需要为我的 PDF 的所有页面添加页脚,所以我发现了这个问题并尝试这样做。上面的代码正在调用以下命令行:
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
如果我从上面的代码中调用它,它会永远运行,当我停止该过程时,会在文件夹中生成格式错误的 PDF(未应用 HTML)。否则,如果我直接从命令行调用该命令,它会在不到 10 秒的时间内为我生成正确的 PDF。
我在这种方法中可能做错了什么?非常感谢。