Ejemplo n.º 1
0
        private ActionResult CreatePdfReport(SuratPengesahanHospitalModel model)
        {
            string pdfString  = GetSuratPengesahanHospitalString(model);
            string exportData = string.Format(pdfString);
            var    bytes      = System.Text.Encoding.UTF8.GetBytes(exportData);

            var document = new Document(PageSize.A4, 30, 30, 28, 28);

            using (var input = new MemoryStream(bytes))
            {
                var output = new MemoryStream();
                var writer = PdfWriter.GetInstance(document, output);
                writer.CloseStream = false;
                document.Open();

                var xmlWorker = XMLWorkerHelper.GetInstance();
                iTextSharp.text.Font contentFont =
                    iTextSharp.text.FontFactory.GetFont("Arial", 7, iTextSharp.text.Font.BOLD);

                xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);

                document.Close();
                output.Position = 0;

                return(new FileStreamResult(output, "application/pdf"));
            }
        }
Ejemplo n.º 2
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();
        }
Ejemplo n.º 3
0
        virtual public void ParseXfaOnlyXML()
        {
            TextReader 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 + "Test.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());
            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();
        }
        public void Go()
        {
            var outputFile = Helpers.IO.GetClassOutputPath(this);
            var fixedHtml  = FixBrokenServerControlMarkup(HTML);

            using (FileStream stream = new FileStream(
                       outputFile,
                       FileMode.Create,
                       FileAccess.Write))
            {
                using (var document = new Document())
                {
                    PdfWriter writer = PdfWriter.GetInstance(
                        document, stream
                        );
                    document.Open();
                    using (var xmlSnippet = new StringReader(fixedHtml))
                    {
                        XMLWorkerHelper.GetInstance().ParseXHtml(
                            writer, document, xmlSnippet
                            );
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public void RunBugSamples()
        {
            bool success = true;

            foreach (String str in list)
            {
                try {
                    Console.WriteLine(str);
                    Document  doc    = new Document();
                    PdfWriter writer = null;
                    try {
                        writer = PdfWriter.GetInstance(doc, new FileStream(TARGET + "/bugs/" + str
                                                                           + ".pdf", FileMode.Create));
                    }
                    catch (DocumentException e) {
                        Console.WriteLine(e);
                    }
                    doc.Open();
                    XMLWorkerHelper helper = XMLWorkerHelper.GetInstance();
                    helper.ParseXHtml(writer, doc, File.OpenText(RESOURCES + "/bugs/" + str));
                    doc.Close();
                }
                catch (Exception e) {
                    Console.WriteLine(e);
                    Console.WriteLine(e);
                    success = false;
                }
            }
            if (!success)
            {
                Assert.Fail();
            }
        }
Ejemplo n.º 6
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;

                    configureSettings?.Invoke(writer, document);
                    document.Open();


                    using (var reader = new MemoryStream(Encoding.UTF8.GetBytes(RenderRazorView(context, viewName))))
                    {
                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader, null, FontFactory.FontImp);

                        document.Close();
                        output = workStream.ToArray();
                    }
                }
            }
            return(output);
        }
