Ejemplo n.º 1
0
        protected virtual void TransformHtml2Pdf(Document doc, PdfWriter pdfWriter, IImageProvider imageProvider,
                                                 IFontProvider fontProvider, Stream cssFile)
        {
            CssFilesImpl cssFiles = new CssFilesImpl();

            if (cssFile == null)
            {
                cssFile =
                    typeof(XMLWorker).Assembly.GetManifestResourceStream("iTextSharp.tool.xml.css.default.css");
            }
            cssFiles.Add(XMLWorkerHelper.GetCSS(cssFile));
            StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
            HtmlPipelineContext  hpc;

            if (fontProvider != null)
            {
                hpc = new HtmlPipelineContext(new CssAppliersImpl(fontProvider));
            }
            else
            {
                hpc = new HtmlPipelineContext(null);
            }

            hpc.SetImageProvider(imageProvider);
            hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter));
            IPipeline    pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
            XMLWorker    worker       = new XMLWorker(pipeline, true);
            XMLParser    xmlParse     = new XMLParser(true, worker, Encoding.GetEncoding("UTF-8"));

            xmlParse.Parse(File.OpenRead(inputHtml), Encoding.GetEncoding("UTF-8"));
        }
Ejemplo n.º 2
0
        /**
         * Parses an HTML string and a string containing CSS into a list of Element objects.
         * The FontProvider will be obtained from iText's FontFactory object.
         *
         * @param   html    a String containing an XHTML snippet
         * @param   css     a String containing CSS
         * @return  an ElementList instance
         */
        public static ElementList ParseToElementList(String html, String css)
        {
            // CSS
            ICSSResolver cssResolver = new StyleAttrCSSResolver();

            if (css != null)
            {
                ICssFile cssFile = XMLWorkerHelper.GetCSS(new MemoryStream(Encoding.Default.GetBytes(css)));
                cssResolver.AddCss(cssFile);
            }

            // HTML
            CssAppliers         cssAppliers = new CssAppliersImpl(FontFactory.FontImp);
            HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);

            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            htmlContext.AutoBookmark(false);

            // Pipelines
            ElementList            elements     = new ElementList();
            ElementHandlerPipeline end          = new ElementHandlerPipeline(elements, null);
            HtmlPipeline           htmlPipeline = new HtmlPipeline(htmlContext, end);
            CssResolverPipeline    cssPipeline  = new CssResolverPipeline(cssResolver, htmlPipeline);

            // XML Worker
            XMLWorker worker = new XMLWorker(cssPipeline, true);
            XMLParser p      = new XMLParser(worker);

            p.Parse(new MemoryStream(Encoding.Default.GetBytes(html)));

            return(elements);
        }
Ejemplo n.º 3
0
    public void ConvertHtmlToPdf(string xHtml, string css)
    {
        // instantiate custom tag processor and add to `HtmlPipelineContext`.
        var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
        //tagProcessorFactory.AddProcessor(
        //    new TableDataProcessor(),
        //    new string[] { HTML.Tag.TD }
        //);
        var htmlPipelineContext = new HtmlPipelineContext(null);

        htmlPipelineContext.SetTagFactory(tagProcessorFactory);

        var pdfWriterPipeline = new PdfWriterPipeline(this.PdfDoc, this.Writer);
        var htmlPipeline      = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);

        // get an ICssResolver and add the custom CSS
        var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);

        cssResolver.AddCss(css, "utf-8", true);
        var cssResolverPipeline = new CssResolverPipeline(
            cssResolver, htmlPipeline
            );

        var worker = new XMLWorker(cssResolverPipeline, true);
        var parser = new XMLParser(worker);

        using (var stringReader = new StringReader(xHtml)) {
            parser.Parse(stringReader);
        }
    }
Ejemplo n.º 4
0
 virtual public void SetUp()
 {
     hpc = new HtmlPipelineContext(null);
     p   = new HtmlPipeline(hpc, null);
     wc  = new WorkerContextImpl();
     p.Init(wc);
 }
Ejemplo n.º 5
0
 public static byte[] ConvertHtmltoPdf(ClientContext context, Microsoft.SharePoint.Client.List documentLibrary, string result, string nameOfTheFile)
 {
     using (var msOutput = new MemoryStream())
     {
         using (var stringReader = new StringReader(result))
         {
             using (Document document = new Document())
             {
                 var pdfWriter = PdfWriter.GetInstance(document, msOutput);
                 pdfWriter.InitialLeading = 12.5f;
                 document.Open();
                 var xmlWorkerHelper       = XMLWorkerHelper.GetInstance();
                 var cssResolver           = new StyleAttrCSSResolver();
                 var xmlWorkerFontProvider = new XMLWorkerFontProvider();
                 //foreach (string font in fonts)
                 //{
                 //    xmlWorkerFontProvider.Register(font);
                 //}
                 var cssAppliers = new CssAppliersImpl(xmlWorkerFontProvider);
                 var htmlContext = new HtmlPipelineContext(cssAppliers);
                 htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                 PdfWriterPipeline   pdfWriterPipeline   = new PdfWriterPipeline(document, pdfWriter);
                 HtmlPipeline        htmlPipeline        = new HtmlPipeline(htmlContext, pdfWriterPipeline);
                 CssResolverPipeline cssResolverPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
                 XMLWorker           xmlWorker           = new XMLWorker(cssResolverPipeline, true);
                 XMLParser           xmlParser           = new XMLParser(xmlWorker);
                 xmlParser.Parse(stringReader);
             }
         }
         return(msOutput.ToArray());
     }
 }
