Inheritance: IXMLParserListener
Ejemplo n.º 1
1
        public byte[] GeneratePdfFromView(string viewString, string[] cssPaths, string fontPath)
        {
            using (var memoryStream = new MemoryStream())
            {
                var doc = new Document(PageSize.A4);
                var writer = PdfWriter.GetInstance(doc, memoryStream);

                doc.Open();

                var tagProcessors = InitializeTagProcessor();
                var cssResolver = InitializeCssFiles(cssPaths);

                var fontProvider = new CustomFontFactory(fontPath);

                var hpc = new HtmlPipelineContext(new CssAppliersImpl(fontProvider));
                hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(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, Encoding.Unicode);
                xmlParser.Parse(new StringReader(viewString));

                doc.Close();
                return memoryStream.ToArray();
            }
        }
        public void HtmlToPdf(string htmlFile, string pdfFile, string htmlImageDirectory)
        {
            using (FileStream pdfStream = new FileStream(pdfFile, FileMode.OpenOrCreate))
            {
                Document doc = new Document();
                PdfWriter writer = PdfWriter.GetInstance(doc, pdfStream);
                doc.Open();

                //TODO: apply external css
                ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);

                //HTML
                HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                htmlContext.SetImageProvider(new ImageProvider(htmlImageDirectory));
                htmlContext.SetLinkProvider(new LinkProvider("/"));

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

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

                using (TextReader reader = File.OpenText(htmlFile))
                {
                    p.Parse(reader);
                }

                doc.Close();
            }
        }
Ejemplo n.º 3
0
        protected override void TransformHtml2Pdf() {
            Document doc = new Document(PageSize.A1.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 + Path.DirectorySeparatorChar + testPath + testName +
                                  Path.DirectorySeparatorChar + "complexDiv02_files" + Path.DirectorySeparatorChar +
                                  "minimum0.css")));
            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + testName +
                                  Path.DirectorySeparatorChar + "complexDiv02_files" + Path.DirectorySeparatorChar +
                                  "print000.css")));
            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 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 virtual void Parse(Stream stream, string xHtml)
        {
            xHtml = XhtmlCleaner != null
                ? XhtmlCleaner(xHtml)
                : XhtmlHelper.CloseSimpleTags(xHtml);
            InitParser();

            using (var stringReader = new StringReader(xHtml))
            {
                using (Document document = new Document())
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, stream);
                    document.Open();

                    HtmlPipelineContext
                        .SetTagFactory(TagProcessorFactory)
                        .SetLinkProvider(LinkProvider)
                        .SetImageProvider(ImageProvider)
                    ;
                    var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
                    var htmlPipeline = new HtmlPipeline(HtmlPipelineContext, pdfWriterPipeline);
                    var cssResolverPipeline = new CssResolverPipeline(CssResolver, htmlPipeline);

                    XMLWorker worker = new XMLWorker(cssResolverPipeline, true);
                    XMLParser parser = new XMLParser(worker);
                    parser.Parse(stringReader);
                }
            }
        }
Ejemplo n.º 5
0
 virtual public void ParseXfaOnlyXML() {
     StreamReader bis = File.OpenText(RESOURCE_TEST_PATH + SNIPPETS + TEST + "snippet.html");
     Document doc = new Document(PageSize.A4);
     float margin = utils.ParseRelativeValue("10%", PageSize.A4.Width);
     doc.SetMargins(margin, margin, margin, margin);
     PdfWriter writer = null;
     try {
         writer = PdfWriter.GetInstance(doc, new FileStream(
             TARGET + TEST + "_charset.pdf", FileMode.Create));
     }
     catch (DocumentException e) {
         Console.WriteLine(e);
     }
     CssFilesImpl cssFiles = new CssFilesImpl();
     cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
     StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
     HtmlPipelineContext hpc = new HtmlPipelineContext(null);
     hpc.SetAcceptUnknown(true)
         .AutoBookmark(true)
         .SetTagFactory(Tags.GetHtmlTagProcessorFactory())
         .CharSet(Encoding.GetEncoding("ISO-8859-1"));
     IPipeline pipeline = new CssResolverPipeline(cssResolver,
         new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer)));
     XMLWorker worker = new XMLWorker(pipeline, true);
     doc.Open();
     XMLParser p = new XMLParser(true, worker);
     p.Parse(bis);
     doc.Close();
 }
        protected override void MakePdf(string outPdf) {
            Document doc = new Document(PageSize.A4.Rotate());
            PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(outPdf, FileMode.Create));
            doc.SetMargins(45, 45, 0, 100);
            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"));
            doc.Close();
        }