Ejemplo n.º 7
0
        public IHttpActionResult TestInvoice()
        {
            try
            {
                byte[] pdf; // result will be here

                var cssText = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Areas/Master/Views/Driver/bootstrap.css"));
                var html    = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Areas/Master/Views/Driver/driverinvoice.html"));
                using (var memoryStream = new MemoryStream())
                {
                    var document = new Document(PageSize.A4, 25f, 25f, 25f, 25f);
                    var writer   = PdfWriter.GetInstance(document, memoryStream);
                    document.Open();

                    using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
                    {
                        using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
                        {
                            XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
                        }
                    }
                    document.Close();

                    pdf = memoryStream.ToArray();
                    FileStream fs = new FileStream(@"Downloads\driverinvoice.pdf", FileMode.OpenOrCreate);
                    fs.Write(pdf, 0, pdf.Length);
                    fs.Close();
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                return(Ok());
            }
        }
Ejemplo n.º 8
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.º 9
0
        public static byte[] Render(string html, List <string> cssFiles = null, Rectangle pageSize = null)
        {
            if (pageSize == null)
            {
                pageSize = PageSize.A4.Rotate();
            }
            using (var stream = new MemoryStream())
            {
                // create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
                using (var document = new Document(pageSize))
                {
                    // create a writer that's bound to our PDF abstraction and our stream
                    using (var writer = PdfWriter.GetInstance(document, stream))
                    {
                        // open the document for writing
                        document.Open();
                        HtmlPipelineContext  htmlContext = new HtmlPipelineContext(null);
                        ITagProcessorFactory factory     = Tags.GetHtmlTagProcessorFactory();
                        factory.AddProcessor(new CustomImageHTMLTagProcessor(), new string[] { "img" });
                        htmlContext.SetTagFactory(factory);

                        var isAnyCssFiles = cssFiles != null && cssFiles.Count > 0;
                        //create a cssresolver to apply css
                        ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(!isAnyCssFiles);
                        if (isAnyCssFiles)
                        {
                            foreach (var cssfile in cssFiles)
                            {
                                if (cssfile.StartsWith("http"))
                                {
                                    cssResolver.AddCssFile(cssfile, true);
                                }
                                else
                                {
                                    cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath(cssfile), true);
                                }
                            }
                        }
                        //create and attach pipeline
                        IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));

                        XMLWorker worker    = new XMLWorker(pipeline, true);
                        XMLParser xmlParser = new XMLParser(true, worker);
                        using (var srHtml = new StringReader(html))
                        {
                            xmlParser.Parse(srHtml);
                        }

                        // close document
                        document.Close();
                    }
                }

                // get bytes from stream
                byte[] bytes = stream.ToArray();
                bytes = AddPageNumbers(bytes, pageSize);
                // success
                return(bytes);
            }
        }
Ejemplo n.º 10
0
        public static byte[] GetPDF(string html)
        {
            byte[] bPDF = null;

            MemoryStream ms        = new MemoryStream();
            TextReader   txtReader = new StringReader(html);

            // 1: create object of a itextsharp document class
            Document doc = new Document(PageSize.A4, 25, 25, 25, 25);

            // 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file
            PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);

            // 3: we create a worker parse the document
            doc.Open();
            HTMLWorker   htmlWorker = new HTMLWorker(doc);
            StringReader sr         = new StringReader(html);

            XMLWorkerHelper.GetInstance().ParseXHtml(oPdfWriter, doc, sr);
            // 4: we open document and start the worker on the document

            //htmlWorker.StartDocument();

            //// 5: parse the html into the document
            //htmlWorker.Parse(txtReader);

            //// 6: close the document and the worker
            //htmlWorker.EndDocument();
            //htmlWorker.Close();
            doc.Close();

            bPDF = ms.ToArray();

            return(bPDF);
        }
Ejemplo n.º 11
0
        public static bool PDFFromHTMLFile(string htmlFileName, string pdffile, string css)
        {
            byte[] pdf; // result will be here

            var cssText = File.ReadAllText(css);
            var html    = htmlFileName; //File.ReadAllText(htmlFileName);


            using (var memoryStream = new MemoryStream())
            {
                var document = new Document(PageSize.LETTER, 20, 20, 60, 60);
                var writer   = PdfWriter.GetInstance(document, memoryStream);
                document.Open();

                using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
                {
                    using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
                    {
                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
                    }
                }

                document.Close();

                pdf = memoryStream.ToArray();
                File.WriteAllBytes(pdffile, pdf);
            }
            return(true);
        }