Ejemplo n.º 6
0
        public void ConvertHtmlToPdf()
        {
            using (var stream = new FileStream(OUTPUT_FILE, FileMode.Create))
            {
                using (var document = new Document())
                {
                    var writer = PdfWriter.GetInstance(document, stream);
                    document.Open();

                    var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
                    // custom tag processor above
                    tagProcessorFactory.AddProcessor(
                        new CustomHorizontalRule(),
                        new string[] { HTML.Tag.HR }
                        );
                    var htmlPipelineContext = new HtmlPipelineContext(null);
                    htmlPipelineContext.SetTagFactory(tagProcessorFactory);

                    var pdfWriterPipeline   = new PdfWriterPipeline(document, writer);
                    var htmlPipeline        = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);
                    var cssResolver         = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                    var cssResolverPipeline = new CssResolverPipeline(
                        cssResolver, htmlPipeline
                        );

                    var worker = new XMLWorker(cssResolverPipeline, true);
                    var parser = new XMLParser(worker);
                    var xHtml  = "<hr style='border:1px dotted red' />";
                    using (var stringReader = new StringReader(xHtml))
                    {
                        parser.Parse(stringReader);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        protected override void TransformHtml2Pdf(Document doc, PdfWriter pdfWriter, IImageProvider imageProvider,
                                                  IFontProvider fontProvider, Stream cssFile)
        {
            ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);

            HtmlPipelineContext hpc;

            if (fontProvider != null)
            {
                hpc = new HtmlPipelineContext(new CssAppliersImpl(fontProvider));
            }
            else
            {
                hpc = new HtmlPipelineContext(null);
            }

            hpc.SetImageProvider(imageProvider);
            hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter));
            IPipeline    pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
            XMLWorker    worker       = new XMLWorker(pipeline, true);
            XMLParser    xmlParse     = new XMLParser(true, worker, Encoding.UTF8);

            xmlParse.Parse(new FileStream(inputHtml, FileMode.Open), Encoding.UTF8);
        }
Ejemplo n.º 8
0
        virtual public void ParseXHtml(PdfWriter writer, Document doc, Stream inp, Stream inCssFile, Encoding charset, IFontProvider fontProvider)
        {
            CssFilesImpl cssFiles = new CssFilesImpl();

            if (inCssFile != null)
            {
                cssFiles.Add(GetCSS(inCssFile));
            }
            else
            {
                cssFiles.Add(GetDefaultCSS());
            }
            StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
            HtmlPipelineContext  hpc         = new HtmlPipelineContext(new CssAppliersImpl(fontProvider));

            hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(GetDefaultTagProcessorFactory());
            HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer));
            IPipeline    pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
            XMLWorker    worker       = new XMLWorker(pipeline, true);
            XMLParser    p            = new XMLParser(true, worker, charset);

            if (charset != null)
            {
                p.Parse(inp, charset);
            }
            else
            {
                p.Parse(inp);
            }
        }
Ejemplo n.º 9
0
        public static ElementList ParseToElementList(string html, string css)
        {
            ICSSResolver iCSSResolver = new StyleAttrCSSResolver();

            if (css != null)
            {
                ICssFile cSS = XMLWorkerHelper.GetCSS(new MemoryStream(Encoding.Default.GetBytes(css)));
                iCSSResolver.AddCss(cSS);
            }

            MyFontsProvider fontProvider = new MyFontsProvider();
            CssAppliers     cssAppliers  = new CssAppliersImpl(fontProvider);
            //CssAppliers cssAppliers = new CssAppliersImpl(FontFactory.FontImp);
            HtmlPipelineContext htmlPipelineContext = new HtmlPipelineContext(cssAppliers);

            htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            htmlPipelineContext.AutoBookmark(false);
            ElementList            elementList = new ElementList();
            ElementHandlerPipeline next        = new ElementHandlerPipeline(elementList, null);
            HtmlPipeline           next2       = new HtmlPipeline(htmlPipelineContext, next);
            CssResolverPipeline    pipeline    = new CssResolverPipeline(iCSSResolver, next2);
            XMLWorker listener  = new XMLWorker(pipeline, true);
            XMLParser xMLParser = new XMLParser(listener);

            //因为XMLWork不支持html的单标签,所以要对单标签进行过滤。不然就会报错:Invalid nested tag div found, expected closing tag br
            html = html.Replace("<br>", "").Replace("<hr>", "").Replace("<img>", "").Replace("<param>", "")
                   .Replace("<link>", "");

            //xMLParser.Parse(new MemoryStream(Encoding.Default.GetBytes(html)));
            xMLParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(html)));
            return(elementList);
        }
Ejemplo n.º 10
0
        protected override void TransformHtml2Pdf()
        {
            Document  doc       = new Document(PageSize.A4.Rotate());
            PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(outPdf, FileMode.Create));

            doc.SetMargins(doc.LeftMargin - 10, doc.RightMargin - 10, doc.TopMargin, doc.BottomMargin);
            doc.Open();

            CssFilesImpl cssFiles = new CssFilesImpl();

            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + @"\tool\xml\examples\" + "sampleTest.css")));
            StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
            HtmlPipelineContext  hpc         =
                new HtmlPipelineContext(
                    new CssAppliersImpl(new XMLWorkerFontProvider(RESOURCES + @"\tool\xml\examples\fonts")));

            hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            hpc.SetImageProvider(new SampleTest.SampleTestImageProvider());
            HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter));
            IPipeline    pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
            XMLWorker    worker       = new XMLWorker(pipeline, true);
            XMLParser    p            = new XMLParser(true, worker, Encoding.GetEncoding("UTF-8"));

            p.Parse(File.OpenRead(inputHtml), Encoding.GetEncoding("UTF-8"));
            doc.Close();
        }
    public static string ConvertHtmlToPdf(string htmlContent, string fileNameWithoutExtension, string filePath, string cssContent = "")
    {
        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }
        var fileNameWithPath = Path.Combine(filePath, fileNameWithoutExtension + ".pdf");

        using (var stream = new FileStream(fileNameWithPath, FileMode.Create)) {
            using (var document = new Document()) {
                var writer = PdfWriter.GetInstance(document, stream);
                document.Open();
                // instantiate custom tag processor and add to `HtmlPipelineContext`.
                var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
                tagProcessorFactory.AddProcessor(new TableData(), new string[] {
                    HTML.Tag.TD
                });
                var htmlPipelineContext = new HtmlPipelineContext(null);
                htmlPipelineContext.SetTagFactory(tagProcessorFactory);
                var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
                var htmlPipeline      = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);
                // get an ICssResolver and add the custom CSS
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                cssResolver.AddCss(cssContent, "utf-8", true);
                var cssResolverPipeline = new CssResolverPipeline(
                    cssResolver, htmlPipeline);
                var worker = new XMLWorker(cssResolverPipeline, true);
                var parser = new XMLParser(worker);
                using (var stringReader = new StringReader(htmlContent)) {
                    parser.Parse(stringReader);
                }
            }
        }
        return(fileNameWithPath);
    }
