public static byte[] GetPdfFile(string uniqueFileId) { string htmlFilePath = string.Format(@"{0}\{1}\{2}.html", HttpContext.Current.Server.MapPath("~"), @"PdfTemp\", uniqueFileId.ToString()); int counter = 0; while (!File.Exists(htmlFilePath)) { counter++; // wait a maximum of 1 minute to see if the HTML file is ready if (counter < 60) { Thread.Sleep(1000); } else { throw new Exception(string.Format("Failed to generate HTML for {0}", uniqueFileId.ToString())); } } PdfOutput pdfOutput = new PdfOutput() { OutputFilePath = htmlFilePath.Replace(".html", ".pdf") }; var absoultePath = System.Web.VirtualPathUtility.ToAbsolute("~/"); PdfDocument pdfDocument = new PdfDocument() { Url = string.Format("{0}://{1}/{2}PdfTemp/{3}.html", /*HttpContext.Current.Request.Url.Scheme*/ "http", HttpContext.Current.Request.Url.Host, absoultePath == "/" ? string.Empty : absoultePath, uniqueFileId) }; //Logging.PutInfo("pdf url: " + pdfDocument.Url); PdfConvert.ConvertHtmlToPdf(pdfDocument, pdfOutput); var file = File.ReadAllBytes(htmlFilePath.Replace(".html", ".pdf")); File.Delete(htmlFilePath); File.Delete(htmlFilePath.Replace(".html", ".pdf")); return(file); }
/// <summary> /// Generates the PDF certificate. /// </summary> /// <param name="htmlCert">The HTML cert.</param> /// <returns>Byte Array - containing PDF file of Certificate.</returns> public static byte[] GeneratePdf(string htmlCert) { byte[] pdfFile = null; // save the file to disk string uniqueFileId = Guid.NewGuid().ToString(); string outputDirectoryPath = HttpContext.Current.Server.MapPath("~/PdfTemp/"); string outputFilePath = Path.Combine(outputDirectoryPath, string.Format("{0}.html", uniqueFileId)); if (!Directory.Exists(outputDirectoryPath)) { Directory.CreateDirectory(outputDirectoryPath); } // save the file to disk using (FileStream fs = new FileStream(outputFilePath, FileMode.Create)) { using (StreamWriter ws = new StreamWriter(fs, Encoding.UTF8)) { ws.WriteLine(htmlCert); } } // wait for the file to be created int counter = 0; while (!File.Exists(outputFilePath)) { counter++; // wait a maximum of 1 minute to see if the HTML file is ready if (counter < 60) { Thread.Sleep(1000); } else { throw new Exception(string.Format("Failed to generate HTML for {0}", uniqueFileId.ToString())); } } // setup transport objects PdfOutput pdfOutput = new PdfOutput { OutputFilePath = outputFilePath.Replace(".html", ".pdf") }; var absoultePath = VirtualPathUtility.ToAbsolute("~/"); PdfDocument pdfDocument = new PdfDocument { Url = string.Format("{0}://{1}/{2}PdfTemp/{3}.html", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Authority, absoultePath, uniqueFileId) }; // make call to convert PdfConvert.ConvertHtmlToPdf(pdfDocument, pdfOutput); pdfFile = File.ReadAllBytes(outputFilePath.Replace(".html", ".pdf")); // clean up both files if (File.Exists(outputFilePath)) { File.Delete(outputFilePath); } if (File.Exists(outputFilePath.Replace(".html", ".pdf"))) { File.Delete(outputFilePath.Replace(".html", ".pdf")); } return(pdfFile); }
public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput) { if (environment == null) { environment = Environment; } String outputPdfFilePath; bool delete; if (woutput.OutputFilePath != null) { outputPdfFilePath = woutput.OutputFilePath; delete = false; } 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. Check if wkhtmltopdf application is installed.", environment.WkHtmlToPdfPath)); } ProcessStartInfo si; StringBuilder paramsBuilder = new StringBuilder(); paramsBuilder.Append("--page-size A4 "); paramsBuilder.Append("--load-error-handling ignore "); //paramsBuilder.Append("--redirect-delay 0 "); not available in latest version paramsBuilder.Append("--margin-top 10 "); paramsBuilder.Append("--margin-left 5 "); paramsBuilder.Append("--margin-right 5 "); paramsBuilder.Append("--margin-bottom 10 "); if (!string.IsNullOrEmpty(document.HeaderUrl)) { paramsBuilder.AppendFormat("--header-html {0} ", document.HeaderUrl); paramsBuilder.Append("--margin-top 0 "); paramsBuilder.Append("--header-spacing 0 "); } if (!string.IsNullOrEmpty(document.FooterUrl)) { paramsBuilder.AppendFormat("--footer-html {0} ", document.FooterUrl); paramsBuilder.Append("--margin-bottom 0 "); paramsBuilder.Append("--footer-spacing 0 "); } //remove the border from the pages // paramsBuilder.Append("-L 0 -R 0 -T 0 -B 0 "); paramsBuilder.AppendFormat("\"{0}\" \"{1}\"", document.Url, outputPdfFilePath); si = new ProcessStartInfo(); si.CreateNoWindow = true; si.FileName = environment.WkHtmlToPdfPath; si.Arguments = paramsBuilder.ToString(); si.UseShellExecute = false; si.RedirectStandardError = true; si.RedirectStandardInput = true; si.RedirectStandardOutput = true; try { using (var process = new Process()) { process.StartInfo = si; process.Start(); if (!process.WaitForExit(environment.Timeout)) { throw new PdfConvertTimeoutException(); } if (!File.Exists(outputPdfFilePath)) { 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)); } throw new PdfConvertException(String.Format("Html to PDF conversion of '{0}' failed. Reason: Output file '{1}' not found.", document.Url, outputPdfFilePath)); } if (woutput.OutputStream != null) { using (Stream fs = new FileStream(outputPdfFilePath, FileMode.Open)) { byte[] buffer = new byte[32 * 1024]; int read; while ((read = fs.Read(buffer, 0, buffer.Length)) > 0) { woutput.OutputStream.Write(buffer, 0, read); } } } if (woutput.OutputCallback != null) { woutput.OutputCallback(document, File.ReadAllBytes(outputPdfFilePath)); } } } finally { if (delete && File.Exists(outputPdfFilePath)) { File.Delete(outputPdfFilePath); } } }
public static void ConvertHtmlToPdf(PdfDocument document, PdfOutput output) { ConvertHtmlToPdf(document, null, output); }