コード例 #1
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
        internal override void GetCmdArguments(StringBuilder paramsBuilder, WorkEnviroment workEnv)
        {
            paramsBuilder.AddArgument(this.Collate, "no-collate", "collate");
            paramsBuilder.AddArgument(this.CookieJar, "cookie-jar");
            paramsBuilder.AddArgument(this.Copies, "copies");
            paramsBuilder.AddArgument(this.Dpi, "dpi");
            paramsBuilder.AddArgument(this.Grayscale, "", "grayscale");
            paramsBuilder.AddArgument(this.ImageDpi, "image-dpi");
            paramsBuilder.AddArgument(this.ImageQuality, "image-quality");
            paramsBuilder.AddArgument(this.LowQuality, "", "lowquality");
            paramsBuilder.AddArgument(this.MarginBottom, "margin-bottom");
            paramsBuilder.AddArgument(this.MarginLeft, "margin-left");
            paramsBuilder.AddArgument(this.MarginRight, "margin-right");
            paramsBuilder.AddArgument(this.MarginTop, "margin-top");
            if (this.Landscape.HasValue)
            {
                paramsBuilder.AddArgument(this.Landscape, "orientation Portrait", "orientation Landscape");
            }
            paramsBuilder.AddArgument(this.PageHeight, "page-height");
            paramsBuilder.AddArgument(this.PageSize, "page-size");
            paramsBuilder.AddArgument(this.PageWidth, "page-width");
            paramsBuilder.AddArgument(this.PdfCompression, "no-pdf-compression", "");
            paramsBuilder.AddArgument(this.Title, "title");
            paramsBuilder.AddArgument(this.Outline, "no-outline", "outline");
            paramsBuilder.AddArgument(this.OutlineDepth, "outline-depth");

            if (Options != null)
            {
                Options.GetCmdArguments(paramsBuilder, workEnv);
            }

            this.Pages.ForEach(obj => obj.GetCmdArguments(paramsBuilder, workEnv));
        }
コード例 #2
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
        internal override void GetCmdArguments(StringBuilder paramsBuilder, WorkEnviroment workEnv)
        {
            paramsBuilder.Append("cover ");
            paramsBuilder.AddInputArgument(this.Html, workEnv, ".html", ForceHtmlAsContent);

            if (Options != null)
            {
                Options.GetCmdArguments(paramsBuilder, workEnv);
            }
        }
コード例 #3
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
 internal void GetCmdArguments(StringBuilder paramsBuilder, string prefix, WorkEnviroment workEnv)
 {
     paramsBuilder.AddArgument(this.Center, prefix + "-center");
     paramsBuilder.AddArgument(this.FontName, prefix + "-font-name");
     paramsBuilder.AddArgument(this.FontSize, prefix + "-font-size");
     paramsBuilder.AddUrlArgument(this.Html, workEnv, prefix + "-html", ".html");
     paramsBuilder.AddArgument(this.Left, prefix + "-left");
     paramsBuilder.AddArgument(this.Line, "no-" + prefix + "-line", prefix + "-line");
     paramsBuilder.AddArgument(this.Right, prefix + "-right");
     paramsBuilder.AddArgument(this.Spacing, prefix + "-spacing");
     paramsBuilder.AddArgument(this.Replace, "replace");
 }
コード例 #4
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
 internal void GetCmdArguments(StringBuilder paramsBuilder, WorkEnviroment workEnv)
 {
     paramsBuilder.AddArgument(this.Allow, "allow");
     paramsBuilder.AddArgument(this.Background, "no-background", "background");
     paramsBuilder.AddArgument(this.BypassProxyFor, "bypass-proxy-for");
     paramsBuilder.AddArgument(this.CacheDir, "cache-dir");
     paramsBuilder.AddArgument(this.CheckboxCheckedSvg, "checkbox-checked-svg");
     paramsBuilder.AddArgument(this.CheckboxSvg, "checkbox-svg");
     paramsBuilder.AddArgument(this.Cookies, "cookie");
     paramsBuilder.AddArgument(this.CustomHeader, "custom-header");
     paramsBuilder.AddArgument(this.CustomHeaderPropagation, "no-custom-header-propagation", "custom-header-propagation");
     paramsBuilder.AddArgument(this.DebugJavascript, "no-debug-javascript", "debug-javascript");
     paramsBuilder.AddArgument(this.DefaultHeader, "", "default-header");
     paramsBuilder.AddArgument(this.Encoding, "encoding");
     paramsBuilder.AddArgument(this.EnableExternalLinks, "disable-external-links", "enable-external-links");
     paramsBuilder.AddArgument(this.EnableForms, "disable-forms", "enable-forms");
     paramsBuilder.AddArgument(this.Images, "no-images", "images");
     paramsBuilder.AddArgument(this.EnableInternalLinks, "disable-internal-links", "enable-internal-links");
     paramsBuilder.AddArgument(this.EnableJavascript, "disable-javascript", "enable-javascript");
     paramsBuilder.AddArgument(this.JavascriptDelay, "javascript-delay");
     paramsBuilder.AddArgument(this.LoadErrorHandling, "load-error-handling");
     paramsBuilder.AddArgument(this.LoadMediaErrorHandling, "load-media-error-handling");
     paramsBuilder.AddArgument(this.EnableLocalFileAccess, "disable-local-file-access", "enable-local-file-access");
     paramsBuilder.AddArgument(this.MinimumFontSize, "minimum-font-size");
     paramsBuilder.AddArgument(this.IncludeInOutline, "exclude-from-outline", "include-in-outline");
     paramsBuilder.AddArgument(this.PageOffset, "page-offset");
     paramsBuilder.AddArgument(this.Password, "password");
     paramsBuilder.AddArgument(this.EnablePlugins, "disable-plugins", "enable-plugins");
     paramsBuilder.AddArgument(this.Post, "post");
     paramsBuilder.AddArgument(this.PostFile, "post-file");
     paramsBuilder.AddArgument(this.PrintMediaType, "no-print-media-type", "print-media-type");
     paramsBuilder.AddArgument(this.Proxy, "proxy");
     paramsBuilder.AddArgument(this.RadiobuttonCheckedSvg, "radiobutton-checked-svg");
     paramsBuilder.AddArgument(this.RadiobuttonSvg, "radiobutton-svg");
     paramsBuilder.AddArgument(this.ResolveRelativeLinks, "keep-relative-links", "resolve-relative-links");
     paramsBuilder.AddArgument(this.RunScript, "run-script");
     paramsBuilder.AddArgument(this.EnableSmartShrinking, "disable-smart-shrinking", "enable-smart-shrinking");
     paramsBuilder.AddArgument(this.StopSlowScripts, "no-stop-slow-scripts", "stop-slow-scripts");
     paramsBuilder.AddArgument(this.EnableTocBackLinks, "disable-toc-back-links", "enable-toc-back-links");
     paramsBuilder.AddUrlArgument(this.UserStyleSheet, workEnv, "user-style-sheet", ".css");
     paramsBuilder.AddArgument(this.Username, "username");
     paramsBuilder.AddArgument(this.ViewportSize, "viewport-size");
     paramsBuilder.AddArgument(this.WindowStatus, "window-status");
     paramsBuilder.AddArgument(this.Zoom, "zoom");
 }