Ejemplo n.º 12
0
        public string GenerateFromHtml(string html)
        {
            string tempPath = Path.GetTempFileName();

            var stream = new FileStream(tempPath, FileMode.Create);

            // create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
            var document = new Document();

            document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());

            // create a writer that's bound to our PDF abstraction and our stream
            var writer = PdfWriter.GetInstance(document, stream);

            // open the document for writing
            document.Open();

            // read html data to StringReader
            var stringReader = new StringReader(html);


            var xmlWorker = XMLWorkerHelper.GetInstance();

            xmlWorker.ParseXHtml(writer, document, stringReader);

            // close document
            document.Close();
            stream.Close();

            return(tempPath);
        }
Ejemplo n.º 13
0
        virtual public void CreateAllSamples()
        {
            bool success = true;

            foreach (String str in list)
            {
                try {
                    Console.WriteLine(str);
                    Document  doc    = new Document();
                    PdfWriter writer = null;
                    try {
                        writer = PdfWriter.GetInstance(doc,
                                                       new FileStream(TARGET + "/" + str + "Test.pdf", FileMode.Create));
                    }
                    catch (DocumentException e) {
                        Console.WriteLine(e);
                    }
                    doc.Open();
                    StreamReader    bis    = File.OpenText(RESOURCE_TEST_PATH + "/snippets/" + str + "snippet.html");
                    XMLWorkerHelper helper = XMLWorkerHelper.GetInstance();
                    helper.ParseXHtml(writer, doc, bis);
                    doc.Close();
                }
                catch (Exception e) {
                    Console.Write(e);
                    success = false;
                }
            }
            if (!success)
            {
                Assert.Fail();
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// https://stackoverflow.com/questions/27015644/how-to-add-a-rich-textbox-html-to-a-table-cell
 /// </summary>
 /// <returns></returns>
 private byte[] GenerateData()
 {
     byte[] data = null;
     using (var ms = new MemoryStream())
     {
         using (var doc = new Document())
         {
             using (var writer = PdfWriter.GetInstance(doc, ms))
             {
                 doc.Open();
                 string htmlString = @"<p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>";
                 //var css = @".headline{font-size:200%}";
                 PdfPTable table = new PdfPTable(2);
                 table.AddCell("Some Rich Text");
                 PdfPCell cell = new PdfPCell();
                 foreach (var item in XMLWorkerHelper.ParseToElementList(htmlString, null))
                 {
                     cell.AddElement(item);
                 }
                 table.AddCell(cell);
                 doc.Add(table);
                 doc.Close();
             }
         }
         data = ms.ToArray();
     }
     return(data);
 }
Ejemplo n.º 15
0
        public void Go()
        {
            var OUTPUT = Helpers.IO.GetClassOutputPath(this);

            string HTML = @"
<html><head>
<title>Test HTML</title>
</head><body>
<div>The 1<sup>st</sup> day of the month</div>
</body></html>
";

            string css = "sup { vertical-align: super; font-size: 0.8em; }";

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

                    using (var htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(HTML)))
                    {
                        using (var cssStream = new MemoryStream(Encoding.UTF8.GetBytes(css)))
                        {
                            XMLWorkerHelper.GetInstance().ParseXHtml(
                                writer, document, htmlStream, cssStream
                                );
                        }
                    }
                }
                File.WriteAllBytes(OUTPUT, stream.ToArray());
            }
        }
Ejemplo n.º 16
0
 //Método que permite crear un pdf de la lista de los alumnos registrados.
 //Permite a los restaurantes imprimirla para llevar un control de los servicios ofrecidos.
 protected void btCrear_Click(object sender, EventArgs e)
 {
     using (StringWriter sw = new StringWriter())
     {
         using (HtmlTextWriter hw = new HtmlTextWriter(sw))
         {
             GridView1.RenderControl(hw);
             StringReader sr = new StringReader(sw.ToString());
             //Se crea declara e instancia el documento con sus dimensiones como parámetros
             Document dc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
             //Se declara e instancia la clase que permite escribir sobre el documento como pdf.
             PdfWriter wr = PdfWriter.GetInstance(dc, Response.OutputStream);
             dc.Open();
             //Método que convierte el pdf en html
             XMLWorkerHelper.GetInstance().ParseXHtml(wr, dc, sr);
             dc.Close();
             Response.ContentType = "application/pdf";
             Response.AddHeader("content-disposition", "attachment;filename=" + Session["Rest"] + ".pdf");
             Response.Cache.SetCacheability(HttpCacheability.NoCache);
             Response.Write(dc);
             //Fin del stream
             Response.End();
         }
     }
 }
