Esempio n. 1
0
//		[Ignore("This test requires (still to be released) wkhtmltopdf v0.12+")]
        public void CanHandleAuthFailure()
        {
            using (var wk = new MultiplexingConverter())
            {
                var failed = false;

                wk.GlobalSettings.Margin.Top    = "0cm";
                wk.GlobalSettings.Margin.Bottom = "0cm";
                wk.GlobalSettings.Margin.Left   = "0cm";
                wk.GlobalSettings.Margin.Right  = "0cm";

                wk.ObjectSettings.Load.Proxy             = "none";
                wk.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.abort;
                wk.ObjectSettings.Load.StopSlowScripts   = true;

                wk.ObjectSettings.Web.EnablePlugins    = false;
                wk.ObjectSettings.Web.EnableJavascript = false;

                wk.ObjectSettings.Page = @"http://192.236.37.129/";                 // Some misg site requiring HTTP Basic auth.

                wk.Begin           += (s, e) => { Console.WriteLine("==>> Begin: {0}", e.Value); };
                wk.PhaseChanged    += (s, e) => { Console.WriteLine("==>> New Phase: {0} ({1})", e.Value, e.Value2); };
                wk.ProgressChanged += (s, e) => { Console.WriteLine("==>> Progress: {0} ({1})", e.Value, e.Value2); };
                wk.Error           += (s, e) => {
                    failed = true;
                    Console.WriteLine("==>> ERROR: {0}", e.Value);
                };
                wk.Finished += (s, e) => { Console.WriteLine("==>> WARN: {0}", e.Value); };

                var tmp = wk.Convert();

                Assert.IsNotNull(tmp);
                Assert.IsTrue(failed);
            }
        }
        public void CanHandleAuthFailure()
        {
            using (var wk = new MultiplexingConverter())
            {
                var failed = false;

                wk.GlobalSettings.Margin.Top = "0cm";
                wk.GlobalSettings.Margin.Bottom = "0cm";
                wk.GlobalSettings.Margin.Left = "0cm";
                wk.GlobalSettings.Margin.Right = "0cm";

                wk.ObjectSettings.Load.Proxy = "none";
                wk.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.abort;
                wk.ObjectSettings.Load.StopSlowScripts = true;

                wk.ObjectSettings.Web.EnablePlugins = false;
                wk.ObjectSettings.Web.EnableJavascript = false;

                wk.ObjectSettings.Page = @"http://192.236.37.129/"; // Some misg site requiring HTTP Basic auth.

                wk.Begin += (s, e) => { Console.WriteLine("==>> Begin: {0}", e.Value); };
                wk.PhaseChanged += (s, e) => { Console.WriteLine("==>> New Phase: {0} ({1})", e.Value, e.Value2); };
                wk.ProgressChanged += (s, e) => { Console.WriteLine("==>> Progress: {0} ({1})", e.Value, e.Value2); };
                wk.Error += (s, e) => {
                    failed = true;
                    Console.WriteLine("==>> ERROR: {0}", e.Value);
                };
                wk.Finished += (s, e) => { Console.WriteLine("==>> WARN: {0}", e.Value); };

                var tmp = wk.Convert();

                Assert.IsNotNull(tmp);
                Assert.IsTrue(failed);
            }
        }
Esempio n. 3
0
        private MultiplexingConverter GetConverter()
        {
            var obj = new MultiplexingConverter();

            obj.Begin    += (s, e) => _log.DebugFormat("Conversion begin, phase count: {0}", e.Value);
            obj.Warning  += (s, e) => _log.Warn(e.Value);
            obj.Finished += (s, e) => _log.InfoFormat("Finished: {0}", e.Value ? "success" : "failed!");
            return(obj);
        }