コード例 #5
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
        internal override void GetCmdArguments(StringBuilder paramsBuilder, WorkEnviroment workEnv)
        {
            paramsBuilder.AddInputArgument(this.Html, workEnv, ".html", ForceHtmlAsContent);

            if (Options != null)
            {
                Options.GetCmdArguments(paramsBuilder, workEnv);
            }

            if (Header != null)
            {
                Header.GetCmdArguments(paramsBuilder, "header", workEnv);
            }

            if (Footer != null)
            {
                Footer.GetCmdArguments(paramsBuilder, "footer", workEnv);
            }
        }
コード例 #6
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
        internal override void GetCmdArguments(StringBuilder paramsBuilder, WorkEnviroment workEnv)
        {
            paramsBuilder.Append("toc ");
            paramsBuilder.AddArgument(this.DottedLines, "disable-dotted-lines", "");
            paramsBuilder.AddArgument(this.HeaderText, "toc-header-text");
            paramsBuilder.AddArgument(this.LevelIndentation, "toc-level-indentation");
            paramsBuilder.AddArgument(this.Links, "disable-toc-links", "");
            paramsBuilder.AddArgument(this.TextSizeShrink, "toc-text-size-shrink");
            paramsBuilder.AddFileArgument(this.XslStyleSheet, workEnv, "xsl-style-sheet", ".xslt");

            if (Header != null)
            {
                Header.GetCmdArguments(paramsBuilder, "header", workEnv);
            }

            if (Footer != null)
            {
                Footer.GetCmdArguments(paramsBuilder, "footer", workEnv);
            }
        }
コード例 #7
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
        /// <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);
                    }
                }
            }
        }
コード例 #8
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
 internal abstract void GetCmdArguments(StringBuilder paramsBuilder, WorkEnviroment workEnv);
コード例 #9
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
 internal static void AddUrlArgument(this StringBuilder builder, string value, WorkEnviroment workEnv, string paramName, string fileExt)
 {
     AddArgument(builder, value, paramName, workEnv, false, fileExt);
 }
コード例 #10
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
        private static void AddArgument(this StringBuilder builder, string value, string paramName, WorkEnviroment workEnv, bool forceHtmlAsContent, string fileExt)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (!string.IsNullOrEmpty(paramName))
                {
                    builder.AppendFormat("--{0} ", paramName);
                }

                if (!forceHtmlAsContent && value.IsUrlOrFilePath())
                {
                    builder.Append(value + " ");
                }
                else
                {
                    //builder.Append("- "); //Extraído de: http://stackoverflow.com/questions/21864382/is-there-any-wkhtmltopdf-option-to-convert-html-text-rather-than-file
                    //workEnv.StdinArguments.Add(value);

                    //if ((fileExt.ToLower(System.Globalization.CultureInfo.CurrentCulture) == ".html") && (!value.StartsWith("<!DOCTYPE html>", true, System.Globalization.CultureInfo.CurrentCulture)))
                    //    value = "<!DOCTYPE html>" + value; // Necessário para funcionar

                    value = workEnv.CreateTempFile(value, fileExt);
                    builder.AppendFormat("\"{0}\" ", value);
                };
            }
        }
コード例 #11
0
ファイル: PdfConvert.cs プロジェクト: ajsjunior/wkhtmltopdf-1
 internal static void AddInputArgument(this StringBuilder builder, string value, WorkEnviroment workEnv, string fileExt, bool forceHtmlAsContent)
 {
     AddArgument(builder, value, null, workEnv, forceHtmlAsContent, fileExt);
 }