Ejemplo n.º 7
0
 public void SetUp() {
     LoggerFactory.GetInstance().SetLogger(new SysoLogger(3));
     cssFiles = new CssFilesImpl();
     String path = RESOURCES + @"\css\test.css";
     path = path.Substring(0, path.LastIndexOf("test.css"));
     FileRetrieveImpl r = new FileRetrieveImpl(new String[] {path});
     StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles, r);
     HtmlPipelineContext hpc = new HtmlPipelineContext(null);
     hpc.SetAcceptUnknown(false).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory());
     IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(hpc, null));
     XMLWorker worker = new XMLWorker(pipeline, true);
     p = new XMLParser(worker);
 }
Ejemplo n.º 8
0
 virtual public void SetupDefaultProcessingYourself() {
     Document doc = new Document(PageSize.A4);
     PdfWriter writer = PdfWriter.GetInstance(doc,
         new FileStream(TARGET + "columbus2.pdf", FileMode.Create));
     doc.Open();
     HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
     htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
     ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
     IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext,
         new PdfWriterPipeline(doc, writer)));
     XMLWorker worker = new XMLWorker(pipeline, true);
     XMLParser p = new XMLParser(worker);
     p.Parse(File.OpenRead(RESOURCES + @"\examples\columbus.html"));
     doc.Close();
 }
        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.º 10
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.º 11
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);
                    String errorMessage = ct.Compare(Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar + "compare" + Path.DirectorySeparatorChar, diffPath);
                    if (errorMessage != null) {
                        Console.WriteLine(errorMessage);
                    }
                }
            }
        }
Ejemplo n.º 12
0
        public void SetUp() {
            worker = new XMLWorker(new CustomPipeline(), false);

            called = false;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// ExecuteResult
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.ContentType = "application/pdf";

            if (Download)
                context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName);

            Html = RenderRazorViewToString(context);

            Format(context.HttpContext);

            using (var document = new Document(Settings.PageSize, Settings.Margin.Left, Settings.Margin.Right, Settings.Margin.Top, Settings.Margin.Bottom))
            {
                var memoryStream = new MemoryStream();
                TextReader textReader = new StringReader(Html);
                var pdfWriter = PdfWriter.GetInstance(document, memoryStream);
                var htmlPipelineContext = new HtmlPipelineContext(null);
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);

                document.Open();

                FontFactory.RegisterDirectories();

                htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                foreach (var styleSheet in StyleSheets)
                {
                    cssResolver.AddCssFile(context.HttpContext.Server.MapPath(styleSheet), true);
                }

                var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(document, pdfWriter)));
                var worker = new XMLWorker(pipeline, true);
                var xmlParse = new XMLParser(true, worker);

                xmlParse.Parse(textReader);
                xmlParse.Flush();

                document.Close();
                document.Dispose();

                context.HttpContext.Response.BinaryWrite(memoryStream.ToArray());
            }

            context.HttpContext.Response.End();
            context.HttpContext.Response.Flush();
        }
