Exemplo n.º 1
0
 /// <summary
 /// Converts a PdfDocument object from HTML to PDf.
 /// </summary>
 /// <param name="document">The PDF input document.</param>
 /// <param name="environment">The wkhtml enviromental settings object.</param>
 /// <param name="woutput">An object holding the output settings.</param>
 public static Task ConvertHtmlToPdfAsync(PdfDocument document, PdfConvertEnvironment environment, PdfOutput output)
 {
     return(Task.Factory.StartNew(() =>
     {
         ConvertHtmlToPdf(document, environment, output);
     }));
 }
Exemplo n.º 2
0
        public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
        {
            if (environment == null)
            {
                environment = Environment;
            }

            if (document.Html != null)
            {
                document.Url = "-";
            }

            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));
            }

            StringBuilder paramsBuilder = new StringBuilder();

            paramsBuilder.Append("--page-size A4 ");

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

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

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

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

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

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

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

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

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

            if (!string.IsNullOrEmpty(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.WkHtmlToPdfPath;
                    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 (document.Html != null)
                                {
                                    using (var stream = process.StandardInput)
                                    {
                                        byte[] buffer = Encoding.UTF8.GetBytes(document.Html);
                                        stream.BaseStream.Write(buffer, 0, buffer.Length);
                                        stream.WriteLine();
                                    }
                                }

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

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


                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)
                {
                    byte[] pdfFileBytes = File.ReadAllBytes(outputPdfFilePath);
                    woutput.OutputCallback(document, pdfFileBytes);
                }
            }
            finally
            {
                if (delete && File.Exists(outputPdfFilePath))
                {
                    File.Delete(outputPdfFilePath);
                }
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Converts a PdfDocument object from HTML to PDf.
 /// </summary>
 /// <param name="document">The PDF input document.</param>
 /// <param name="environment">The wkhtml enviromental settings object.</param>
 /// <param name="woutput">An object holding the output settings.</param>
 public static Task ConvertHtmlToPdfAsync(PdfDocument document, PdfConvertEnvironment environment, PdfOutput output)
 {
     return Task.Factory.StartNew(() =>
     {
         ConvertHtmlToPdf(document, environment, output);
     });
 }
Exemplo n.º 4
0
        /// <summary>
        /// Converts a PdfDocument object from HTML to PDf.
        /// </summary>
        /// <param name="document">The PDF input document.</param>
        /// <param name="environment">The wkhtml enviromental settings object.</param>
        /// <param name="woutput">An object holding the output settings.</param>
        public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
        {
            if (IsEmptyUrl(document.Url) && string.IsNullOrEmpty(document.Html))
                throw new PdfConvertException(
                    String.Format("You must supply a HTML string, if you have entered the url: {0}",
                        document.Url)
                );

            if (environment == null)
                environment = Environment;

            if (!File.Exists(environment.WkHtmlToPdfPath))
                throw new PdfConvertException(
                    String.Format("File '{0}' not found. Check if wkhtmltopdf application is installed.",
                        environment.WkHtmlToPdfPath));

            string PdfOutputPath;
            if (woutput.OutputFilePath == null)
                PdfOutputPath = Path.Combine(Environment.TempFolderPath, Path.GetRandomFileName());
            else
                PdfOutputPath = woutput.OutputFilePath;

            var error = new StringBuilder();

            using (var output = new MemoryStream())
            using (Process process = new Process())
            {
                process.StartInfo.FileName = environment.WkHtmlToPdfPath;
                process.StartInfo.Arguments = BuildParams(document, PdfOutputPath);
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardInput = true;

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

                    process.ErrorDataReceived += errorHandler;
                    process.Start();
                    process.BeginErrorReadLine();

                    if (document.Html != null && IsEmptyUrl(document.Url))
                        using (var stream = process.StandardInput)
                            stream.Write(document.Html);

                    if (process.WaitForExit(environment.Timeout) && errorWaitHandle.WaitOne())
                    {
                        if (process.ExitCode != 0)
                            throw new PdfConvertException(
                                String.Format("Html to PDF conversion of document failed. Wkhtmltopdf output: \r\n{1}",
                                document.Url, error));
                        else
                        {
                            if (woutput.OutputStream != null || woutput.OutputCallback != null)
                            {
                                int read;
                                byte[] buff = new byte[BUFFER_SIZE];
                                using (var fs = new FileStream(PdfOutputPath, FileMode.Open))
                                    while ((read = fs.Read(buff, 0, BUFFER_SIZE)) > 0)
                                        output.Write(buff, 0, read);

                                output.Position = 0;
                                if (woutput.OutputStream != null)
                                    while ((read = output.Read(buff, 0, BUFFER_SIZE)) > 0)
                                        woutput.OutputStream.Write(buff, 0, read);
                                if (woutput.OutputCallback != null)
                                    woutput.OutputCallback(document, output.ToArray());
                            }
                        }
                    }
                    else
                    {
                        if (!process.HasExited)
                            process.Kill();

                        throw new PdfConvertTimeoutException();
                    }

                    process.ErrorDataReceived -= errorHandler;
                    if (woutput.OutputFilePath == null)
                        File.Delete(PdfOutputPath);
                }
            }
        }
