public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput) { if (environment == null) environment = Environment; String outputPdfFilePath; bool delete = false; if (woutput.OutputFilePath != null) outputPdfFilePath = woutput.OutputFilePath; else { outputPdfFilePath = Path.Combine(environment.TempFolderPath, String.Format("{0}.pdf", Guid.NewGuid())); delete = true; } if (!File.Exists(environment.WkHtmlToPdfPath)) throw new PdfConvertException(String.Format("File '{0}' not found. Make sure wkhtmltopdf files exist.", environment.WkHtmlToPdfPath)); var paramsBuilder = BuildParameters(document, outputPdfFilePath); var si = new ProcessStartInfo { CreateNoWindow = !environment.Debug, FileName = environment.WkHtmlToPdfPath, Arguments = paramsBuilder.ToString(), UseShellExecute = false, RedirectStandardError = !environment.Debug }; try { using (var process = new Process()) { ProcessHtmlToPdf(si, process, environment, document); if (!File.Exists(outputPdfFilePath)) throw new PdfConvertException(String.Format("Html to PDF conversion of '{0}' failed. Reason: Output file '{1}' not found.", document.Url, outputPdfFilePath)); WriteOutput(woutput, outputPdfFilePath); ExecuteCallback(document, woutput, outputPdfFilePath); } } finally { if (delete && File.Exists(outputPdfFilePath)) File.Delete(outputPdfFilePath); } }
private static void ProcessHtmlToPdf(ProcessStartInfo si, Process process, PdfConvertEnvironment environment, PdfDocument document) { process.StartInfo = si; process.Start(); if (!process.WaitForExit(environment.Timeout)) throw new PdfConvertTimeoutException(); if (process.ExitCode != 0) { var error = si.RedirectStandardError ? process.StandardError.ReadToEnd() : String.Format("Process exited with code {0}.", process.ExitCode); throw new PdfConvertException(String.Format("Html to PDF conversion of '{0}' failed. Wkhtmltopdf output: \r\n{1}", document.Url, error)); } }