Esempio n. 4
0
        private MultiplexingConverter _GetConverter()
        {
            var obj = new MultiplexingConverter();

            obj.Begin           += (s, e) => _Log.DebugFormat("Conversion begin, phase count: {0}", e.Value);
            obj.Error           += (s, e) => _Log.Error(e.Value);
            obj.Warning         += (s, e) => _Log.Warn(e.Value);
            obj.PhaseChanged    += (s, e) => _Log.InfoFormat("PhaseChanged: {0} - {1}", e.Value, e.Value2);
            obj.ProgressChanged += (s, e) => _Log.InfoFormat("ProgressChanged: {0} - {1}", e.Value, e.Value2);
            obj.Finished        += (s, e) => _Log.InfoFormat("Finished: {0}", e.Value ? "success" : "failed!");
            return(obj);
        }
 public void ConvertFromString()
 {
     using (var wk = new MultiplexingConverter())
     {
         using (var stream = new MemoryStream(Resources.SimplePage_xhtml))
         using (var sr = new StreamReader(stream))
         {
             var str = sr.ReadToEnd();
             var tmp = wk.Convert(str);
             Assert.IsNotEmpty(tmp);
         }
     }
 }
        private IHtmlToPdfConverter GetDefaultConverter(Action <IHtmlToPdfConverter> setUpAction = null)
        {
            var multiplexingConverter = new MultiplexingConverter();

            multiplexingConverter.ObjectSettings.Web.PrintMediaType = true;
            multiplexingConverter.GlobalSettings.Margin.Top         = "1.25cm";
            multiplexingConverter.GlobalSettings.Margin.Bottom      = "1.25cm";
            multiplexingConverter.GlobalSettings.Margin.Left        = "1.25cm";
            multiplexingConverter.GlobalSettings.Margin.Right       = "1.25cm";

            multiplexingConverter.ObjectSettings.Load.BlockLocalFileAccess = false;
            multiplexingConverter.ObjectSettings.Web.LoadImages            = true;
            multiplexingConverter.ObjectSettings.Web.PrintMediaType        = true;

            if (setUpAction != null)
            {
                setUpAction(multiplexingConverter);
            }
            return(multiplexingConverter);
        }
Esempio n. 7
0
        public byte[] Convert(string url)
        {
            using (var wk = new MultiplexingConverter())
            {
                wk.GlobalSettings.Margin.Top    = "0cm";
                wk.GlobalSettings.Margin.Bottom = "0cm";
                wk.GlobalSettings.Margin.Left   = "0cm";
                wk.GlobalSettings.Margin.Right  = "0cm";


                wk.ObjectSettings.Web.EnablePlugins    = false;
                wk.ObjectSettings.Web.EnableJavascript = false;
                wk.ObjectSettings.Page = url;

                wk.ObjectSettings.Load.Proxy = "none";

                var tmp = wk.Convert();
                return(tmp);
            }
        }
Esempio n. 8
0
        public static string Run(string pdfPath, string htmlFullPath, int pdfFontSize)
        {
            var htmlTemp = Path.Combine(new DirectoryInfo(htmlFullPath).Parent.FullName,
                                        Guid.NewGuid().ToString() + ".html");

            File.Copy(htmlFullPath, htmlTemp);
            var pdfUrl = pdfPath;

            try
            {
                #region USING WkHtmlToXSharp.dll

                // IHtmlToPdfConverter converter = new WkHtmlToPdfConverter();
                IHtmlToPdfConverter converter = new MultiplexingConverter();

                converter.GlobalSettings.Margin.Top    = "0cm";
                converter.GlobalSettings.Margin.Bottom = "0cm";
                converter.GlobalSettings.Margin.Left   = "0cm";
                converter.GlobalSettings.Margin.Right  = "0cm";

                converter.ObjectSettings.Page = htmlTemp;
                converter.ObjectSettings.Web.EnablePlugins      = true;
                converter.ObjectSettings.Web.EnableJavascript   = true;
                converter.ObjectSettings.Web.Background         = true;
                converter.ObjectSettings.Web.LoadImages         = true;
                converter.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.abort;
                converter.ObjectSettings.Web.MinimumFontSize    = pdfFontSize;
                Byte[] bufferPDF = converter.Convert();
                System.IO.File.WriteAllBytes(pdfUrl, bufferPDF);
                converter.Dispose();

                #endregion
            }
            catch (Exception ex) {
                File.Delete(htmlTemp);
                logger.Error(ex);
                return("error." + ex.Message);
            }
            File.Delete(htmlTemp);
            return("ok");
        }