Exemplo n.º 5
0
        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("--redirect-delay 0 "); not available in latest version
            if (!string.IsNullOrEmpty(document.HeaderUrl))
            {
                paramsBuilder.AppendFormat("--header-html {0} ", document.HeaderUrl);
                paramsBuilder.Append("--margin-top 25 ");
                paramsBuilder.Append("--header-spacing 5 ");
            }
            if (!string.IsNullOrEmpty(document.FooterUrl))
            {
                paramsBuilder.AppendFormat("--footer-html {0} ", document.FooterUrl);
                paramsBuilder.Append("--margin-bottom 25 ");
                paramsBuilder.Append("--footer-spacing 5 ");
            }

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

            si = new ProcessStartInfo();
            si.CreateNoWindow = !environment.Debug;
            si.FileName = environment.WkHtmlToPdfPath;
            si.Arguments = paramsBuilder.ToString();
            si.UseShellExecute = false;
            si.RedirectStandardError = !environment.Debug;

            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, 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("--redirect-delay 0 "); not available in latest version
            if (!string.IsNullOrEmpty(document.HeaderUrl))
            {
                paramsBuilder.AppendFormat("--header-html {0} ", document.HeaderUrl);
                paramsBuilder.Append("--margin-top 25 ");
                paramsBuilder.Append("--header-spacing 5 ");
            }
            if (!string.IsNullOrEmpty(document.FooterUrl))
            {
                paramsBuilder.AppendFormat("--footer-html {0} ", document.FooterUrl);
                paramsBuilder.Append("--margin-bottom 25 ");
                paramsBuilder.Append("--footer-spacing 5 ");
            }

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


            si = new ProcessStartInfo();
            si.CreateNoWindow        = !environment.Debug;
            si.FileName              = environment.WkHtmlToPdfPath;
            si.Arguments             = paramsBuilder.ToString();
            si.UseShellExecute       = false;
            si.RedirectStandardError = !environment.Debug;

            try
            {
                using (var process = new Process())
                {
                    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));
                    }

                    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));
                    }

                    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);
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Converts a PdfDocument object from HTML to PDf.
        /// </summary>
        /// <param name="document">The PDF input document.</param>
        /// <param name="environment">The wkhtml enviromental settings object.</param>
        /// <param name="woutput">An object holding the output settings.</param>
        public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
        {
            if (IsEmptyUrl(document.Url) && string.IsNullOrEmpty(document.Html))
            {
                throw new PdfConvertException(
                          String.Format("You must supply a HTML string, if you have entered the url: {0}",
                                        document.Url)
                          );
            }

            if (environment == null)
            {
                environment = Environment;
            }

            if (!File.Exists(environment.WkHtmlToPdfPath))
            {
                throw new PdfConvertException(
                          String.Format("File '{0}' not found. Check if wkhtmltopdf application is installed.",
                                        environment.WkHtmlToPdfPath));
            }

            string PdfOutputPath;

            if (woutput.OutputFilePath == null)
            {
                PdfOutputPath = Path.Combine(Environment.TempFolderPath, Path.GetRandomFileName());
            }
            else
            {
                PdfOutputPath = woutput.OutputFilePath;
            }

            var error = new StringBuilder();

            using (var output = new MemoryStream())
                using (Process process = new Process())
                {
                    process.StartInfo.FileName               = environment.WkHtmlToPdfPath;
                    process.StartInfo.Arguments              = BuildParams(document, PdfOutputPath);
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;
                    process.StartInfo.RedirectStandardInput  = true;
                    process.StartInfo.CreateNoWindow         = true;
                    process.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;

                    using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                    {
                        DataReceivedEventHandler errorHandler = (sender, e) =>
                        {
                            //if (e.Data == null)
                            //    errorWaitHandle.Set();
                            //else
                            //{
                            if (e.Data != null)
                            {
                                error.AppendLine(e.Data);
                            }
                            else
                            {
                                errorWaitHandle.Set();
                            }
                            //}
                        };

                        process.ErrorDataReceived += errorHandler;
                        process.Start();
                        process.BeginErrorReadLine();

                        if (document.Html != null && IsEmptyUrl(document.Url))
                        {
                            using (var stream = process.StandardInput)
                                stream.Write(document.Html);
                        }

                        if (process.WaitForExit(environment.Timeout) && errorWaitHandle.WaitOne())
                        {
                            if (process.ExitCode != 0 && process.ExitCode != 1)
                            {
                                throw new PdfConvertException(
                                          String.Format("Html to PDF conversion of document failed. Wkhtmltopdf output: \r\n{1}",
                                                        document.Url, error));
                            }
                            else
                            {
                                if (woutput.OutputStream != null || woutput.OutputCallback != null)
                                {
                                    int    read;
                                    byte[] buff = new byte[BUFFER_SIZE];
                                    using (var fs = new FileStream(PdfOutputPath, FileMode.Open))
                                        while ((read = fs.Read(buff, 0, BUFFER_SIZE)) > 0)
                                        {
                                            output.Write(buff, 0, read);
                                        }

                                    output.Position = 0;
                                    if (woutput.OutputStream != null)
                                    {
                                        while ((read = output.Read(buff, 0, BUFFER_SIZE)) > 0)
                                        {
                                            woutput.OutputStream.Write(buff, 0, read);
                                        }
                                    }
                                    if (woutput.OutputCallback != null)
                                    {
                                        woutput.OutputCallback(document, output.ToArray());
                                    }
                                }
                            }
                        }
                        else
                        {
                            process.ErrorDataReceived -= errorHandler;
                            if (!process.HasExited)
                            {
                                process.Kill();
                            }
                            if (woutput.OutputFilePath == null || File.Exists(PdfOutputPath))
                            {
                                try {
                                    File.Delete(PdfOutputPath);
                                }
                                catch (System.IO.IOException e)
                                {
                                    Console.Write(e.StackTrace.ToString());
                                }
                            }
                            throw new PdfConvertTimeoutException();
                        }
                        process.ErrorDataReceived -= errorHandler;
                        if (woutput.OutputFilePath == null)
                        {
                            File.Delete(PdfOutputPath);
                        }
                    }
                }
        }