Ejemplo n.º 17
0
        public byte[] Generate()
        {
            var result = default(byte[]);

            Validate();
            var indexStart = _html.IndexOf(HeaderTagStart);
            var indexEnd   = _html.IndexOf(HeaderTagEnd);

            var headerContent = _html.Substring(indexStart, indexEnd - indexStart);
            var eventsHelper  = new PageEventHelper(headerContent);

            using (var ms = new MemoryStream())
                using (var document = new Document(PageSize.A4, 0, 0, 10, 20))
                {
                    var writer = PdfWriter.GetInstance(document, ms);
                    writer.PageEvent = eventsHelper;

                    using (var reader = new StringReader(_html))
                    {
                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);
                        document.Close();
                        result = ms.GetBuffer();
                    }
                }

            return(result);
        }
Ejemplo n.º 18
0
        public FileResult Export(string GridHtml)
        {
            var fpath = "";

            try
            {
                using (MemoryStream stream = new System.IO.MemoryStream())
                {
                    // fpath = HttpContext.Server.MapPath("~/PDFFiles/Quotation/");
                    StringReader sr     = new StringReader(GridHtml);
                    Document     pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
                    PdfWriter    writer = PdfWriter.GetInstance(pdfDoc, stream);
                    pdfDoc.Open();
                    iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(HttpContext.Server.MapPath("~/NewCssAndTheme/img/ssmlogo.jpg"));
                    image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
                    image1.SetAbsolutePosition(20, 780);
                    image1.ScaleToFit(80f, 80f);

                    pdfDoc.Add(image1);
                    XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
                    pdfDoc.Close();
                    return(File(stream.ToArray(), "application/pdf", "Quotation.pdf"));

                    //  return File(HttpContext.Server.MapPath("~/PDFFiles/Quotation/") , "application/pdf", "Grid.pdf");
                }
            }
            catch (Exception ex)
            {
                ErrorHandlerClass.LogError(ex);
            }
            return(null);
        }
Ejemplo n.º 19
0
    public byte[] ConvertHtmlTextToPDF(string htmlText)
    {
        if (string.IsNullOrEmpty(htmlText))
        {
            return(null);
        }
        //避免當htmlText無任何html tag標籤的純文字時,轉PDF時會掛掉,所以一律加上<p>標籤
        htmlText = "<p>" + htmlText + "</p>";
        //System.IO.MemoryStream
        MemoryStream outputStream = new MemoryStream();          //要把PDF寫到哪個串流

        byte[]       data    = Encoding.UTF8.GetBytes(htmlText); //字串轉成byte[]
        MemoryStream msInput = new MemoryStream(data);
        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();
        //使用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();
        //回傳PDF檔案
        return(outputStream.ToArray());
    }
Ejemplo n.º 20
0
        public byte[] GeneratePdfOutputFromHtmlString(ControllerContext context, object model        = null, string htmlString = null,
                                                      Action <PdfWriter, Document> configureSettings = null)
        {
            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();


                    using (var reader = new StringReader(htmlString))
                    {
                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);

                        document.Close();
                        output = workStream.ToArray();
                    }
                }
            }
            return(output);
        }
