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(); }
public FileResult Export(string GridHtml) { List <string> cssFiles = new List <string>(); cssFiles.Add(@"/Content/bootstrap.css"); var output = new MemoryStream(); var input = new MemoryStream(Encoding.UTF8.GetBytes(GridHtml)); var document = new Document(); var writer = PdfWriter.GetInstance(document, output); writer.CloseStream = false; document.Open(); var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssFiles.ForEach(i => cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath(i), 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(input); document.Close(); output.Position = 0; return(File(output.ToArray(), "application/pdf", "Reporte.pdf")); }
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(); }
private byte[] BindPdf(string pHTML) { var cssText = "~/Content/css/facture.css"; byte[] bPDF = null; var memoryStream = new MemoryStream(); var input = new MemoryStream(Encoding.UTF8.GetBytes(pHTML)); var document = new Document(PageSize.A4, 10f, 10f, 100f, 0f); var writer = PdfWriter.GetInstance(document, memoryStream); writer.CloseStream = false; document.Open(); var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath(cssText), 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(input); document.Close(); bPDF = memoryStream.ToArray(); return(bPDF); }
/** * 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); }
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); }
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()); } }
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); } }
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 byte[] GetPDF(string conteudo, string cssFile) { Document doc = new Document(PageSize.A4, 50, 50, 50, 50); using (var ms = new MemoryStream()) { var writer = PdfWriter.GetInstance(doc, ms); writer.CloseStream = false; doc.Open(); var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); var cssResolver = XMLWorkerHelper.GetInstance() .GetDefaultCssResolver(false); cssResolver.AddCssFile(cssFile, true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(doc, writer))); var worker = new XMLWorker(pipeline, true); var xmlParser = new XMLParser(worker); xmlParser.Parse(new MemoryStream(Encoding.UTF8 .GetBytes(conteudo))); doc.Close(); return(ms.GetBuffer()); } }
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); } } } }
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); } }
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); } }
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(); }
//private byte[] parseHtml(String html) //{ // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // // step 1 // Document document = new Document(); // // step 2 // PdfWriter writer = PdfWriter.getInstance(document, baos); // // step 3 // document.open(); // // step 4 // XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, // new FileInputStream(html)); // // step 5 // document.close(); // // return the bytes of the PDF // return baos.toByteArray(); //} private byte[] ConvertHtmlToPdf(string html, string cssPath) { Document document = new Document(PageSize.A1); byte[] pdfBytes; using (var ms = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(document, ms); writer.CloseStream = false; document.Open(); HtmlPipelineContext htmlPipelineContext = new HtmlPipelineContext(null); htmlPipelineContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(cssPath, true); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlPipelineContext, new PdfWriterPipeline(document, writer))); XMLWorker xmlWorker = new XMLWorker(pipeline, true); XMLParser xmlParser = new XMLParser(xmlWorker); xmlParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(html))); // document.NewPage(); document.Close(); pdfBytes = ms.GetBuffer(); } return(pdfBytes); }
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); }
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); }
private MemoryStream GetPDFStream(string htmlContent, string CSSContent) { iTextSharp.text.Document document = new iTextSharp.text.Document(); try { MemoryStream memStream = new System.IO.MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(document, memStream); document.Open(); var interfaceProps = new Dictionary <string, Object>(); var ih = new ImageHander() { BaseUri = Request.Url.ToString() }; interfaceProps.Add(HTMLWorker.IMG_PROVIDER, ih); var cssResolver = new StyleAttrCSSResolver(); var CSSStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(CSSContent)); var cssFile = XMLWorkerHelper.GetCSS(CSSStream); cssResolver.AddCss(cssFile); CssAppliers ca = new CssAppliersImpl(); HtmlPipelineContext hpc = new HtmlPipelineContext(ca); hpc.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer); CssResolverPipeline css = new CssResolverPipeline(cssResolver, new HtmlPipeline(hpc, pdf)); XMLWorker xworker = new XMLWorker(css, true); XMLParser p = new XMLParser(xworker); var HTMLStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlContent)); var CSSStream1 = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(CSSContent)); using (TextReader sr = new StringReader(htmlContent)) { XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, HTMLStream, CSSStream1); //p.Parse(sr); } writer.CloseStream = false; document.Close(); return(memStream); } catch (Exception ex) { document.Close(); litPdfViewMsg.Text = ex.Message; //throw ex; return(null); } }
private byte[] InternalGeneratePdf <T>(Action <PdfWriter, Document> configureSettings, T model = null, string viewName = null, List <BasePageSnippet> pageSnippets = null, Margins margins = null) where T : class { ControllerContext.Controller.ViewData.Model = model; byte[] output; var document = margins == null ? new Document() : new Document(margins.PageSize, margins.Left, margins.Right, margins.Top, margins.Bottom); using (document) { using (var workStream = new MemoryStream()) { var writer = PdfWriter.GetInstance(document, workStream); writer.CloseStream = false; if (pageSnippets != null) { var aggregateHelper = new AggregateHelper(pageSnippets, InternalGeneratePdf); writer.PageEvent = aggregateHelper; } configureSettings?.Invoke(writer, document); document.Open(); using (var reader = new StringReader(RenderRazorView(viewName))) { var workerInstance = XMLWorkerHelper.GetInstance(); var tagProcessors = Tags.GetHtmlTagProcessorFactory(); if (!string.IsNullOrEmpty(ImageBasePath)) { tagProcessors.RemoveProcessor(HTML.Tag.IMG); tagProcessors.AddProcessor(new ImageTagProcessor(ImageBasePath), new[] { HTML.Tag.IMG }); } var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(tagProcessors); var cssResolver = workerInstance.GetDefaultCssResolver(true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var parser = new XMLParser(worker); parser.Parse(reader); document.Close(); output = workStream.ToArray(); } } } return(output); }
/*-------------------------------------------------------- * Exportar um HTML fornecido. * - O HTML. * - Nome do Arquivo. * - Link para o CSS. * ----------------------------------------------------------*/ public static void Export(string html, string fileName, string linkCss) { ////reset response HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/pdf"; ////define pdf filename HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName); //Gera o arquivo PDF using (var document = new Document(PageSize.A4, 40, 40, 40, 40)) { //html = FormatImageLinks(html); //define o output do HTML var memStream = new MemoryStream(); TextReader xmlString = new StringReader(html); PdfWriter writer = PdfWriter.GetInstance(document, memStream); writer.PageEvent = new PDFWriteEvents(); document.Open(); //Registra todas as fontes no computador cliente. FontFactory.RegisterDirectories(); // Set factories var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); // Set css ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(HttpContext.Current.Server.MapPath(linkCss), true); // Exporta IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var xmlParse = new XMLParser(true, worker); xmlParse.Parse(xmlString); xmlParse.Flush(); document.Close(); document.Dispose(); HttpContext.Current.Response.BinaryWrite(memStream.ToArray()); } HttpContext.Current.Response.End(); HttpContext.Current.Response.Flush(); }
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"); }
public byte[] Render(string htmlText, string pageTitle, string linkCss, bool horizontal) { byte[] renderedBuffer; using (var outputMemoryStream = new MemoryStream()) { using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin)) { if (horizontal) { pdfDocument.SetPageSize(PageSize.A4.Rotate()); } PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream); pdfWriter.CloseStream = false; pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle }; pdfDocument.Open(); // register all fonts in current computer FontFactory.RegisterDirectories(); // Set factories var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); // Set css ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(HttpContext.Current.Server.MapPath(linkCss), true); cssResolver.AddCss(".shadow {background-color: #ebdddd; }", true); //Export IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDocument, pdfWriter))); using (var xmlString = new StringReader(htmlText)) { var worker = new XMLWorker(pipeline, true); var xmlParse = new XMLParser(true, worker); xmlParse.Parse(xmlString); xmlParse.Flush(); } } renderedBuffer = new byte[outputMemoryStream.Position]; outputMemoryStream.Position = 0; outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length); } return(renderedBuffer); }
public byte[] GeneratePdf <T>(Action <PdfWriter, Document> configureSettings, T model = null, string viewName = null) where T : class { byte[] output; var document = Margins == null ? new Document() : new Document(Margins.PageSize, Margins.Left, Margins.Right, Margins.Top, Margins.Bottom); using (document) { using (var workStream = new MemoryStream()) { var writer = PdfWriter.GetInstance(document, workStream); writer.CloseStream = false; configureSettings?.Invoke(writer, document); document.Open(); var renderedView = Parser.RenderView(viewName, model, Templates); using (var reader = new StringReader(renderedView)) { var workerInstance = XMLWorkerHelper.GetInstance(); var tagProcessors = Tags.GetHtmlTagProcessorFactory(); if (!string.IsNullOrEmpty(ImageBasePath)) { tagProcessors.RemoveProcessor(HTML.Tag.IMG); tagProcessors.AddProcessor(new ImageTagProcessor(ImageBasePath), new[] { HTML.Tag.IMG }); } var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(tagProcessors); var cssResolver = workerInstance.GetDefaultCssResolver(true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); var worker = new XMLWorker(pipeline, true); var parser = new XMLParser(worker); parser.Parse(reader); document.Close(); output = workStream.ToArray(); } } } return(output); }
public byte[] GeneratePDF2(string name) { byte[] result; string Path = AppDomain.CurrentDomain.BaseDirectory; Path = Path.Substring(0, Path.Length - 10); var Pathcss = string.Format("{0}{1}", Path, "htmltoPdf\\Content\\bootstrap.min.css"); List <string> cssFile = new List <string>(); cssFile.Add(Pathcss); MemoryStream stream = null; string Html = html(); string ModifiedFileName = string.Empty; using (stream = new MemoryStream()) { Document pdfDoc = new Document(PageSize.A4, 60f, 60f, 50f, 40f); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); writer.PageEvent = new NumPage(); pdfDoc.Open(); HtmlPipelineContext htmlcontext = new HtmlPipelineContext(null); htmlcontext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); cssResolver.AddCssFile(Pathcss, true); //cssFile.ForEach(x=>cssResolver.AddCssFile(x,true)); IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlcontext, new PdfWriterPipeline(pdfDoc, writer))); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser xmlparser = new XMLParser(worker); xmlparser.Parse(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(Html))); pdfDoc.Close(); result = stream.GetBuffer(); //PdfReader reader = new PdfReader(stream); //PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting); //reader.Close(); //return File(stream.ToArray(), "application/pdf", "Grid.pdf"); } return(result); }
private static bool GeneratePdf(string htmlText, string fileFullName, string watermarkText, PdfFont font) { if (string.IsNullOrEmpty(htmlText)) { return(false); } htmlText = "<p>" + htmlText + "</p>"; var document = new Document(); var writer = PdfWriter.GetInstance(document, new FileStream(fileFullName, FileMode.Create)); if (!string.IsNullOrEmpty(watermarkText)) { writer.PageEvent = new PdfWatermarkPageEvent(watermarkText); } document.Open(); //pipeline var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); htmlContext.SetImageProvider(new ChannelImageProvider()); htmlContext.SetCssAppliers(new CssAppliersImpl(GetFontProviderBy(font))); var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); //parse byte[] data = Encoding.UTF8.GetBytes(htmlText); var msInput = new MemoryStream(data); var worker = new XMLWorker(pipeline, true); var parser = new XMLParser(worker); parser.Parse(msInput); //XMLWorkerHelper.GetInstance().ParseXHtml(..) var pdfDest = new PdfDestination(PdfDestination.XYZ, 0, document.PageSize.Height, 1f); var action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); //close document.Close(); msInput.Close(); return(true); }
/// <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()); } } } } }
/** * @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(); 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); p.Parse(inp); }
virtual public void SetUp() { StyleAttrCSSResolver css = new StyleAttrCSSResolver(); css.AddCss("dummy { key1: value1; key2: value2 } .aklass { key3: value3;} #dumid { key4: value4}", true); CssResolverPipeline p = new CssResolverPipeline(css, null); Tag t = new Tag("dummy"); t.Attributes["id"] = "dumid"; t.Attributes["class"] = "aklass"; WorkerContextImpl context = new WorkerContextImpl(); p.Init(context); IPipeline open = p.Open(context, t, null); css2 = t.CSS; }
/** * 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 */ virtual 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); }