Exemplo n.º 8
0
        private static async Task ConvertHtmlToPdfCoreAsync(bool blnSync, PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
        {
            if (environment == null)
            {
                environment = Environment;
            }

            if (document.Html != null)
            {
                document.Url = "-";
            }

            string outputPdfFilePath;
            bool   delete;

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

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

            string strParams;

            using (new FetchSafelyFromPool <StringBuilder>(Utils.StringBuilderPool,
                                                           out StringBuilder sbdParams))
            {
                sbdParams.Append("--page-size A4 ");
                sbdParams.Append("--disable-smart-shrinking ");

                if (!string.IsNullOrEmpty(document.HeaderUrl))
                {
                    sbdParams.Append("--header-html ").Append(document.HeaderUrl).Append(" --margin-top 25 ")
                    .Append("--margin-top 25 ").Append("--header-spacing 5 ");
                }

                if (!string.IsNullOrEmpty(document.FooterUrl))
                {
                    sbdParams.Append("--footer-html ").Append(document.FooterUrl).Append(" --margin-bottom 25 ")
                    .Append("--footer-spacing 5 ");
                }

                if (!string.IsNullOrEmpty(document.HeaderLeft))
                {
                    sbdParams.Append("--header-left \"").Append(document.HeaderLeft).Append("\" ");
                }

                if (!string.IsNullOrEmpty(document.HeaderCenter))
                {
                    sbdParams.Append("--header-center \"").Append(document.HeaderCenter).Append("\" ");
                }

                if (!string.IsNullOrEmpty(document.HeaderRight))
                {
                    sbdParams.Append("--header-right \"").Append(document.HeaderRight).Append("\" ");
                }

                if (!string.IsNullOrEmpty(document.FooterLeft))
                {
                    sbdParams.Append("--footer-left \"").Append(document.FooterLeft).Append("\" ");
                }

                if (!string.IsNullOrEmpty(document.FooterCenter))
                {
                    sbdParams.Append("--footer-center \"").Append(document.FooterCenter).Append("\" ");
                }

                if (!string.IsNullOrEmpty(document.FooterRight))
                {
                    sbdParams.Append("--footer-right \"").Append(document.FooterRight).Append("\" ");
                }

                if (!string.IsNullOrEmpty(document.HeaderFontSize))
                {
                    sbdParams.Append("--header-font-size \"").Append(document.HeaderFontSize).Append("\" ");
                }

                if (!string.IsNullOrEmpty(document.FooterFontSize))
                {
                    sbdParams.Append("--footer-font-size \"").Append(document.FooterFontSize).Append("\" ");
                }

                if (!string.IsNullOrEmpty(document.HeaderFontName))
                {
                    sbdParams.Append("--header-font-name \"").Append(document.HeaderFontName).Append("\" ");
                }

                if (!string.IsNullOrEmpty(document.FooterFontName))
                {
                    sbdParams.Append("--footer-font-name \"").Append(document.FooterFontName).Append("\" ");
                }

                if (document.ExtraParams != null)
                {
                    foreach (KeyValuePair <string, string> extraParam in document.ExtraParams)
                    {
                        sbdParams.Append("--").Append(extraParam.Key).Append(' ').Append(extraParam.Value)
                        .Append(' ');
                    }
                }

                if (document.Cookies != null)
                {
                    foreach (KeyValuePair <string, string> cookie in document.Cookies)
                    {
                        sbdParams.Append("--cookie ").Append(cookie.Key).Append(' ').Append(cookie.Value)
                        .Append(' ');
                    }
                }

                sbdParams.Append('\"').Append(document.Url).Append("\" \"").Append(outputPdfFilePath).Append('\"');
                strParams = sbdParams.ToString();
            }

            try
            {
                using (Process process = new Process {
                    EnableRaisingEvents = true
                })
                {
                    process.StartInfo.FileName               = environment.WkHtmlToPdfPath;
                    process.StartInfo.Arguments              = strParams;
                    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))
                            using (new FetchSafelyFromPool <StringBuilder>(Utils.StringBuilderPool,
                                                                           out StringBuilder output))
                                using (new FetchSafelyFromPool <StringBuilder>(Utils.StringBuilderPool,
                                                                               out StringBuilder error))
                                {
                                    void OutputHandler(object sender, DataReceivedEventArgs e)
                                    {
                                        if (e.Data == null)
                                        {
                                            // ReSharper disable once AccessToDisposedClosure
                                            outputWaitHandle.Set();
                                        }
                                        else
                                        {
                                            output.AppendLine(e.Data);
                                        }
                                    }

                                    void ErrorHandler(object sender, DataReceivedEventArgs e)
                                    {
                                        if (e.Data == null)
                                        {
                                            // ReSharper disable once AccessToDisposedClosure
                                            errorWaitHandle.Set();
                                        }
                                        else
                                        {
                                            error.AppendLine(e.Data);
                                        }
                                    }

                                    process.OutputDataReceived += OutputHandler;
                                    process.ErrorDataReceived  += ErrorHandler;

                                    Task <int> tskAsyncProcess = null;
                                    try
                                    {
                                        using (CancellationTokenSource objCancellationTokenSource
                                                   = new CancellationTokenSource(environment.Timeout))
                                        {
                                            CancellationToken objToken = objCancellationTokenSource.Token;
                                            if (blnSync)
                                            {
                                                process.Start();
                                            }
                                            else
                                            {
#pragma warning disable AsyncFixer04 // Fire-and-forget async call inside a using block
                                                tskAsyncProcess = process.StartAsync(objToken);
#pragma warning restore AsyncFixer04 // Fire-and-forget async call inside a using block
                                            }

                                            process.BeginOutputReadLine();
                                            process.BeginErrorReadLine();

                                            if (document.Html != null)
                                            {
                                                using (StreamWriter stream = process.StandardInput)
                                                {
                                                    byte[] buffer = Encoding.UTF8.GetBytes(document.Html);
                                                    if (blnSync)
                                                    {
                                                        // ReSharper disable once MethodHasAsyncOverloadWithCancellation
                                                        stream.BaseStream.Write(buffer, 0, buffer.Length);
                                                        // ReSharper disable once MethodHasAsyncOverload
                                                        stream.WriteLine();
                                                    }
                                                    else
                                                    {
                                                        try
                                                        {
                                                            await stream.BaseStream.WriteAsync(buffer, 0, buffer.Length, objToken);

                                                            await stream.WriteLineAsync();
                                                        }
                                                        catch (OperationCanceledException)
                                                        {
                                                            // Swallow this
                                                        }
                                                    }
                                                }
                                            }

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

                                                    throw new PdfConvertTimeoutException();
                                                }
                                            }
                                            else
                                            {
                                                int intTaskResult = await tskAsyncProcess;
                                                if (tskAsyncProcess.IsCompleted && !objToken.IsCancellationRequested)
                                                {
                                                    if (intTaskResult != 0 && !File.Exists(outputPdfFilePath))
                                                    {
                                                        throw new PdfConvertException(
                                                                  $"Html to PDF conversion of '{document.Url}' failed. Wkhtmltopdf output: \r\n{error}");
                                                    }
                                                }
                                                else
                                                {
                                                    if (!process.HasExited)
                                                    {
                                                        process.Kill();
                                                    }

                                                    throw new PdfConvertTimeoutException();
                                                }
                                            }
                                        }
                                    }
                                    finally
                                    {
                                        process.OutputDataReceived -= OutputHandler;
                                        process.ErrorDataReceived  -= ErrorHandler;
                                        tskAsyncProcess?.Dispose();
                                    }
                                }
                }

                if (woutput.OutputStream != null)
                {
                    using (FileStream fs = new FileStream(outputPdfFilePath, FileMode.Open))
                    {
                        byte[] buffer = ArrayPool <byte> .Shared.Rent(32 * 1024);

                        int read;

                        if (blnSync)
                        {
                            // ReSharper disable once MethodHasAsyncOverload
                            while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                // ReSharper disable once MethodHasAsyncOverload
                                woutput.OutputStream.Write(buffer, 0, read);
                            }
                        }
                        else
                        {
                            while ((read = await fs.ReadAsync(buffer, 0, buffer.Length)) > 0)
                            {
                                await woutput.OutputStream.WriteAsync(buffer, 0, read);
                            }
                        }

                        ArrayPool <byte> .Shared.Return(buffer);
                    }
                }

                if (woutput.OutputCallback != null)
                {
                    byte[] pdfFileBytes = File.ReadAllBytes(outputPdfFilePath);
                    woutput.OutputCallback(document, pdfFileBytes);
                }
            }
            finally
            {
                if (delete)
                {
                    if (blnSync)
                    {
                        // ReSharper disable once MethodHasAsyncOverload
                        Utils.SafeDeleteFile(outputPdfFilePath, true);
                    }
                    else
                    {
                        await Utils.SafeDeleteFileAsync(outputPdfFilePath, true);
                    }
                }
            }
        }
        public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
        {
            if (document.Url == "-" && document.Html == null)
                throw new PdfConvertException(
                    String.Format("You must supply a HTML string, if you have enterd the url: {0}", document.Url)
                );

            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));

            StringBuilder paramsBuilder = new StringBuilder();
            paramsBuilder.Append("--page-size A4 ");

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

            if (!string.IsNullOrEmpty(document.HeaderLeft))
                paramsBuilder.AppendFormat("--header-left \"{0}\" ", document.HeaderLeft);

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

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

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

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

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

            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.WkHtmlToPdfPath;
                    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 (document.Html != null)
                            {
                                using (var stream = process.StandardInput)
                                {
                                    byte[] buffer = Encoding.UTF8.GetBytes(document.Html);
                                    stream.BaseStream.Write(buffer, 0, buffer.Length);
                                    stream.WriteLine();
                                }
                            }

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

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

                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)
                {
                    byte[] pdfFileBytes = File.ReadAllBytes(outputPdfFilePath);
                    woutput.OutputCallback(document, pdfFileBytes);
                }

            }
            finally
            {
                if (delete && File.Exists(outputPdfFilePath))
                    File.Delete(outputPdfFilePath);
            }
        }