Ejemplo n.º 12
0
        protected override void MakePdf(string outPdf)
        {
            Document  doc       = new Document(PageSize.A4_LANDSCAPE);
            PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(outPath + outPdf, FileMode.Create));

            doc.SetMargins(0, 0, 0, 0);
            doc.Open();


            CssFilesImpl cssFiles = new CssFilesImpl();

            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + testName +
                                  Path.DirectorySeparatorChar + "sampleTest.css")));
            StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
            HtmlPipelineContext  hpc         =
                new HtmlPipelineContext(
                    new CssAppliersImpl(new XMLWorkerFontProvider(RESOURCES + @"\tool\xml\examples\fonts")));

            hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            hpc.SetImageProvider(new SampleTestImageProvider());
            HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter));
            IPipeline    pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
            XMLWorker    worker       = new XMLWorker(pipeline, true);
            XMLParser    p            = new XMLParser(true, worker, Encoding.GetEncoding("UTF-8"));

            p.Parse(File.OpenRead(inputHtml), Encoding.GetEncoding("UTF-8"));
            doc.Close();
        }
Ejemplo n.º 13
0
        public byte[] GeneratePdfOutput(ControllerContext context, object model        = null, string viewName = null,
                                        Action <PdfWriter, Document> configureSettings = null)
        {
            if (viewName == null)
            {
                viewName = context.RouteData.GetRequiredString("action");
            }

            context.Controller.ViewData.Model = model;

            byte[] output;
            using (var document = new Document())
            {
                using (var workStream = new MemoryStream())
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, workStream);
                    writer.CloseStream = false;

                    if (configureSettings != null)
                    {
                        configureSettings(writer, document);
                    }

                    document.Open();

                    //base64 image support : https://rupertmaier.wordpress.com/2014/08/22/creating-a-pdf-with-an-image-in-itextsharp/
                    var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
                    tagProcessors.RemoveProcessor(HTML.Tag.IMG);
                    tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor());

                    var cssFiles = new CssFilesImpl();
                    cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
                    var cssResolver = new StyleAttrCSSResolver(cssFiles);

                    var charset = Encoding.UTF8;
                    var hpc     = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
                    hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors);
                    var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(document, writer));
                    var cssPipeline  = new CssResolverPipeline(cssResolver, htmlPipeline);
                    var worker       = new XMLWorker(cssPipeline, true);
                    var xmlParser    = new XMLParser(true, worker, charset);

                    using (var reader = new StringReader(RenderRazorView(context, viewName)))
                    {
                        xmlParser.Parse(reader);
                        document.Close();
                        output = workStream.ToArray();
                    }
                }
            }
            return(output);
        }
        //public FileResult GetEligibilityForm(string id = "0")
        public ActionResult GetMDTFormPDF(long id = 0, bool isdoc = false)
        {
            var fileBytes = new byte[0];

            if (isdoc)
            {
                var attachDetails = FactoryInstance.Instance.CreateInstance <Reporting>().GetMDTAttachmentById(id);
                fileBytes = attachDetails.AttachmentFileByte;
            }
            else
            {
                var result = FactoryInstance.Instance.CreateInstance <Reporting>().GetMDTReportById(id, "pdf");
                // Render the view xml to a string, then parse that string into an XML dom.
                string html   = this.RenderActionResultToString(this.View("MDTFormPdfView", result));
                var    output = new MemoryStream();
                using (var doc = new Document(PageSize.A4))
                {
                    var writer = PdfWriter.GetInstance(doc, output);

                    PDFBackgroundHelper pageEventHelper = new PDFBackgroundHelper();
                    writer.PageEvent = pageEventHelper;

                    writer.CloseStream = false;
                    doc.Open();


                    var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
                    tagProcessors.RemoveProcessor(HTML.Tag.IMG);                             // remove the default processor
                    tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use our new processor

                    CssFilesImpl cssFiles = new CssFilesImpl();
                    cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
                    var cssResolver = new StyleAttrCSSResolver(cssFiles);
                    cssResolver.AddCss(@"code { padding: 2px 4px; }", "utf-8", true);
                    var charset = Encoding.UTF8;
                    var hpc     = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
                    hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors
                    var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer));
                    var pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
                    var worker       = new XMLWorker(pipeline, true);
                    var xmlParser    = new XMLParser(true, worker, charset);
                    xmlParser.Parse(new StringReader(html));
                }

                output.Position = 0;
                fileBytes       = output.ToArray();
            }
            // Send the binary data to the browser.
            return(new BinaryContentResult(fileBytes, "application/pdf"));
            // return File(fileBytes, "application/pdf", "MDT form of" + result.Name + ".pdf");
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Converts the specified view name and data model to a PDF.
        /// </summary>
        /// <param name="viewName">The name of the view to convert to PDF.</param>
        /// <param name="dataModel">The data model to use.</param>
        /// <param name="pageSize">The size of the page to create.</param>
        /// <returns>The raw data of the PDF as a byte array.</returns>
        protected virtual byte[] PdfBytes(string viewName, object dataModel, Rectangle pageSize)
        {
            if (String.IsNullOrEmpty(viewName))
            {
                viewName = ControllerContext.RouteData.Values["action"].ToString();
            }
            using (var document = new Document()) {
                if (pageSize == null)
                {
                    pageSize = PageSize.LETTER;
                }
                document.SetPageSize(pageSize);
                using (var ms = new MemoryStream()) {
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    writer.CloseStream = false;
                    document.Open();
                    using (var sw = new StringWriter()) {
                        ViewData.Model = dataModel;
                        var viewEngine      = (ICompositeViewEngine)HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine));
                        var contextAccessor = (IActionContextAccessor)HttpContext.RequestServices.GetService(typeof(IActionContextAccessor));
                        var viewResult      = viewEngine.FindView(contextAccessor.ActionContext, viewName, true);
                        var viewContext     = new ViewContext(contextAccessor.ActionContext, viewResult.View, ViewData, TempData, sw, new HtmlHelperOptions());
                        var viewTask        = viewResult.View.RenderAsync(viewContext);
                        viewTask.Wait();
                        using (var reader = new StringReader(sw.ToString())) {
                            var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
                            tagProcessors.RemoveProcessor(HTML.Tag.IMG);                               // remove the default processor
                            tagProcessors.AddProcessor(HTML.Tag.IMG, new EmbeddedImageTagProcessor()); // use our new processor

                            CssFilesImpl cssFiles = new CssFilesImpl();
                            cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
                            var cssResolver = new StyleAttrCSSResolver(cssFiles);
                            var charset     = Encoding.UTF8;
                            var hpc         = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
                            hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors);                             // inject the tagProcessors
                            var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(document, writer));
                            var pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
                            var worker       = new XMLWorker(pipeline, true);
                            var xmlParser    = new XMLParser(true, worker, charset);
                            //XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);
                            xmlParser.Parse(reader);
                            document.Close();
                            return(ms.ToArray());
                        }
                    }
                }
            }
        }