Ejemplo n.º 14
0
        public static void GeneratePdf(IList<SqlPdfFormat> data, 
            string pdfFullFileName, string cssFullFileName)
        {
            data.OrderBy(x => x.SoldDate);
            DateTime oldDate = data[0].SoldDate;
            StringBuilder sb = new StringBuilder();
            decimal subSum = 0;
            decimal totalSum = 0;
           
            sb.Append("<table>");
            sb.Append("<tr>");
            sb.Append("<th colspan=\"5\" class=\"title\">Aggregated Sales Report </th>");
            sb.Append("</tr>");

            sb.Append("<tr class=\"grayBack\" >");
            sb.AppendFormat("<th colspan=\"5\" class=\"date\">Date: {0}</th>", oldDate.ToShortDateString());
            sb.Append("</tr>");
            sb.Append("<tr class=\"grayBack\" >");
            sb.Append("<th  class=\"th\">Product</th>");
            sb.Append("<th  class=\"th\">Quantity</th>");
            sb.Append("<th  class=\"th\">Unit Price</th>");
            sb.Append("<th  class=\"th\">Location</th>");
            sb.Append("<th  class=\"th\">Sum</th>");
            sb.Append("</tr>");

            for (int i = 0; i < data.Count; i++)
            {
                if (data[i].SoldDate > oldDate)
                {
                    sb.Append("<tr>");
                    sb.AppendFormat("<td colspan=\"4\" class=\"sum\">Total sum for {0}:&nbsp;</td>",
                        oldDate.ToShortDateString());
                    sb.AppendFormat("<td class=\"bold\">{0}</td>", subSum);
                    sb.Append("</tr>");

                    oldDate = data[i].SoldDate;
                    totalSum += subSum;
                    subSum = 0;

                    sb.Append("<tr class=\"grayBack\">");
                    sb.AppendFormat("<th colspan=\"5\" class=\"date\">Date: {0}</th>", 
                        oldDate.ToShortDateString());
                    sb.Append("</tr>");
                    sb.Append("<tr class=\"grayBack\">");
                    sb.Append("<th  class=\"th\">Product</th>");
                    sb.Append("<th  class=\"th\">Quantity</th>");
                    sb.Append("<th  class=\"th\">Unit Price</th>");
                    sb.Append("<th  class=\"th\">Location</th>");
                    sb.Append("<th  class=\"th\">Sum</th>");
                    sb.Append("</tr>");
                }

                subSum += data[i].Sum;

                sb.Append("<tr>");
                sb.AppendFormat("<td>{0}</td>", data[i].ProductName);
                sb.AppendFormat("<td>{0}</td>", data[i].Quantity + " " + data[i].Measure);
                sb.AppendFormat("<td>{0}</td>", data[i].UnitPrice);
                sb.AppendFormat("<td>{0}</td>", data[i].SupermarketName);
                sb.AppendFormat("<td>{0}</td>", data[i].Sum);
                sb.Append("</tr>");
            }

            sb.Append("<tr>");
            sb.AppendFormat("<td colspan=\"4\" class=\"sum\">Total sum for {0}:&nbsp;</td>",
                oldDate.ToShortDateString());
            sb.AppendFormat("<td class=\"bold\">{0}</td>", subSum);
            sb.Append("</tr>");

            totalSum += subSum;

            sb.Append("<tr>");
            sb.Append("<td colspan=\"4\" class=\"sum\">Grand Total:&nbsp;</td>");
            sb.AppendFormat("<td class=\"bold\">{0}</td>", totalSum);
            sb.Append("</tr>");
            sb.Append("</table>");
            
            using (Document document = new Document())
            {
                PdfWriter writer = PdfWriter.GetInstance(document,
                    new FileStream(pdfFullFileName, FileMode.Create));
                document.Open();

                HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

                ICSSResolver cssResolver =
                    XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
                //change this to your CCS file location
                cssResolver.AddCssFile(cssFullFileName, true);
                IPipeline pipeline =
                    new CssResolverPipeline(cssResolver,
                        new HtmlPipeline(htmlContext,
                            new PdfWriterPipeline(document, writer)));

                XMLWorker worker = new XMLWorker(pipeline, true);
                XMLParser p = new XMLParser(worker);
                //p.Parse((TextReader)File.OpenText(@"G:\Template.html"));
                p.Parse(new StringReader(sb.ToString()));
            }
        }
Ejemplo n.º 15
0
 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.º 16
0
        private void processHtml(IElementHandler elementsHandler)
        {
            var cssResolver = new StyleAttrCSSResolver();

            if (CssFilesPath != null && CssFilesPath.Any())
            {
                foreach (var cssFile in CssFilesPath)
                {
                    cssResolver.AddCss(XmlWorkerUtils.GetCssFile(cssFile));
                }
            }

            if (!string.IsNullOrEmpty(InlineCss))
            {
                cssResolver.AddCss(InlineCss, "utf-8", true);
            }

            var htmlContext = new HtmlPipelineContext(new CssAppliersImpl(new UnicodeFontProvider(DefaultFont)));
            if (!string.IsNullOrEmpty(ImagesPath))
            {
                htmlContext.SetImageProvider(new ImageProvider { ImagesPath = ImagesPath });
            }
            htmlContext.CharSet(Encoding.UTF8);

            var tagsProcessorFactory = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
            if (PdfElement != null)
            {
                tagsProcessorFactory.AddProcessor("totalpagesnumber", new TotalPagesNumberXmlWorkerProcessor(PdfElement));
            }

            htmlContext.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagsProcessorFactory);
            var pipeline = new CssResolverPipeline(cssResolver,
                                                   new HtmlPipeline(htmlContext, new ElementHandlerPipeline(elementsHandler, null)));
            var worker = new XMLWorker(pipeline, parseHtml: true);
            var parser = new XMLParser();
            parser.AddListener(worker);
            parser.Parse(new StringReader(Html));
        }
        public void ConvertHtmlToPdf(string xHtml, string css)
        {
            using (var stream = new FileStream(OUTPUT_FILE, 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 TableDataProcessor(), 
                        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(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.º 18
0
        protected 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.º 19
0
        private void iTextSharp(string html)
        {
            System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=BookingDetails.pdf");
            System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            Document pdfDoc = new Document(new Rectangle(922, 1296), 7f, 7f, 7f, 0f);

            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
            pdfDoc.Open();

            HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
            htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

            ICssFile cfile = new CssFileImpl();
            ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
            cssResolver.AddCssFile(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @"App_Data\PDF.all.min.css", true);

            //Pipeline
            IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, writer)));
            //XMLWorker
            XMLWorker worker = new XMLWorker(pipeline, true);
            XMLParser parser = new XMLParser();
            parser.AddListener(worker);
            using (TextReader sr = new StringReader(html))
            {
                parser.Parse(sr);
            }

            parser.Flush();
            pdfDoc.Close();

            System.Web.HttpContext.Current.Response.Write(pdfDoc);
            System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
Ejemplo n.º 20
0
 /**
  * Parses the xml data. This method configures the XMLWorker to parse
  * (X)HTML/CSS and accept unknown tags. Writes the output in the given
  * PdfWriter with the given document.
  *
  * @param writer the PdfWriter
  * @param doc the Document
  * @param inp the reader
  * @throws IOException thrown when something went wrong with the IO
  */
 public void ParseXHtml(PdfWriter writer, Document doc, TextReader inp) {
     CssFilesImpl cssFiles = new CssFilesImpl();
     cssFiles.Add(GetDefaultCSS());
     StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
     HtmlPipelineContext hpc = new HtmlPipelineContext(null);
     hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(GetDefaultTagProcessorFactory());
     IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(hpc, new PdfWriterPipeline(doc,
             writer)));
     XMLWorker worker = new XMLWorker(pipeline, true);
     XMLParser p = new XMLParser();
     p.AddListener(worker);
     p.Parse(inp);
 }
Ejemplo n.º 21
0
 /**
  * Parses the xml data. This method configures the XMLWorker to parse
  * (X)HTML/CSS and accept unknown tags. Writes the output in the given
  * PdfWriter with the given document.
  *
  * @param writer the PdfWriter
  * @param doc the Document
  * @param in the reader
  * @throws IOException thrown when something went wrong with the IO
  */
 public PdfTemplate ParseToTemplate(PdfContentByte cb, TextReader input)
 {
     CssFilesImpl cssFiles = new CssFilesImpl();
     cssFiles.Add(GetDefaultCSS());
     ICSSResolver cssResolver = new StyleAttrSvgCSSResolver(cssFiles);
     SvgPipelineContext hpc = new SvgPipelineContext();
     hpc.SetTagFactory(GetDefaultTagProcessorFactory());
     PdfTemplatePipeline templatePipeline = new PdfTemplatePipeline(cb);
     IPipeline pipeline = new CssResolverPipeline(cssResolver, new SvgPipeline(hpc, templatePipeline));
     XMLWorker worker = new XMLWorker(pipeline, true);
     XMLParser p = new XMLParser();
     p.AddListener(worker);
     p.Parse(input);
     return templatePipeline.GetTemplate();
 }
Ejemplo n.º 22
0
 /**
  * @param d the ElementHandler
  * @param inp the Stream
  * @throws IOException if something went seriously wrong with IO.
  */
 public void ParseXHtml(IElementHandler d, Stream inp, Encoding charset) {
     CssFilesImpl cssFiles = new CssFilesImpl();
     cssFiles.Add(GetDefaultCSS());
     StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
     HtmlPipelineContext hpc = new HtmlPipelineContext(null);
     hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(GetDefaultTagProcessorFactory());
     IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(hpc, new ElementHandlerPipeline(d,
             null)));
     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.º 23
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.º 24
0
        protected void btnGeneratePdf_Click1(object sender, EventArgs e)
        {
            var sb = new StringBuilder();
            sb.Append("<table>");
            sb.Append("<tr>");
            sb.Append("<th class=\"th\">Title</th>");
            sb.Append("<th>Author</th>");
            sb.Append("</tr>");
            MongoDbProvider.db.LoadData<Word>().ToList().ForEach(b =>
            {
                sb.Append("<tr>");
                sb.AppendFormat("<td>{0}</td>", b.WordName);
                sb.AppendFormat("<td>{0}</td>", b.Translation);
                sb.Append("</tr>");
            });
            sb.Append("</table>");

            using (var document = new Document())
            {
                PdfWriter writer = PdfWriter.GetInstance(document,
                    new FileStream(Server.MapPath("loremipsum5.pdf"), FileMode.Append));
                document.Open();

                var htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                //change this to your CCS file location
                cssResolver.AddCssFile(Server.MapPath("style.css"), true);
                var pipeline = new CssResolverPipeline(cssResolver,
                    new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
                var worker = new XMLWorker(pipeline, true);
                var p = new XMLParser(worker);
                p.Parse(new StringReader(sb.ToString()));
            }
        }
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);
        }