Exemplo n.º 10
0
 public static Task ConvertHtmlToPdfAsync(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
 {
     return(ConvertHtmlToPdfCoreAsync(false, document, environment, woutput));
 }
Exemplo n.º 11
0
 public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
 {
     ConvertHtmlToPdfCoreAsync(true, document, environment, woutput).GetAwaiter().GetResult();
 }
Exemplo n.º 12
0
        /// <summary>
        /// Converts one or more HTML pages into a PDF document.
        /// </summary>
        /// <param name="document">Document definitions.</param>
        /// <param name="environment">Environment definitions.</param>
        /// <param name="woutput">Output definitions.</param>
        public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
        {
            if ((document.Pages == null) || (document.Pages.Count == 0))
            {
                throw new PdfConvertException("You must supply at least one page");
            }

            if (document.Pages.OfType <PdfPage>().Any(p => string.IsNullOrEmpty(p.Html)))
            {
                throw new PdfConvertException("You must supply a HTML string or a URL for all pages");
            }

            if (document.Pages.OfType <PdfCover>().Any(p => string.IsNullOrEmpty(p.Html)))
            {
                throw new PdfConvertException("You must supply a HTML string or a URL for all cover pages");
            }

            if (environment == null)
            {
                environment = new PdfConvertEnvironment();
            }

            if (!environment.Timeout.HasValue)
            {
                environment.Timeout = 60000;
            }

            if (string.IsNullOrEmpty(environment.TempFolderPath))
            {
                environment.TempFolderPath = Path.GetTempPath();
            }

            if (string.IsNullOrEmpty(environment.WkHtmlToPdfPath))
            {
                environment.WkHtmlToPdfPath = GetWkhtmlToPdfExeLocation();
            }

            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;
            }

            // Se for um caminho completo verifica se o executável existe, do contrário considera que ele estará no PATH para rodar corretamente
            if ((environment.WkHtmlToPdfPath.IndexOf(@"\", StringComparison.CurrentCulture) >= 0) && (!File.Exists(environment.WkHtmlToPdfPath)))
            {
                throw new PdfConvertException(string.Format("File '{0}' not found. Check if wkhtmltopdf application is installed.", environment.WkHtmlToPdfPath));
            }

            StringBuilder  paramsBuilder = new StringBuilder();
            WorkEnviroment workEnv       = new WorkEnviroment()
            {
                TempFolderPath = environment.TempFolderPath
            };

            document.GetCmdArguments(paramsBuilder, workEnv);
            paramsBuilder.AppendFormat("\"{0}\" ", outputPdfFilePath);

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

                using (Process process = new Process())
                {
                    process.StartInfo.FileName               = environment.WkHtmlToPdfPath;
                    process.StartInfo.Arguments              = paramsBuilder.ToString().TrimEnd();
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError  = true;
                    process.StartInfo.RedirectStandardInput  = true;
                    process.StartInfo.WorkingDirectory       = AppDomain.CurrentDomain.BaseDirectory;

                    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;

                            Debug.Print("Converting to PDF: {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
                            try
                            {
                                process.Start();

                                process.BeginOutputReadLine();
                                process.BeginErrorReadLine();

                                //TODO:Usar parâmetro --read-args-from-stdin para otimizar geração de vários PDFs em processo batch
                                if (workEnv.StdinArguments.Count > 0) // Se precisa passar algum HTML por stdin
                                {
                                    using (var stream = process.StandardInput)
                                    {
                                        workEnv.StdinArguments.ForEach(input =>
                                        {
                                            byte[] buffer = Encoding.UTF8.GetBytes(input);
                                            stream.BaseStream.Write(buffer, 0, buffer.Length);
                                            stream.WriteLine();
                                        });
                                    }
                                }
                                ;

                                if (process.WaitForExit(environment.Timeout.Value) && outputWaitHandle.WaitOne(environment.Timeout.Value) && errorWaitHandle.WaitOne(environment.Timeout.Value))
                                {
                                    if (process.ExitCode != 0 && !File.Exists(outputPdfFilePath))
                                    {
                                        throw new PdfConvertException(string.Format("Html to PDF conversion failed. Wkhtmltopdf output: \r\n{0}\r\nCommand line: {1} {2}", error, process.StartInfo.FileName, process.StartInfo.Arguments));
                                    }
                                }
                                else
                                {
                                    if (!process.HasExited)
                                    {
                                        process.Kill();
                                    }

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

                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)
                {
                    byte[] pdfFileBytes = File.ReadAllBytes(outputPdfFilePath);
                    woutput.OutputCallback(document, pdfFileBytes);
                }
            }
            finally
            {
                if (delete && File.Exists(outputPdfFilePath))
                {
                    File.Delete(outputPdfFilePath);
                }

                foreach (var tmpFile in workEnv.TempFiles)
                {
                    if (File.Exists(tmpFile))
                    {
                        File.Delete(tmpFile);
                    }
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Converts a PdfDocument object from HTML to PDf.
        /// </summary>
        /// <param name="document">The PDF input document.</param>
        /// <param name="environment">The wkhtml enviromental settings object.</param>
        /// <param name="woutput">An object holding the output settings.</param>
        public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
        {
            if (IsEmptyUrl(document.Url) && string.IsNullOrEmpty(document.Html))
                throw new PdfConvertException(
                    String.Format("You must supply a HTML string, if you have entered the url: {0}",
                        document.Url)
                );

            if (!IsEmptyUrl(document.Url))
                if (!Uri.IsWellFormedUriString(document.Url, UriKind.Absolute))
                    throw new PdfConvertException(
                        String.Format("This is not a valid url: {0}", document.Url)
                    );

            if (environment == null)
                environment = Environment;

            if (!File.Exists(environment.WkHtmlToPdfPath))
                throw new PdfConvertException(
                    String.Format("File '{0}' not found. Check if wkhtmltopdf application is installed.",
                        environment.WkHtmlToPdfPath));

            string PdfOutputPath;
            if (string.IsNullOrEmpty(woutput.OutputFilePath))
                PdfOutputPath = Path.Combine(Environment.TempFolderPath, Guid.NewGuid().ToString());
            else
                PdfOutputPath = woutput.OutputFilePath;

            var error = new StringBuilder();

            using (Process process = new Process())
            {
                process.StartInfo.FileName = environment.WkHtmlToPdfPath;
                process.StartInfo.Arguments = BuildParams(document, PdfOutputPath);
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardInput = true;

                using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                {
                    process.ErrorDataReceived += (DataReceivedEventHandler)((sender, e) =>
                    {
                        if (e.Data == null)
                            errorWaitHandle.Set();
                        else
                        {
                            error.AppendLine(e.Data);
                        }
                    });
                    process.Start();
                    process.BeginErrorReadLine();

                    if (document.Html != null && IsEmptyUrl(document.Url))
                        using (var stream = process.StandardInput)
                            stream.Write(document.Html);

                    if (process.WaitForExit(environment.Timeout) && errorWaitHandle.WaitOne(environment.Timeout))
                    {
                        if (process.ExitCode != 0)
                            throw new PdfConvertException(
                                String.Format("Html to PDF conversion of document failed. Wkhtmltopdf output: \r\n{1}",
                                document.Url, error));
                        else
                        {
                            if (woutput.OutputStream != null || woutput.OutputCallback != null)
                            {
                                byte[] buff = File.ReadAllBytes(PdfOutputPath);

                                if (woutput.OutputStream != null)
                                    woutput.OutputStream.Write(buff, 0, buff.Length);
                                if (woutput.OutputCallback != null)
                                    woutput.OutputCallback(document, buff);
                            }
                        }
                    }
                    else
                    {
                        if (!process.HasExited)
                            process.Kill();

                        throw new PdfConvertTimeoutException();
                    }

                    if (woutput.OutputFilePath == null)
                        File.Delete(PdfOutputPath);
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Converts a PdfDocument object from HTML to PDf.
        /// </summary>
        /// <param name="document">The PDF input document.</param>
        /// <param name="environment">The wkhtml enviromental settings object.</param>
        /// <param name="woutput">An object holding the output settings.</param>
        public static void ConvertHtmlToPdf(PdfDocument document, PdfConvertEnvironment environment, PdfOutput woutput)
        {
            if (IsEmptyUrl(document.Url) && string.IsNullOrEmpty(document.Html))
            {
                throw new PdfConvertException(
                          String.Format("You must supply a HTML string, if you have entered the url: {0}",
                                        document.Url)
                          );
            }

            if (!IsEmptyUrl(document.Url))
            {
                if (!Uri.IsWellFormedUriString(document.Url, UriKind.Absolute))
                {
                    throw new PdfConvertException(
                              String.Format("This is not a valid url: {0}", document.Url)
                              );
                }
            }

            if (environment == null)
            {
                environment = Environment;
            }

            if (!File.Exists(environment.WkHtmlToPdfPath))
            {
                throw new PdfConvertException(
                          String.Format("File '{0}' not found. Check if wkhtmltopdf application is installed.",
                                        environment.WkHtmlToPdfPath));
            }

            string PdfOutputPath;

            if (string.IsNullOrEmpty(woutput.OutputFilePath))
            {
                PdfOutputPath = Path.Combine(Environment.TempFolderPath, Guid.NewGuid().ToString());
            }
            else
            {
                PdfOutputPath = woutput.OutputFilePath;
            }

            var error = new StringBuilder();

            using (Process process = new Process())
            {
                process.StartInfo.FileName              = environment.WkHtmlToPdfPath;
                process.StartInfo.Arguments             = BuildParams(document, PdfOutputPath);
                process.StartInfo.UseShellExecute       = false;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardInput = true;

                using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                {
                    process.ErrorDataReceived += (DataReceivedEventHandler)((sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            error.AppendLine(e.Data);
                        }
                    });
                    process.Start();
                    process.BeginErrorReadLine();

                    if (document.Html != null && IsEmptyUrl(document.Url))
                    {
                        using (var stream = process.StandardInput)
                            stream.Write(document.Html);
                    }

                    if (process.WaitForExit(environment.Timeout) && errorWaitHandle.WaitOne(environment.Timeout))
                    {
                        if (process.ExitCode != 0)
                        {
                            throw new PdfConvertException(
                                      String.Format("Html to PDF conversion of document failed. Wkhtmltopdf output: \r\n{1}",
                                                    document.Url, error));
                        }
                        else
                        {
                            if (woutput.OutputStream != null || woutput.OutputCallback != null)
                            {
                                byte[] buff = File.ReadAllBytes(PdfOutputPath);

                                if (woutput.OutputStream != null)
                                {
                                    woutput.OutputStream.Write(buff, 0, buff.Length);
                                }
                                if (woutput.OutputCallback != null)
                                {
                                    woutput.OutputCallback(document, buff);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (!process.HasExited)
                        {
                            process.Kill();
                        }

                        throw new PdfConvertTimeoutException();
                    }

                    if (woutput.OutputFilePath == null)
                    {
                        File.Delete(PdfOutputPath);
                    }
                }
            }
        }