Ejemplo n.º 16
0
        public static byte[] WriteHtmlToPdf(string htmlString, string css)
        {
            byte[] bytes;
            //Boilerplate iTextSharp setup here
            //Create a stream that we can write to, in this case a MemoryStream
            using (var ms = new MemoryStream())
            {
                //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
                using (var doc = new Document())
                {
                    //Create a writer that's bound to our PDF abstraction and our stream
                    using (var writer = PdfWriter.GetInstance(doc, ms))
                    {
                        doc.Open();

                        var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();

                        var htmlPipelineContext = new HtmlPipelineContext(null);
                        htmlPipelineContext.SetTagFactory(tagProcessorFactory);
                        var pdfWriterPipeline = new PdfWriterPipeline(doc, writer);
                        var htmlPipeline      = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);

                        // get an ICssResolver and add the custom CSS
                        var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                        cssResolver.AddCss(css, "utf-8", true);
                        var cssResolverPipeline = new CssResolverPipeline(
                            cssResolver, htmlPipeline
                            );


                        var worker = new XMLWorker(cssResolverPipeline, true);
                        var parser = new XMLParser(worker);
                        using (var sr = new StringReader(htmlString))

                        {
                            parser.Parse(sr);

                            //XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, sr);
                        }
                        doc.Close();
                    }
                    bytes = ms.ToArray();
                }
                return(bytes);
            }
        }
Ejemplo n.º 17
0
        public static void ServePdfEmbeddedImages(string url)
        {
            using (var doc = new Document(PageSize.LETTER))
            {
                var writer = PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream);
                writer.InitialLeading = 12.5f;
                doc.Open();

                string   lastPart = "";
                string[] parts    = url.Split('=');
                if (parts.Count() > 2)
                {
                    lastPart = "_" + parts[parts.Count() - 2];
                }

                HttpContext.Current.Response.ContentType = "application/pdf";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Alert" + lastPart + ".pdf");
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

                WebClient web  = new WebClient();
                var       html = web.DownloadString(url);

                var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
                tagProcessors.RemoveProcessor(HTML.Tag.IMG);                             // remove the default processor
                tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use our new processor

                CssFilesImpl cssFiles = new CssFilesImpl();
                cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
                var cssResolver = new StyleAttrCSSResolver(cssFiles);
                cssResolver.AddCss(@"code { padding: 2px 4px; } img { padding: 4px 8px; }", "utf-8", true);
                var charset = Encoding.UTF8;
                var hpc     = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
                hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors);                 // inject the tagProcessors
                var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer));
                var pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
                var worker       = new XMLWorker(pipeline, true);
                var xmlParser    = new XMLParser(true, worker, charset);
                xmlParser.Parse(new StringReader(html));

                HttpContext.Current.Response.Write(doc);
                HttpContext.Current.Response.End();
            }
            //Process.Start("test.pdf");
        }
        protected byte[] RenderHtmlToPDF(string Html)
        {
            // http://stackoverflow.com/questions/36180131/using-itextsharp-xmlworker-to-convert-html-to-pdf-and-write-text-vertically
            // http://stackoverflow.com/questions/20488045/change-default-font-and-fontsize-in-pdf-using-itextsharp

            Document document = new Document(PageSize.A4, 50f, 30f, 40f, 90f);

            if (Html.Contains("class=\"landscape\""))
            {
                document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
            }

            MemoryStream stream = new MemoryStream();
            TextReader   reader = new StringReader(Html);
            PdfWriter    writer = PdfWriter.GetInstance(document, stream);

            document.AddTitle("muster ag");

            XMLWorkerFontProvider fonts    = new XMLWorkerFontProvider();
            CssAppliers           appliers = new CssAppliersImpl(fonts);

            HtmlPipelineContext context = new HtmlPipelineContext(appliers);

            context.SetAcceptUnknown(true);
            context.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

            PdfWriterPipeline pdfpipeline  = new PdfWriterPipeline(document, writer);
            HtmlPipeline      htmlpipeline = new HtmlPipeline(context, pdfpipeline);

            var resolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);

            resolver.AddCssFile(Server.MapPath("~/Content/inv.pdf.css"), true);
            CssResolverPipeline csspipeline = new CssResolverPipeline(resolver, htmlpipeline);

            XMLWorker worker = new XMLWorker(csspipeline, true);
            XMLParser parser = new XMLParser(worker);

            document.Open();
            parser.Parse(reader);
            worker.Close();
            document.Close();

            return(stream.ToArray());
        }
Ejemplo n.º 19
0
        private XMLWorker CreateXmlWorker(Document doc, PdfWriter writer)
        {
            var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);

            cssResolver.AddCss(content: css, isPersistent: true);

            var htmlContext = new HtmlPipelineContext(null);

            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            htmlContext.SetImageProvider(imageProvider);

            var pdfPipeline  = new PdfWriterPipeline(doc, writer);
            var htmlPipeline = new HtmlPipeline(htmlContext, pdfPipeline);
            var cssPipeline  = new CssResolverPipeline(cssResolver, htmlPipeline);

            var worker = new XMLWorker(cssPipeline, true);

            return(worker);
        }
Ejemplo n.º 20
0
        private void CreatePdfFromHtmlString(string HtmlTemplate, string DestinationPath)
        {
            Document doc = new Document();

            var fontFile = Server.MapPath("~/fonts/ARIALUNI.ttf");

            try
            {
                var FS = new System.IO.FileStream(DestinationPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);

                var document = new Document();

                var writer = PdfWriter.GetInstance(document, FS);

                document.Open();

                var cssResolver  = new StyleAttrCSSResolver();
                var fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
                fontProvider.Register(fontFile);
                var cssAppliers = new CssAppliersImpl(fontProvider);
                var htmlContext = new HtmlPipelineContext(cssAppliers);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                var pdf  = new PdfWriterPipeline(document, writer);
                var html = new HtmlPipeline(htmlContext, pdf);
                var css  = new CssResolverPipeline(cssResolver, html);

                var worker = new XMLWorker(css, true);
                var p      = new XMLParser(worker);

                var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(HtmlTemplate));

                var sr = new StreamReader(ms);

                p.Parse(sr);

                document.Close();
            }
            catch (Exception e)
            {
                throw;
            }
        }
Ejemplo n.º 21
0
        protected override void MakePdf(string outPdf)
        {
            Document doc = new Document(PageSize.A3.Rotate());

            PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(outPdf, FileMode.Create));

            pdfWriter.CreateXmpMetadata();

            doc.SetMargins(200, 200, 0, 0);
            doc.Open();


            CssFilesImpl cssFiles = new CssFilesImpl();

            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + Path.DirectorySeparatorChar + testName +
                                  Path.DirectorySeparatorChar + "complexDiv_files" + Path.DirectorySeparatorChar +
                                  "main.css")));
            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + Path.DirectorySeparatorChar + testName +
                                  Path.DirectorySeparatorChar + "complexDiv_files" + Path.DirectorySeparatorChar +
                                  "widget082.css")));
            StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
            HtmlPipelineContext  hpc         =
                new HtmlPipelineContext(
                    new CssAppliersImpl(new XMLWorkerFontProvider(RESOURCES + @"\tool\xml\examples\fonts")));

            hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            hpc.SetImageProvider(new SampleTestImageProvider());
            hpc.SetPageSize(doc.PageSize);
            HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter));
            IPipeline    pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
            XMLWorker    worker       = new XMLWorker(pipeline, true);
            XMLParser    p            = new XMLParser(true, worker, Encoding.GetEncoding("UTF-8"));

            p.Parse(File.OpenRead(inputHtml), Encoding.GetEncoding("UTF-8"));
            //ICC_Profile icc = ICC_Profile.getInstance(ComplexDiv01Test.class.getResourceAsStream("sRGB Color Space Profile.icm"));
            //pdfWriter.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
            doc.Close();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creates a <see cref="PdfTable"/> object from specified <b>HTML</b> code.
        /// </summary>
        /// <param name="html">A reference to input html code to convert.</param>
        /// <param name="css">A reference to css styles to apply.</param>
        /// <param name="config">Table configuration reference.</param>
        /// <returns>
        /// A new <see cref="PdfPTable"/> that contains a
        /// </returns>
        public static PdfTable CreateFromHtml(string html, string css = default, PdfTableConfig config = null)
        {
            var hasCss = !string.IsNullOrEmpty(css);

            if (!hasCss)
            {
                css = " ";
            }

            // css
            StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver();
            ICssFile             cssFile     = XMLWorkerHelper.GetCSS(css.AsStream());

            cssResolver.AddCss(cssFile);

            // html
            XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts)));
            CssAppliers           cssAppliers  = new CssAppliersImpl(fontProvider);
            HtmlPipelineContext   htmlContext  = new HtmlPipelineContext(cssAppliers);

            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

            // pipelines
            ElementList            elements     = new ElementList();
            ElementHandlerPipeline pdf          = new ElementHandlerPipeline(elements, null);
            HtmlPipeline           htmlPipeline = new HtmlPipeline(htmlContext, pdf);
            CssResolverPipeline    cssPipeline  = new CssResolverPipeline(cssResolver, htmlPipeline);

            // XML Worker
            XMLWorker worker = new XMLWorker(cssPipeline, true);
            XMLParser parser = new XMLParser(worker, Encoding.UTF8);

            parser.Parse(html.AsStream(Encoding.UTF8));

            PdfPTable nativeTable = (PdfPTable)elements[0];

            return(new PdfTable(nativeTable, config));
        }
Ejemplo n.º 23
0
        public void Go()
        {
            using (var stream = new FileStream(OUTPUT_FILE, FileMode.Create))
            {
                using (var document = new Document())
                {
                    PdfWriter writer = PdfWriter.GetInstance(
                        document, stream
                        );
                    document.Open();

                    // instantiate custom tag processor and add to `HtmlPipelineContext`.
                    var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
                    tagProcessorFactory.AddProcessor(
                        new TableProcessor(),
                        new string[] { HTML.Tag.TABLE }
                        );
                    var htmlPipelineContext = new HtmlPipelineContext(null);
                    htmlPipelineContext.SetTagFactory(tagProcessorFactory);

                    var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
                    var htmlPipeline      = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);

                    var cssResolver         = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                    var cssResolverPipeline = new CssResolverPipeline(
                        cssResolver, htmlPipeline
                        );

                    var worker = new XMLWorker(cssResolverPipeline, true);
                    var parser = new XMLParser(worker);
                    using (var stringReader = new StringReader(GetHtml()))
                    {
                        parser.Parse(stringReader);
                    }
                }
            }
        }
        private static void AddHTMLText(PdfWriter writer, Document document, string htmlString, List <string> stylesheetFilePath)
        {
            var cssResolver = new StyleAttrCSSResolver();

            Stream cssStream = null;

            if (stylesheetFilePath != null)
            {
                foreach (var stylesheetPath in stylesheetFilePath)
                {
                    cssStream = new FileStream(stylesheetPath, FileMode.Open, FileAccess.Read);
                    var cssFile = XMLWorkerHelper.GetCSS(cssStream);
                    cssResolver.AddCss(cssFile);
                }
            }

            var cssAppliersImpl     = new CssAppliersImpl();
            var htmlPipelineContext = new HtmlPipelineContext(cssAppliersImpl);

            htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            htmlPipelineContext.SetImageProvider(new DownloadImageProvider());

            var pdfWriterPipeline   = new PdfWriterPipeline(document, writer);
            var htmlPipe            = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);
            var cssResolverPipeline = new CssResolverPipeline(cssResolver, htmlPipe);

            var worker       = new XMLWorker(cssResolverPipeline, true);
            var parser       = new XMLParser(worker);
            var stringReader = new StringReader(htmlString);

            parser.Parse(stringReader);

            if (cssStream != null)
            {
                cssStream.Dispose();
            }
        }
Ejemplo n.º 25
0
        static protected void TransformHtml2Pdf(FileStream inputHtml, Document doc, PdfWriter pdfWriter)
        {
            CssFilesImpl cssFiles = new CssFilesImpl();

            cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
            StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);

            String Css1 =
                "https://specialtyonlinestg.cardinalhealth.com/CardinalHealthSpecialty/themes/html/SS_SPDCardinalHealth/css/globalStyles.css?version=RI_20121023";
            String Css2 =
                "https://specialtyonlinestg.cardinalhealth.com/CardinalHealthSpecialty/themes/html/SS_SPDCardinalHealth/css/SPDCSS/CAHPHReconciliationPortletView.css?version=AC_20120717";

            try {
                cssResolver.AddCssFile(Css1, true);
                cssResolver.AddCssFile(Css2, true);
            }
            catch (CssResolverException e) {
                // TODO Auto-generated catch block
            }

            HtmlPipelineContext htmlContext = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));

            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            htmlContext.SetPageSize(new Rectangle(doc.Left, doc.Bottom, doc.Right, doc.Top));

            // Pipelines
            PdfWriterPipeline   pdf  = new PdfWriterPipeline(doc, pdfWriter);
            HtmlPipeline        html = new HtmlPipeline(htmlContext, pdf);
            CssResolverPipeline css  = new CssResolverPipeline(cssResolver, html);


            XMLWorker worker = new XMLWorker(css, true);
            XMLParser parser = new XMLParser(worker, Encoding.UTF8);

            parser.Parse(inputHtml, Encoding.UTF8);
        }
Ejemplo n.º 26
0
        public static byte[] HTMLToPdf(string htmlContent)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            StringWriter           sw = new StringWriter(new StringBuilder(htmlContent));
            HtmlTextWriter         hw = new HtmlTextWriter(sw);
            StringReader           sr = new StringReader(sw.ToString());
            Document   pdfDoc         = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            HTMLWorker htmlparser     = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, ms);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();

            byte[] Result = ms.ToArray();

            return(Result);


            HtmlAgilityPack.HtmlDocument hd = new HtmlAgilityPack.HtmlDocument();

            hd.OptionWriteEmptyNodes = true; //autoclose hr, br etc
            hd.OptionOutputAsXml     = true; //MJW extension to preserve case of server tags
            hd.LoadHtml(htmlContent);

#if (DEBUG)
            string tmpFile = Path.GetTempFileName();
            System.IO.File.WriteAllText(tmpFile, hd.DocumentNode.OuterHtml);
            System.Diagnostics.Debug.WriteLine(tmpFile);
#endif



            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                using (TextReader reader = new StringReader(hd.DocumentNode.OuterHtml))
                    using (Document document = new Document(PageSize.A4, 30, 30, 30, 30))
                        using (PdfWriter writer = PdfWriter.GetInstance(document, stream))
                            using (var srHtml = new StringReader(hd.DocumentNode.OuterHtml))
                            {
                                CssFilesImpl cssFiles = new CssFilesImpl();
                                cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
                                var cssResolver = new StyleAttrCSSResolver(cssFiles);
                                cssResolver.AddCss(@"code { padding: 2px 4px; }", "utf-8", true);
                                var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
                                tagProcessors.RemoveProcessor(HTML.Tag.IMG);                             // remove the default processor
                                tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use our new processor
                                var charset = Encoding.UTF8;
                                var hpc     = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
                                hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors
                                var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(document, writer));
                                var pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
                                var worker       = new XMLWorker(pipeline, true);
                                var xmlParser    = new XMLParser(true, worker, charset);



                                document.Open();
                                xmlParser.Parse(reader);
                                document.Close();

                                return(stream.ToArray());
                            }
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Invalid number of arguments.");
                Console.WriteLine("Usage: html2Pdf.exe [input html_file/directory] [default css file]");
                return;
            }

            List <FileStream> fileList = new List <FileStream>();

            if (File.Exists(args[0]))
            {
                fileList.Add(new FileStream(args[0], FileMode.Open));
            }
            else if (Directory.Exists(args[0]))
            {
                CollectHtmlFiles(fileList, args[0]);
            }

            if (fileList.Count == 0)
            {
                Console.WriteLine("Invalid html_file/directory");
                Console.WriteLine("Usage: html2Pdf.exe [input html_file/directory] [default css file]");
                return;
            }

            foreach (FileStream fileStream in fileList)
            {
                Document doc = new Document(PageSize.LETTER);
                doc.SetMargins(doc.LeftMargin, doc.RightMargin, 35, 0);
                String path = Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar +
                              Path.GetFileNameWithoutExtension(fileStream.Name) + ".pdf";
                PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));

                doc.Open();
                Dictionary <String, String> substFonts = new Dictionary <String, String>();
                substFonts["Arial Unicode MS"] = "Helvetica";
                CssFilesImpl cssFiles = new CssFilesImpl();
                cssFiles.Add(XMLWorkerHelper.GetCSS(new FileStream(args[1], FileMode.Open)));
                StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
                HtmlPipelineContext  hpc         = new HtmlPipelineContext(new CssAppliersImpl(new UnembedFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS, substFonts)));
                hpc.SetImageProvider(new ImageProvider(args[0]));
                hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter));
                IPipeline    pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
                XMLWorker    worker       = new XMLWorker(pipeline, true);
                XMLParser    xmlParse     = new XMLParser(true, worker, null);
                xmlParse.Parse(fileStream);
                doc.Close();

                String cmpPath = Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar +
                                 "cmp_" + Path.GetFileNameWithoutExtension(fileStream.Name) + ".pdf";
                if (File.Exists(cmpPath))
                {
                    CompareTool ct       = new CompareTool(path, cmpPath);
                    String      outImage = "<testName>-%03d.png".Replace("<testName>", Path.GetFileNameWithoutExtension(fileStream.Name));
                    String      cmpImage = "cmp_<testName>-%03d.png".Replace("<testName>", Path.GetFileNameWithoutExtension(fileStream.Name));
                    String      diffPath = Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) +
                                           Path.DirectorySeparatorChar + "diff_" + Path.GetFileNameWithoutExtension(fileStream.Name) + ".png";
                    String errorMessage = ct.Compare(Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar + "compare" + Path.DirectorySeparatorChar, diffPath);
                    if (errorMessage != null)
                    {
                        Console.WriteLine(errorMessage);
                    }
                }
            }
        }
 public CssResolverPipeline(object cssResolver, HtmlPipeline htmlPipeline)
 {
     this.cssResolver  = cssResolver;
     this.htmlPipeline = htmlPipeline;
 }
Ejemplo n.º 29
0
        //将html字符串转为字节数组(代码来自百度)
        private byte[] ConvertHtmlTextToPDF(string htmlText)
        {
            if (string.IsNullOrEmpty(htmlText))
            {
                return(null);
            }
            //避免當htmlText無任何html tag標籤的純文字時,轉PDF時會掛掉,所以一律加上<p>標籤
            //htmlText = "<p>" + htmlText + "</p>";

            try
            {
                MemoryStream outputStream = new MemoryStream();               //要把PDF寫到哪個串流
                byte[]       data         = Encoding.UTF8.GetBytes(htmlText); //字串轉成byte[]
                MemoryStream msInput      = new MemoryStream(data);

                // 设置页面
                iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(GetPdfSize(75), GetPdfSize(100), 1);

                pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xFF);
                Document doc = new Document(pageSize, 0, 0, 0, 0);
                //document.SetMargins(0f, 0f, 0f, 0f);
                doc.SetPageSize(pageSize);


                //Document doc = new Document(); //要寫PDF的文件,建構子沒填的話預設直式A4
                PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);

                //指定文件預設開檔時的縮放為100%
                PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
                //開啟Document文件
                doc.Open();

                #region 图片的处理
                CssFilesImpl cssFiles = new CssFilesImpl();
                cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
                var cssResolver = new StyleAttrCSSResolver(cssFiles);

                var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
                tagProcessors.RemoveProcessor(HTML.Tag.IMG);                                         // remove the default processor
                tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor(m_ImageXYDic)); // use new processor

                var hpc = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
                hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors

                var charset      = Encoding.UTF8;
                var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer));
                var pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
                var worker       = new XMLWorker(pipeline, true);
                var xmlParser    = new XMLParser(true, worker, charset);
                xmlParser.Parse(new StringReader(htmlText));
                #endregion

                //使用XMLWorkerHelper把Html parse到PDF檔裡
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());

                //將pdfDest設定的資料寫到PDF檔
                PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
                writer.SetOpenAction(action);

                doc.Close();
                msInput.Close();
                outputStream.Close();

                return(outputStream.ToArray());
            }
            catch (Exception ex)
            {
                throw new ApplicationException("转PDF时异常", ex);
            }
        }
Ejemplo n.º 30
0
        public async Task <Guid> SubmitWorkItem(HTMLtoPDFJob job)
        {
            iTextSharp.text.Rectangle pageSize = PageSize.A4;

            if (job == null)
            {
                throw new Exception("html to pdf job is null");
            }

            switch (job.paperSize)
            {
            case PaperSize.a1:
                pageSize = PageSize.A1;
                break;

            case PaperSize.a2:
                pageSize = PageSize.A2;
                break;

            case PaperSize.a3:
                pageSize = PageSize.A3;
                break;

            case PaperSize.a4:
                pageSize = PageSize.A4;
                break;

            case PaperSize.a5:
                pageSize = PageSize.A5;
                break;

            case PaperSize.a6:
                pageSize = PageSize.A6;
                break;

            case PaperSize.a7:
                pageSize = PageSize.A7;
                break;

            case PaperSize.a8:
                pageSize = PageSize.A8;
                break;

            case PaperSize.a9:
                pageSize = PageSize.A9;
                break;

            case PaperSize.letter:
                pageSize = PageSize.LETTER;
                break;

            default:
                pageSize = PageSize.A4;
                break;
            }

            try
            {
                _context.Jobs.Add(job);
                _context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
                throw new DbEntityValidationException(errorMessages);
            }

            var task = Task.Factory.StartNew(t =>
            {
                HTMLtoPDFJob ebJob    = (HTMLtoPDFJob)t;
                string htmlStream     = "";
                string outputFileName = Guid.NewGuid().ToString("N") + ".pdf";
                string tempfile       = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

                try
                {
                    File.WriteAllBytes(tempfile + ".html", job.FileContent);
                    htmlStream = new StreamReader(tempfile + ".html").ReadToEnd();

                    if (!string.IsNullOrEmpty(htmlStream))
                    {
                        var fsOut         = new MemoryStream();
                        var stringReader  = new StringReader(htmlStream);
                        Document document = new Document(pageSize, 5, 5, 5, 5);

                        //Document setup
                        var pdfWriter = PdfAWriter.GetInstance(document, fsOut);
                        pdfWriter.SetTagged();
                        pdfWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
                        pdfWriter.CreateXmpMetadata();
                        pdfWriter.AddViewerPreference(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE);
                        pdfWriter.Info.Put(new PdfName("Producer"), new PdfString("©" + DateTime.Now.Year.ToString() + " Robobraille.org"));

                        //PDF/A-1A Conformance
                        //pdfWriter = PdfAWriter.GetInstance(document, fsOut, PdfAConformanceLevel.PDF_A_1A);

                        document.Open();
                        document.AddCreationDate();


                        //Custom tag processor
                        var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
                        tagProcessors.AddProcessor(HTML.Tag.HTML, new HTMLTagProcessor(document));
                        tagProcessors.AddProcessor(HTML.Tag.TITLE, new HTMLTagProcessor(document));
                        tagProcessors.AddProcessor(HTML.Tag.TABLE, new TableTagProcessor());
                        tagProcessors.AddProcessor(HTML.Tag.TH, new THTagProcessor());

                        string colorProfilePath = null;
                        string defaultCSSPath   = null;
                        try
                        {
                            colorProfilePath = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data/colors/sRGB.profile");
                            defaultCSSPath   = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data/css/default.css");
                        }
                        catch (Exception e)
                        {
                            colorProfilePath = Path.Combine(ConfigurationManager.AppSettings.Get("ProjectDirectory"), "App_Data/colors/sRGB.profile");
                            defaultCSSPath   = Path.Combine(ConfigurationManager.AppSettings.Get("ProjectDirectory"), "App_Data/css/default.css");
                        }
                        //Setup color profile
                        var cssResolver = new StyleAttrCSSResolver();
                        if (colorProfilePath != null && defaultCSSPath != null)
                        {
                            ICC_Profile icc = ICC_Profile.GetInstance(new FileStream(colorProfilePath, FileMode.Open, FileAccess.Read));
                            pdfWriter.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
                            var xmlWorkerHelper = XMLWorkerHelper.GetInstance();
                            cssResolver.AddCssFile(defaultCSSPath, true);// CSS with default style for all converted docs
                        }

                        //Register system fonts
                        var xmlWorkerFontProvider = new XMLWorkerFontProvider();
                        Environment.SpecialFolder specialFolder = Environment.SpecialFolder.Fonts;
                        string path = Environment.GetFolderPath(specialFolder);
                        DirectoryInfo directoryInfo = new DirectoryInfo(path);
                        FileInfo[] fontFiles        = directoryInfo.GetFiles();
                        foreach (var fontFile in fontFiles)
                        {
                            if (fontFile.Extension == ".ttf")
                            {
                                xmlWorkerFontProvider.Register(fontFile.FullName);
                            }
                        }

                        //HTML & CSS parsing
                        var cssAppliers = new CssAppliersImpl(xmlWorkerFontProvider);
                        var htmlContext = new HtmlPipelineContext(cssAppliers);
                        htmlContext.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors);
                        PdfWriterPipeline pdfWriterPipeline     = new PdfWriterPipeline(document, pdfWriter);
                        HtmlPipeline htmlPipeline               = new HtmlPipeline(htmlContext, pdfWriterPipeline);
                        CssResolverPipeline cssResolverPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
                        XMLWorker xmlWorker = new XMLWorker(cssResolverPipeline, true);
                        XMLParser xmlParser = new XMLParser(xmlWorker);
                        xmlParser.Parse(stringReader);
                        document.Close();

                        //Data as byte array
                        byte[] fileData = fsOut.ToArray();

                        try
                        {
                            string mime               = "application/pdf";
                            string fileExtension      = ".pdf";
                            ebJob.DownloadCounter     = 0;
                            ebJob.ResultFileExtension = fileExtension;
                            ebJob.ResultMimeType      = mime;
                            ebJob.ResultContent       = fileData;
                            ebJob.Status              = JobStatus.Done;
                            ebJob.FinishTime          = DateTime.Now;
                            _context.Jobs.Attach(ebJob);
                            _context.Entry(job).State = EntityState.Modified;
                            _context.SaveChanges();
                        }
                        catch (Exception ex)
                        {
                            RoboBrailleProcessor.SetJobFaulted(job, _context);
                            throw ex;
                        }
                    }
                    else
                    {
                        RoboBrailleProcessor.SetJobFaulted(job, _context);
                        //Error No HTML file to convert
                        throw new Exception("Error No HTML file to convert");
                    }
                }
                catch (Exception e)
                {
                    RoboBrailleProcessor.SetJobFaulted(job, _context);
                    //ignore
                    throw e;
                }
            }, job);

            return(job.Id);
        }