Esempio n. 9
0
        public ReporterPDF(ReportData inputData, ref ReportNode rnRoot
                           , string templatePath, string outputFilePath)
        {
            // absolute output file path
            string absOutputFilePath;

            if (Path.IsPathRooted(outputFilePath))
            {
                absOutputFilePath = outputFilePath;
            }
            else
            {
                absOutputFilePath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), outputFilePath));
            }
            // absolute template path
            string absTemplatePath;

            if (Path.IsPathRooted(templatePath))
            {
                absTemplatePath = templatePath;
            }
            else
            {
                absTemplatePath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), templatePath));
            }

            // does output directory exists
            string outDir = Path.GetDirectoryName(absOutputFilePath);

            if (!Directory.Exists(outDir))
            {
                try { Directory.CreateDirectory(outDir); }
                catch (UnauthorizedAccessException /*ex*/)
                { throw new UnauthorizedAccessException(string.Format("User not allowed to write under {0}", Directory.GetParent(outDir).FullName)); }
                catch (Exception ex)
                { throw new Exception(string.Format("Directory {0} does not exist, and could not be created.", outDir), ex); }
            }
            // html file path
            string htmlFilePath = Path.ChangeExtension(absOutputFilePath, "html");

            BuildAnalysisReport(inputData, ref rnRoot, absTemplatePath, htmlFilePath);

            try
            {
                var ignore = Environment.GetEnvironmentVariable("WKHTMLTOXSHARP_NOBUNDLES");

                if (ignore == null || ignore.ToLower() != "true")
                {
                    // Register all available bundles
                    WkHtmlToXLibrariesManager.Register(new Win32NativeBundle());
                    WkHtmlToXLibrariesManager.Register(new Win64NativeBundle());
                }

                using (IHtmlToPdfConverter converter = new MultiplexingConverter())
                {
                    converter.GlobalSettings.Margin.Top    = "0cm";
                    converter.GlobalSettings.Margin.Bottom = "0cm";
                    converter.GlobalSettings.Margin.Left   = "0cm";
                    converter.GlobalSettings.Margin.Right  = "0cm";
                    converter.GlobalSettings.Orientation   = PdfOrientation.Portrait;
                    converter.GlobalSettings.Size.PageSize = PdfPageSize.A4;

                    converter.ObjectSettings.Page = htmlFilePath;
                    converter.ObjectSettings.Web.EnablePlugins      = true;
                    converter.ObjectSettings.Web.EnableJavascript   = true;
                    converter.ObjectSettings.Web.Background         = true;
                    converter.ObjectSettings.Web.LoadImages         = true;
                    converter.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.ignore;

                    byte[] bufferPDF = converter.Convert();
                    File.WriteAllBytes(absOutputFilePath, bufferPDF);
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
            }
        }