Ejemplo n.º 21
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"));
        }
 public static ICssFile GetCssFile(string filePath)
 {
     using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
     {
         return(XMLWorkerHelper.GetCSS(stream));
     }
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Html生成PDF,图片以http形式保存(保存后其会存在PDF中)
        /// </summary>
        /// <param name="css">CSS文本</param>
        /// <param name="destPath">PDF保存虚拟路径</param>
        public static void HtmlToPdf(string html, string css, string destPath)
        {
            //1,mThe document has no pages.
            //答:html的样式关闭有问题,如<body>无关闭标签,或列表无法合并
            Document   doc = new Document();
            FileStream fs  = null;

            try
            {
                fs = new FileStream(function.VToP(destPath), FileMode.Create);
                PdfWriter writer = PdfWriter.GetInstance(doc, fs);
                doc.Open();
                //string html = SafeSC.ReadFileStr("/test/test.html"), css = SafeSC.ReadFileStr("/test/test.css");
                using (var htmlMS = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
                {
                    using (var cssMS = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(css)))
                    {
                        var xmlWorker = XMLWorkerHelper.GetInstance();
                        xmlWorker.ParseXHtml(writer, doc, htmlMS, cssMS, System.Text.Encoding.UTF8, new UnicodeFontFactory());
                    }
                }
                doc.Close();
            }
            catch (Exception ex) { throw new Exception(ex.Message); }
            finally { if (fs != null)
                      {
                          doc.Dispose(); fs.Dispose();
                      }
            }
        }
Ejemplo n.º 24
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.º 25
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.º 26
0
        public FileContentResult GetPdf()
        {
            //var html = GetHtml();
            //Byte[] bytes = new SimplePechkin(new GlobalConfig()).Convert(html);
            //return new FileContentResult(bytes, "application/pdf");
            byte[] pdf; // result will be here

            using (var memoryStream = new MemoryStream())
            {
                var document = new Document(PageSize.A4, 50, 50, 60, 60);
                var writer   = PdfWriter.GetInstance(document, memoryStream);
                document.Open();

                using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(_css)))
                {
                    using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(GetHtml())))
                    {
                        XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
                    }
                }

                document.Close();

                pdf = memoryStream.ToArray();
            }
            return(new FileContentResult(pdf, "application/pdf"));
        }
        static void Main(string[] args)
        {
            //Build HTML document
            StringBuilder sb = new StringBuilder();

            sb.Append("<body>");
            sb.Append("<h1 style=\"text-align:center;\">これは日本語のテキストの例です。</h1>");
            sb.Append("</body>");
            //Create our document object
            Document Doc = new Document(PageSize.A4);

            //Create our file stream
            using (FileStream fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf"), FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                //Bind PDF writer to document and stream
                PdfWriter writer = PdfWriter.GetInstance(Doc, fs);
                //Open document for writing
                Doc.Open();
                //Add a page
                Doc.NewPage();
                MemoryStream msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(sb.ToString()));
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, Doc, msHtml, null, Encoding.UTF8, new UnicodeFontFactory());
                //Close the PDF
                Doc.Close();
            }
        }
        public void Go()
        {
            var outputFile = Helpers.IO.GetClassOutputPath(this);

            HTML = HTML.Replace("&amp;#160;", "\u00A0");
            using (var stringReader = new StringReader(HTML))
            {
                using (FileStream stream = new FileStream(
                           outputFile,
                           FileMode.Create,
                           FileAccess.Write))
                {
                    using (var document = new Document())
                    {
                        PdfWriter writer = PdfWriter.GetInstance(
                            document, stream
                            );
                        document.Open();
                        XMLWorkerHelper.GetInstance().ParseXHtml(
                            writer, document, stringReader
                            );
                    }
                }
            }
        }
Ejemplo n.º 29
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.º 30
0
        public byte[] GetPDFBalance(ConsortiumBalanceStruct consortiumBalanceStruct)
        {
            Byte[] resultPDF;

            using (var ms = new MemoryStream())
            {
                using (var doc = new Document())
                {
                    using (var writer = PdfWriter.GetInstance(doc, ms))
                    {
                        doc.Open();
                        using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(consortiumBalanceStruct.HtmlBalanceStyles.ToString())))
                        {
                            using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(consortiumBalanceStruct.HtmlBalance.ToString())))
                            {
                                XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
                            }
                        }


                        doc.Close();
                    }
                }
                resultPDF = ms.ToArray();
            }

            return(resultPDF);
        }