Пример #1
0
        /// <summary>
        ///     Convert Html to Pdf
        /// </summary>
        /// <param name="url">     File path or HTTP URL </param>
        /// <param name="pdfPath"></param>
        public static void ToPdf(string url, string pdfPath)
        {
            var pdfOutput = new HtmlToPdf.PdfOutput {
                OutputFilePath = pdfPath
            };

            ToPdf(new HtmlToPdf.PdfDocument {
                Url = url
            }, pdfOutput);
        }
Пример #2
0
        /// <summary>
        ///     Convert Html to Pdf
        /// </summary>
        /// <param name="url"> File path or HTTP URL </param>
        public static byte[] ToPdf(string url)
        {
            byte[] fileBytes = null;

            var pdfOutput = new HtmlToPdf.PdfOutput
            {
                OutputCallback = (document, bytes) =>
                {
                    fileBytes = bytes;
                }
            };

            ToPdf(new HtmlToPdf.PdfDocument {
                Url = url
            }, pdfOutput);

            return(fileBytes);
        }
Пример #3
0
        public static void ToPdf(HtmlToPdf.PdfDocument document, HtmlToPdf.PdfOutput pdfOutput)
        {
            var environment = new ToolEnvironment
            {
                TempFolderPath = Path.GetTempPath(),
                ToolPath       = $"{nameof(HtmlUtils)}/wkhtml/wkhtmltopdf.exe".GetFullPath(null),
                Timeout        = 60000
            };

            string outputPdfFilePath;
            bool   delete;

            if (pdfOutput.OutputFilePath != null)
            {
                outputPdfFilePath = pdfOutput.OutputFilePath;
                delete            = false;
            }
            else
            {
                outputPdfFilePath = Path.Combine(environment.TempFolderPath, $"{Guid.NewGuid():N}.pdf");
                delete            = true;
            }

            if (!File.Exists(environment.ToolPath))
            {
                throw new HtmlConvertException($"File '{environment.ToolPath}' not found. Check if wkhtmltopdf application is installed.");
            }

            var paramsBuilder = new StringBuilder();

            paramsBuilder.AppendFormat("--page-size {0} ", document.PaperType);

            if (!string.IsNullOrWhiteSpace(document.HeaderUrl))
            {
                paramsBuilder.AppendFormat("--header-html {0} ", document.HeaderUrl);
                paramsBuilder.Append("--margin-top 25 ");
                paramsBuilder.Append("--header-spacing 5 ");
            }
            if (!string.IsNullOrWhiteSpace(document.FooterUrl))
            {
                paramsBuilder.AppendFormat("--footer-html {0} ", document.FooterUrl);
                paramsBuilder.Append("--margin-bottom 25 ");
                paramsBuilder.Append("--footer-spacing 5 ");
            }
            if (!string.IsNullOrWhiteSpace(document.HeaderLeft))
            {
                paramsBuilder.AppendFormat("--header-left \"{0}\" ", document.HeaderLeft);
            }

            if (!string.IsNullOrWhiteSpace(document.HeaderCenter))
            {
                paramsBuilder.AppendFormat("--header-center \"{0}\" ", document.HeaderCenter);
            }

            if (!string.IsNullOrWhiteSpace(document.HeaderRight))
            {
                paramsBuilder.AppendFormat("--header-right \"{0}\" ", document.HeaderRight);
            }

            if (!string.IsNullOrWhiteSpace(document.FooterLeft))
            {
                paramsBuilder.AppendFormat("--footer-left \"{0}\" ", document.FooterLeft);
            }

            if (!string.IsNullOrWhiteSpace(document.FooterCenter))
            {
                paramsBuilder.AppendFormat("--footer-center \"{0}\" ", document.FooterCenter);
            }

            if (!string.IsNullOrWhiteSpace(document.FooterRight))
            {
                paramsBuilder.AppendFormat("--footer-right \"{0}\" ", document.FooterRight);
            }

            if (!string.IsNullOrWhiteSpace(document.HeaderFontSize))
            {
                paramsBuilder.AppendFormat("--header-font-size \"{0}\" ", document.HeaderFontSize);
            }

            if (!string.IsNullOrWhiteSpace(document.FooterFontSize))
            {
                paramsBuilder.AppendFormat("--footer-font-size \"{0}\" ", document.FooterFontSize);
            }

            if (!string.IsNullOrWhiteSpace(document.HeaderFontName))
            {
                paramsBuilder.AppendFormat("--header-font-name \"{0}\" ", document.HeaderFontName);
            }

            if (!string.IsNullOrWhiteSpace(document.FooterFontName))
            {
                paramsBuilder.AppendFormat("--footer-font-name \"{0}\" ", document.FooterFontName);
            }

            if (document.ExtraParams != null)
            {
                foreach (var extraParam in document.ExtraParams)
                {
                    paramsBuilder.AppendFormat("--{0} {1} ", extraParam.Key, extraParam.Value);
                }
            }

            if (document.Cookies != null)
            {
                foreach (var cookie in document.Cookies)
                {
                    paramsBuilder.AppendFormat("--cookie {0} {1} ", cookie.Key, cookie.Value);
                }
            }

            paramsBuilder.AppendFormat("\"{0}\" \"{1}\"", document.Url, outputPdfFilePath);

            try
            {
                StringBuilder output = new StringBuilder();
                StringBuilder error  = new StringBuilder();

                using (Process process = new Process())
                {
                    process.StartInfo.FileName               = environment.ToolPath;
                    process.StartInfo.Arguments              = paramsBuilder.ToString();
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;
                    process.StartInfo.RedirectStandardInput  = true;

                    using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
                        using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                        {
                            DataReceivedEventHandler outputHandler = (sender, e) =>
                            {
                                if (e.Data == null)
                                {
                                    outputWaitHandle.Set();
                                }
                                else
                                {
                                    output.AppendLine(e.Data);
                                }
                            };

                            DataReceivedEventHandler errorHandler = (sender, e) =>
                            {
                                if (e.Data == null)
                                {
                                    errorWaitHandle.Set();
                                }
                                else
                                {
                                    error.AppendLine(e.Data);
                                }
                            };

                            process.OutputDataReceived += outputHandler;
                            process.ErrorDataReceived  += errorHandler;

                            try
                            {
                                process.Start();
                                process.BeginOutputReadLine();
                                process.BeginErrorReadLine();

                                if (process.WaitForExit(environment.Timeout) && outputWaitHandle.WaitOne(environment.Timeout) && errorWaitHandle.WaitOne(environment.Timeout))
                                {
                                    if (process.ExitCode != 0 && !File.Exists(outputPdfFilePath))
                                    {
                                        throw new HtmlConvertException($"Html to PDF conversion of '{document.Url}' failed. Wkhtmltopdf output: \r\n{error}");
                                    }
                                }
                                else
                                {
                                    if (!process.HasExited)
                                    {
                                        process.Kill();
                                    }

                                    throw new HtmlConvertTimeoutException();
                                }
                            }
                            finally
                            {
                                process.OutputDataReceived -= outputHandler;
                                process.ErrorDataReceived  -= errorHandler;
                            }
                        }
                }

                if (pdfOutput.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)
                        {
                            pdfOutput.OutputStream.Write(buffer, 0, read);
                        }
                    }
                }

                if (pdfOutput.OutputCallback != null)
                {
                    byte[] pdfFileBytes = File.ReadAllBytes(outputPdfFilePath);
                    pdfOutput.OutputCallback(document, pdfFileBytes);
                }
            }
            finally
            {
                if (delete && File.Exists(outputPdfFilePath))
                {
                    FileHelper.SafeDelete(outputPdfFilePath);
                }
            }
        }