Esempio n. 10
0
        public void PrintTables(List <DataTable> aTables, List <string> aDetails, List <string> aFooter, string aLogoPath, string aFilePath, bool aIsThermal = false, bool print = false, bool savepdf = false, string pdfdir = "", bool saveexcel2003 = false, string excel2003dir = "", bool colored = false, bool ForceRTL = false)
        {
            try
            {
                DateTime StartTime = DateTime.Now;
                ExportToHTML(aTables, aDetails, aFooter, aFilePath, aIsThermal, (aIsThermal || ForceRTL) ? Reports.ReportsHelper.ReceiptRTL : Reports.ReportsHelper.RTL, colored);
                //Process p = new Process();
                if (print || savepdf)
                {
                    using (var sr = new StreamReader(aFilePath))
                    {
                        var str = sr.ReadToEnd();
                        sr.Close();
                        using (var wk = new MultiplexingConverter())
                        {
                            var tmp = wk.Convert(str);
                            if (print)
                            {
                                string PDFFilePath = aFilePath.Replace(".html", ".pdf");
                                File.WriteAllBytes(PDFFilePath, tmp);
                                PrintPDFs(PDFFilePath);
                            }
                            else if (savepdf)
                            {
                                pdfdir = pdfdir.Replace(".html", "");
                                File.WriteAllBytes(pdfdir, tmp);
                            }
                            wk.Dispose();
                        }
                    }
                    //p.StartInfo.FileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\wkhtmltopdf.exe";
                    //p.StartInfo.CreateNoWindow = true;
                    //p.StartInfo.UseShellExecute = false;
                    //if (print)
                    //{
                    //    p.StartInfo.Arguments = "-q \"" + aFilePath + "\" \"" + aFilePath + ".pdf\"";
                    //    p.Start();
                    //    p.WaitForExit(1000);
                    //    PrintPDFs(aFilePath + ".pdf");
                    //}
                    //else if (savepdf)
                    //{
                    //    p.StartInfo.Arguments = "\"" + aFilePath + "\" \"" + pdfdir + "\"";
                    //    p.Start();
                    //    p.WaitForExit();
                    //}
                }
                else if (saveexcel2003)
                {
                    System.IO.File.Copy(aFilePath, excel2003dir, true);
                }

                //TimeSpan ts = DateTime.Now.Subtract(StartTime);
                //string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                //        ts.Hours, ts.Minutes, ts.Seconds,
                //        ts.Milliseconds / 10);
                //MessageBox.Show("IncreaseBtn_Click=" + elapsedTime);
                File.Delete(aFilePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Printing Manager ERROR" + ex.Message + ex.ToString());
            }
        }
Esempio n. 11
0
 private MultiplexingConverter _GetConverter()
 {
     var obj = new MultiplexingConverter();
     obj.Begin += (s,e) => _Log.DebugFormat("Conversion begin, phase count: {0}", e.Value);
     obj.Error += (s, e) => _Log.Error(e.Value);
     obj.Warning += (s, e) => _Log.Warn(e.Value);
     obj.PhaseChanged += (s, e) => _Log.InfoFormat("PhaseChanged: {0} - {1}", e.Value, e.Value2);
     obj.ProgressChanged += (s, e) => _Log.InfoFormat("ProgressChanged: {0} - {1}", e.Value, e.Value2);
     obj.Finished += (s, e) => _Log.InfoFormat("Finished: {0}", e.Value ? "success" : "failed!");
     return obj;
 }
Esempio n. 12
0
        /// <summary>
        /// Generates documentation.
        /// </summary>
        /// <returns>The generation errors.</returns>
        public Model.GenerationError[] Generate(Configuration configuration)
        {
            // Initialize the list containing all generation errors
            List <Model.GenerationError> generationError = new List <Model.GenerationError>();

            // Ensure output directory exists
            if (!this.OutputDirectory.Exists)
            {
                this.OutputDirectory.Create();
            }

            // Process all pages
            List <Model.Page> pages = new List <Model.Page>();

            foreach (Page page in configuration.Pages)
            {
                // Compute the page id used as a tab id and page prefix for bookmarking
                string pageId = page.Path.Replace(".", string.Empty).Replace("/", string.Empty).Replace("\\", string.Empty);

                // Load the document
                Block document;

                // Process the page
                string pageFilePath = this.fileSystem.FileInfo.FromFileName(page.FileSystemPath).FullName;
                using (StreamReader reader = new StreamReader(this.fileSystem.File.Open(pageFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    document = CommonMarkConverter.ProcessStage1(reader);
                }

                // Process snippet
                CommonMarkConverter.ProcessStage2(document);
                Dictionary <Guid, Extension.Model.Snippet> snippetDictionary = new Dictionary <Guid, Extension.Model.Snippet>();
                foreach (var node in document.AsEnumerable())
                {
                    // Filter fenced code
                    if (node.Block != null && node.Block.Tag == BlockTag.FencedCode)
                    {
                        // Build extraction rule
                        string fencedCode = node.Block.FencedCodeData.Info;

                        // Do not trigger extraction if the fenced code is empty
                        if (string.IsNullOrWhiteSpace(fencedCode))
                        {
                            continue;
                        }

                        SnippetExtractionRule snippetExtractionRule = SnippetExtractionRule.Parse(fencedCode);

                        // Extract and inject snippet and the factory were able to create an extractor
                        if (null != snippetExtractionRule)
                        {
                            // Cleanup Projbook specific syntax
                            node.Block.FencedCodeData.Info = snippetExtractionRule.Language;

                            // Inject snippet
                            try
                            {
                                // Retrieve the extractor instance
                                ISnippetExtractor snippetExtractor;
                                if (!this.extractorCache.TryGetValue(snippetExtractionRule.TargetPath, out snippetExtractor))
                                {
                                    snippetExtractor = this.snippetExtractorFactory.CreateExtractor(snippetExtractionRule);
                                    this.extractorCache[snippetExtractionRule.TargetPath] = snippetExtractor;
                                }

                                // Look for the file in available source directories
                                FileSystemInfoBase  fileSystemInfo = null;
                                DirectoryInfoBase[] directoryInfos = null;
                                if (TargetType.FreeText != snippetExtractor.TargetType)
                                {
                                    directoryInfos = this.ExtractSourceDirectories(this.CsprojFile);
                                    foreach (DirectoryInfoBase directoryInfo in directoryInfos)
                                    {
                                        // Get directory name
                                        string directoryName = directoryInfo.FullName;
                                        if (1 == directoryName.Length && Path.DirectorySeparatorChar == directoryName[0])
                                        {
                                            directoryName = string.Empty;
                                        }

                                        // Compute file full path
                                        string fullFilePath = this.fileSystem.Path.GetFullPath(this.fileSystem.Path.Combine(directoryName, snippetExtractionRule.TargetPath ?? string.Empty));
                                        switch (snippetExtractor.TargetType)
                                        {
                                        case TargetType.File:
                                            if (this.fileSystem.File.Exists(fullFilePath))
                                            {
                                                fileSystemInfo = this.fileSystem.FileInfo.FromFileName(fullFilePath);
                                            }
                                            break;

                                        case TargetType.Folder:
                                            if (this.fileSystem.Directory.Exists(fullFilePath))
                                            {
                                                fileSystemInfo = this.fileSystem.DirectoryInfo.FromDirectoryName(fullFilePath);
                                            }
                                            break;
                                        }

                                        // Stop lookup if the file system info is found
                                        if (null != fileSystemInfo)
                                        {
                                            break;
                                        }
                                    }
                                }

                                // Raise an error if cannot find the file
                                if (null == fileSystemInfo && TargetType.FreeText != snippetExtractor.TargetType)
                                {
                                    // Locate block line
                                    int line = this.LocateBlockLine(node.Block, page);

                                    // Compute error column: Index of the path in the fenced code + 3 (for the ``` prefix) + 1 (to be 1 based)
                                    int column = fencedCode.IndexOf(snippetExtractionRule.TargetPath) + 4;

                                    // Report error
                                    generationError.Add(new Model.GenerationError(
                                                            sourceFile: page.Path,
                                                            message: string.Format("Cannot find target '{0}' in any referenced project ({0})", snippetExtractionRule.TargetPath, string.Join(";", directoryInfos.Select(x => x.FullName))),
                                                            line: line,
                                                            column: column));
                                    continue;
                                }

                                // Extract the snippet
                                Extension.Model.Snippet snippet =
                                    TargetType.FreeText == snippetExtractor.TargetType
                                    ? snippetExtractor.Extract(null, snippetExtractionRule.TargetPath)
                                    : snippetExtractor.Extract(fileSystemInfo, snippetExtractionRule.Pattern);

                                // Reference snippet
                                Guid guid = Guid.NewGuid();
                                snippetDictionary[guid] = snippet;

                                // Inject reference as content
                                StringContent code    = new StringContent();
                                string        content = SNIPPET_REFERENCE_PREFIX + guid;
                                code.Append(content, 0, content.Length);
                                node.Block.StringContent = code;

                                // Change tag to html for node snippets
                                NodeSnippet nodeSnippet = snippet as NodeSnippet;
                                if (null != nodeSnippet)
                                {
                                    node.Block.Tag = BlockTag.HtmlBlock;
                                }
                            }
                            catch (SnippetExtractionException snippetExtraction)
                            {
                                // Locate block line
                                int line = this.LocateBlockLine(node.Block, page);

                                // Compute error column: Fenced code length - pattern length + 3 (for the ``` prefix) + 1 (to be 1 based)
                                int column = fencedCode.Length - snippetExtractionRule.Pattern.Length + 4;

                                // Report error
                                generationError.Add(new Model.GenerationError(
                                                        sourceFile: page.Path,
                                                        message: string.Format("{0}: {1}", snippetExtraction.Message, snippetExtraction.Pattern),
                                                        line: line,
                                                        column: column));
                            }
                            catch (System.Exception exception)
                            {
                                generationError.Add(new Model.GenerationError(
                                                        sourceFile: page.Path,
                                                        message: exception.Message,
                                                        line: 0,
                                                        column: 0));
                            }
                        }
                    }
                }

                // Write to output
                ProjbookHtmlFormatter projbookHtmlFormatter = null;
                MemoryStream          documentStream        = new MemoryStream();
                using (StreamWriter writer = new StreamWriter(documentStream))
                {
                    // Setup custom formatter
                    CommonMarkSettings.Default.OutputDelegate = (d, o, s) => (projbookHtmlFormatter = new ProjbookHtmlFormatter(pageId, o, s, configuration.SectionTitleBase, snippetDictionary, SNIPPET_REFERENCE_PREFIX)).WriteDocument(d);

                    // Render
                    CommonMarkConverter.ProcessStage3(document, writer);
                }

                // Initialize the pre section content
                string preSectionContent = string.Empty;

                // Retrieve page content
                byte[] pageContent = documentStream.ToArray();

                // Set the whole page content if no page break is detected
                if (projbookHtmlFormatter.PageBreak.Length == 0)
                {
                    preSectionContent = System.Text.Encoding.UTF8.GetString(pageContent);
                }

                // Compute pre section content from the position 0 to the first page break position
                if (projbookHtmlFormatter.PageBreak.Length > 0 && projbookHtmlFormatter.PageBreak.First().Position > 0)
                {
                    preSectionContent = this.StringFromByteArray(pageContent, 0, projbookHtmlFormatter.PageBreak.First().Position);
                }

                // Build section list
                List <Model.Section> sections = new List <Model.Section>();
                for (int i = 0; i < projbookHtmlFormatter.PageBreak.Length; ++i)
                {
                    // Retrieve the current page break
                    PageBreakInfo pageBreak = projbookHtmlFormatter.PageBreak[i];

                    // Extract the content from the current page break to the next one if any
                    string content = null;
                    if (i < projbookHtmlFormatter.PageBreak.Length - 1)
                    {
                        PageBreakInfo nextBreak = projbookHtmlFormatter.PageBreak[1 + i];
                        content = this.StringFromByteArray(pageContent, pageBreak.Position, nextBreak.Position - pageBreak.Position);
                    }

                    // Otherwise extract the content from the current page break to the end of the content
                    else
                    {
                        content = this.StringFromByteArray(pageContent, pageBreak.Position, pageContent.Length - pageBreak.Position);
                    }

                    // Create a new section and add to the known list
                    sections.Add(new Model.Section(
                                     id: pageBreak.Id,
                                     level: pageBreak.Level,
                                     title: pageBreak.Title,
                                     content: content));
                }

                // Add new page
                pages.Add(new Model.Page(
                              id: pageId,
                              title: page.Title,
                              preSectionContent: preSectionContent,
                              sections: sections.ToArray()));
            }

            // Html generation
            if (configuration.GenerateHtml)
            {
                try
                {
                    string outputFileHtml = this.fileSystem.Path.Combine(this.OutputDirectory.FullName, configuration.OutputHtml);
                    this.GenerateFile(configuration.TemplateHtml, outputFileHtml, configuration, pages);
                }
                catch (TemplateParsingException templateParsingException)
                {
                    generationError.Add(new Model.GenerationError(configuration.TemplateHtml, string.Format("Error during HTML generation: {0}", templateParsingException.Message), templateParsingException.Line, templateParsingException.Column));
                }
                catch (System.Exception exception)
                {
                    generationError.Add(new Model.GenerationError(configuration.TemplateHtml, string.Format("Error during HTML generation: {0}", exception.Message), 0, 0));
                }
            }

            // Pdf generation
            if (configuration.GeneratePdf && !this.SkipPdf)
            {
                try
                {
                    // Generate the pdf template
                    string outputFileHtml = this.fileSystem.Path.Combine(this.OutputDirectory.FullName, configuration.OutputPdf);
                    this.GenerateFile(configuration.TemplatePdf, outputFileHtml, configuration, pages);

#if !NOPDF
                    // Compute file names
                    string outputPdf     = this.fileSystem.Path.ChangeExtension(configuration.OutputPdf, ".pdf");
                    string outputFilePdf = this.fileSystem.Path.Combine(this.OutputDirectory.FullName, outputPdf);

                    // Prepare the converter
                    MultiplexingConverter pdfConverter = new MultiplexingConverter();
                    pdfConverter.ObjectSettings.Page = outputFileHtml;
                    pdfConverter.Error += (s, e) => {
                        generationError.Add(new Model.GenerationError(configuration.TemplatePdf, string.Format("Error during PDF generation: {0}", e.Value), 0, 0));
                    };

                    // Prepare file system if abstracted
                    bool requireCopyToFileSystem = !File.Exists(outputFileHtml);
                    try
                    {
                        // File system may be abstracted, this requires to copy the pdf generation file to the actual file system
                        // in order to allow wkhtmltopdf to process the generated html as input file
                        if (requireCopyToFileSystem)
                        {
                            File.WriteAllBytes(outputFileHtml, this.fileSystem.File.ReadAllBytes(outputFileHtml));
                        }

                        // Run pdf converter
                        using (pdfConverter)
                            using (Stream outputFileStream = this.fileSystem.File.Open(outputFilePdf, FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                try
                                {
                                    byte[] buffer = pdfConverter.Convert();
                                    outputFileStream.Write(buffer, 0, buffer.Length);
                                }
                                catch
                                {
                                    // Ignore generation errors at that level
                                    // Errors are handled by the error handling having the best description
                                }
                            }
                    }
                    finally
                    {
                        if (requireCopyToFileSystem && File.Exists(outputFileHtml))
                        {
                            File.Delete(outputFileHtml);
                        }
                    }
#endif
                }
                catch (TemplateParsingException templateParsingException)
                {
                    generationError.Add(new Model.GenerationError(configuration.TemplatePdf, string.Format("Error during PDF generation: {0}", templateParsingException.Message), templateParsingException.Line, templateParsingException.Column));
                }
                catch (System.Exception exception)
                {
                    if (null != exception.InnerException && INCORRECT_FORMAT_HRESULT == exception.InnerException.HResult)
                    {
                        // Report detailed error message for wrong architecture loading
                        string runningArchitectureProccess      = IntPtr.Size == 8 ? "x64" : "x86";
                        string otherRunningArchitectureProccess = IntPtr.Size != 8 ? "x64" : "x86";
                        generationError.Add(new Model.GenerationError(configuration.TemplatePdf, string.Format("Error during PDF generation: Could not load wkhtmltopdf for {0}. Try again running as a {1} process.", runningArchitectureProccess, otherRunningArchitectureProccess), 0, 0));
                    }
                    else
                    {
                        // Report unknown error
                        generationError.Add(new Model.GenerationError(configuration.TemplatePdf, string.Format("Error during PDF generation: {0}", exception.Message), 0, 0));
                    }
                }
            }

            // Return the generation errors
            return(generationError.ToArray());
        }
        private void _SimpleConversion()
        {
            using (var wk = new MultiplexingConverter())
            {
                wk.GlobalSettings.Margin.Top = "0cm";
                wk.GlobalSettings.Margin.Bottom = "0cm";
                wk.GlobalSettings.Margin.Left = "0cm";
                wk.GlobalSettings.Margin.Right = "0cm";
                //wk.GlobalSettings.Out = @"c:\temp\tmp.pdf";

                wk.ObjectSettings.Web.EnablePlugins = false;
                wk.ObjectSettings.Web.EnableJavascript = false;
                wk.ObjectSettings.Page = SimplePageFile;
                //wk.ObjectSettings.Page = "http://doc.trolltech.com/4.6/qstring.html";
                wk.ObjectSettings.Load.Proxy = "none";

                var tmp = wk.Convert();

                Assert.IsNotEmpty(tmp);
                var number = 0;
                lock (this) number = count++;
                File.WriteAllBytes(@"c:\temp\tmp" + (number) + ".pdf", tmp);
            }
        }
Esempio n. 14
0
        protected byte[] CreatePdfFile(string page, string fileName, EnumPdfType source)
        {
            bool?isFailed;

            byte[] fileBytes;
            string _log = string.Empty;

            try
            {
                using (IHtmlToPdfConverter wkHtml = new MultiplexingConverter())
                {
                    isFailed = false;

                    wkHtml.GlobalSettings.Margin.Top    = "0cm";
                    wkHtml.GlobalSettings.Margin.Bottom = "0cm";
                    wkHtml.GlobalSettings.Margin.Left   = "0cm";
                    wkHtml.GlobalSettings.Margin.Right  = "0cm";

                    wkHtml.ObjectSettings.Load.Proxy             = "none";
                    wkHtml.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.ignore;
                    wkHtml.ObjectSettings.Load.StopSlowScripts   = false;
                    wkHtml.ObjectSettings.Load.Jsdelay           = 1000;

                    //Credentials
                    wkHtml.ObjectSettings.Load.Username = UserName;
                    wkHtml.ObjectSettings.Load.Password = Password;

                    wkHtml.ObjectSettings.Web.EnablePlugins    = true;
                    wkHtml.ObjectSettings.Web.EnableJavascript = true;

                    wkHtml.ObjectSettings.Page = page; // Some misg site requiring HTTP Basic auth.

                    wkHtml.Begin += (s, e) =>
                    {
                        _log += string.Format("==>> Begin: {0}\n", e.Value);
                        Console.WriteLine("==>> Begin: {0}", e.Value);
                    };
                    wkHtml.PhaseChanged += (s, e) =>
                    {
                        _log += string.Format("==>> New Phase: {0} ({1})\n", e.Value, e.Value2);
                        Console.WriteLine("==>> New Phase: {0} ({1})", e.Value, e.Value2);
                    };
                    wkHtml.ProgressChanged += (s, e) =>
                    {
                        _log += string.Format("==>> Progress: {0} ({1})\n", e.Value, e.Value2);
                        Console.WriteLine("==>> Progress: {0} ({1})", e.Value, e.Value2);
                    };
                    wkHtml.Error += (s, e) =>
                    {
                        _log    += string.Format("==>> ERROR: {0}\n", e.Value);
                        isFailed = true;
                        Console.WriteLine("==>> ERROR: {0}", e.Value);
                    };
                    wkHtml.Finished += (s, e) => { Console.WriteLine("==>> WARN: {0}", e.Value); };
                    lock (wkHtml)
                    {
                        if (source == EnumPdfType.Html)
                        {
                            fileBytes = wkHtml.Convert(page);
                        }
                        else
                        {
                            fileBytes = wkHtml.Convert();
                        }
                    }

                    using (FileStream fs = new FileStream(string.Concat(Path, fileName.ToLower().Replace(".pdf", string.Empty), ".PDF"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        fs.Write(fileBytes, 0, fileBytes.Length);
                        fs.Close();
                    }

                    return(fileBytes);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }