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 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(); }
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(); }
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 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"); }
/// <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); }
/** * 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); }
virtual 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); }
protected byte[] RenderHtmlToPDF(string Html) { // http://stackoverflow.com/questions/36180131/using-itextsharp-xmlworker-to-convert-html-to-pdf-and-write-text-vertically // http://stackoverflow.com/questions/20488045/change-default-font-and-fontsize-in-pdf-using-itextsharp Document document = new Document(PageSize.A4, 50f, 30f, 40f, 90f); if (Html.Contains("class=\"landscape\"")) { document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); } MemoryStream stream = new MemoryStream(); TextReader reader = new StringReader(Html); PdfWriter writer = PdfWriter.GetInstance(document, stream); document.AddTitle("muster ag"); XMLWorkerFontProvider fonts = new XMLWorkerFontProvider(); CssAppliers appliers = new CssAppliersImpl(fonts); HtmlPipelineContext context = new HtmlPipelineContext(appliers); context.SetAcceptUnknown(true); context.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); PdfWriterPipeline pdfpipeline = new PdfWriterPipeline(document, writer); HtmlPipeline htmlpipeline = new HtmlPipeline(context, pdfpipeline); var resolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false); resolver.AddCssFile(Server.MapPath("~/Content/inv.pdf.css"), true); CssResolverPipeline csspipeline = new CssResolverPipeline(resolver, htmlpipeline); XMLWorker worker = new XMLWorker(csspipeline, true); XMLParser parser = new XMLParser(worker); document.Open(); parser.Parse(reader); worker.Close(); document.Close(); return(stream.ToArray()); }
public static void ServePdfEmbeddedImages(string url) { using (var doc = new Document(PageSize.LETTER)) { var writer = PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream); writer.InitialLeading = 12.5f; doc.Open(); string lastPart = ""; string[] parts = url.Split('='); if (parts.Count() > 2) { lastPart = "_" + parts[parts.Count() - 2]; } HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Alert" + lastPart + ".pdf"); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); WebClient web = new WebClient(); var html = web.DownloadString(url); var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory(); tagProcessors.RemoveProcessor(HTML.Tag.IMG); // remove the default processor tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use our new processor CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS()); var cssResolver = new StyleAttrCSSResolver(cssFiles); cssResolver.AddCss(@"code { padding: 2px 4px; } img { padding: 4px 8px; }", "utf-8", true); var charset = Encoding.UTF8; var hpc = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider())); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer)); var pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); var worker = new XMLWorker(pipeline, true); var xmlParser = new XMLParser(true, worker, charset); xmlParser.Parse(new StringReader(html)); HttpContext.Current.Response.Write(doc); HttpContext.Current.Response.End(); } //Process.Start("test.pdf"); }
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)); }
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(); }
private static void _add_to_table(Guid applicationId, HttpContext context, PdfPTable mainTable, StyleAttrCSSResolver cssResolver, WikiPDFText text, Font font, PdfPCell cell = null) { if (cell == null) { cell = new PdfPCell(); } cell.Border = 0; cell.HorizontalAlignment = Element.ALIGN_JUSTIFIED; cell.RunDirection = text.IsRTL ? PdfWriter.RUN_DIRECTION_RTL : PdfWriter.RUN_DIRECTION_LTR; cell.SetLeading(0, 2); itsXmlHtml.DefaultTagProcessorFactory tagProcessors = (itsXmlHtml.DefaultTagProcessorFactory)itsXmlHtml.Tags.GetHtmlTagProcessorFactory(); tagProcessors.RemoveProcessor(itsXmlHtml.HTML.Tag.IMG); // remove the default processor tagProcessors.AddProcessor(itsXmlHtml.HTML.Tag.IMG, new CustomImageTagProcessor(applicationId)); // use our new processor //tagProcessors.AddProcessor(itsXmlHtml.HTML.Tag.TABLE, new TableTagProcessor()); HtmlPipelineContext htmlContext = new HtmlPipelineContext(new itsXmlHtml.CssAppliersImpl(new IranSansFontProvider(font))); htmlContext.SetImageProvider(new ImageProvider()); htmlContext.CharSet(Encoding.UTF8); htmlContext.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); ElementsCollector elementsHandler = new ElementsCollector(); CssResolverPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new ElementHandlerPipeline(elementsHandler, null))); itsXml.XMLWorker worker = new itsXml.XMLWorker(pipeline, parseHtml: true); XMLParser parser = new XMLParser(true, worker, Encoding.UTF8); parser.Parse(new StringReader(text.Text)); cell.AddElement(elementsHandler.Paragraph); mainTable.AddCell(cell); }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Invalid number of arguments."); Console.WriteLine("Usage: html2Pdf.exe [input html_file/directory] [default css file]"); return; } List <FileStream> fileList = new List <FileStream>(); if (File.Exists(args[0])) { fileList.Add(new FileStream(args[0], FileMode.Open)); } else if (Directory.Exists(args[0])) { CollectHtmlFiles(fileList, args[0]); } if (fileList.Count == 0) { Console.WriteLine("Invalid html_file/directory"); Console.WriteLine("Usage: html2Pdf.exe [input html_file/directory] [default css file]"); return; } foreach (FileStream fileStream in fileList) { Document doc = new Document(PageSize.LETTER); doc.SetMargins(doc.LeftMargin, doc.RightMargin, 35, 0); String path = Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(fileStream.Name) + ".pdf"; PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create)); doc.Open(); Dictionary <String, String> substFonts = new Dictionary <String, String>(); substFonts["Arial Unicode MS"] = "Helvetica"; CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(XMLWorkerHelper.GetCSS(new FileStream(args[1], FileMode.Open))); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl(new UnembedFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS, substFonts))); hpc.SetImageProvider(new ImageProvider(args[0])); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory()); HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter)); IPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser xmlParse = new XMLParser(true, worker, null); xmlParse.Parse(fileStream); doc.Close(); String cmpPath = Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar + "cmp_" + Path.GetFileNameWithoutExtension(fileStream.Name) + ".pdf"; if (File.Exists(cmpPath)) { CompareTool ct = new CompareTool(path, cmpPath); String outImage = "<testName>-%03d.png".Replace("<testName>", Path.GetFileNameWithoutExtension(fileStream.Name)); String cmpImage = "cmp_<testName>-%03d.png".Replace("<testName>", Path.GetFileNameWithoutExtension(fileStream.Name)); String diffPath = Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar + "diff_" + Path.GetFileNameWithoutExtension(fileStream.Name) + ".png"; String errorMessage = ct.Compare(Path.GetDirectoryName(Path.GetFullPath(fileStream.Name)) + Path.DirectorySeparatorChar + "compare" + Path.DirectorySeparatorChar, diffPath); if (errorMessage != null) { Console.WriteLine(errorMessage); } } } }
public FileContentResult PDFViewMultiple <T>(List <T> models, string viewPath, string Page = "Potrait") { List <byte[]> listBytes = new List <byte[]>(); int CheckModels = 0; TSS_SurveyDocument GetFirstSurvey = models[0] as TSS_SurveyDocument; string SiteSubCategory = GetFirstSurvey.SubCategory; float marginTop = 220; foreach (var model in models) { CheckModels++; TSS_SurveyDocument TempModel = model as TSS_SurveyDocument; var Title = TempModel.SurveyTitle + " " + TempModel.SiteCode.ToString(); TempModel.ChecklistCount = CheckModels; var html = WebUtility.HtmlDecode(GetHtml(TempModel, viewPath)); byte[] bytes; using (var ms = new MemoryStream()) { using (var doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, marginTop, 10)) { using (var writer = PdfWriter.GetInstance(doc, ms)) { doc.Open(); try { doc.NewPage(); doc.SetPageSize(PageSize.A4.Rotate()); 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)); } catch (Exception Ex) { doc.NewPage(); doc.SetPageSize(PageSize.A4.Rotate()); 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("<p>Content Load Failed!</p>")); } finally { doc.Close(); } } } bytes = ms.ToArray(); } using (var reader = new PdfReader(bytes)) { using (var ms = new MemoryStream()) { using (var stamper = new PdfStamper(reader, ms)) { int PageCount = reader.NumberOfPages; for (int i = 1; i <= PageCount; i++) { if (SiteSubCategory.ToUpper() == "CRAN" || SiteSubCategory.ToUpper() == "AIRSCALE") { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Content/Images/ClientLogo/verizon_logo_mini.png")); var pdfContentByte = stamper.GetOverContent(i); image.SetAbsolutePosition(305, 495); pdfContentByte.AddImage(image); } else { iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Content/Images/ClientLogo/rsz_amp-slide-bkg.jpg")); var pdfContentByte = stamper.GetOverContent(i); image.SetAbsolutePosition(285, 465); pdfContentByte.AddImage(image); } if (listBytes.Count == 0) { if (i != 1) { //ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, // new Phrase(Title, new Font(Font.FontFamily.UNDEFINED, 15, Font.BOLD)), 420, 430, 0); } else { if (SiteSubCategory.ToUpper() == "MICROWAVE" || SiteSubCategory.ToUpper() == "CORRECTION" || SiteSubCategory.ToUpper() == "MAINTENANCE" || SiteSubCategory.ToUpper() == "LOS COP" || SiteSubCategory.ToUpper() == "FASTBACK") { ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, new Phrase("Completed by AMP Communications LLC", new Font(Font.FontFamily.UNDEFINED, 15, Font.BOLD)), 430, 20, 0); } } } else { //ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, // new Phrase(Title, new Font(Font.FontFamily.UNDEFINED, 15, Font.BOLD)), 420, 430, 0); } //ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT, new Phrase(String.Format("Page {0} of {1}", i, PageCount), new Font(Font.FontFamily.HELVETICA, 8)), 760, 10, 0); } } listBytes.Add(ms.ToArray()); } } } byte[] Multiplebytes = CombineMultipleByteArrays(listBytes); return(new FileContentResult(Multiplebytes, "application/pdf")); }
public FileContentResult PDFView <T>(T model, string viewPath, string Page = "Potrait") { TSS_SurveyDocument TempModel = model as TSS_SurveyDocument; var Title = TempModel.SurveyTitle + " " + TempModel.SiteCode.ToString(); var html = WebUtility.HtmlDecode(GetHtml(model, viewPath)); byte[] bytes; using (var ms = new MemoryStream()) { using (var doc = new Document()) { using (var writer = PdfWriter.GetInstance(doc, ms)) { doc.Open(); try { 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)); } catch (Exception ex) { 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("<p>Some Content Failed to Load!</p>")); } finally { doc.Close(); } } } bytes = ms.ToArray(); } using (var reader = new PdfReader(bytes)) { using (var ms = new MemoryStream()) { using (var stamper = new PdfStamper(reader, ms)) { int PageCount = reader.NumberOfPages; for (int i = 1; i <= PageCount; i++) { ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT, new Phrase(String.Format("Page {0} of {1}", i, PageCount), new Font(Font.FontFamily.HELVETICA, 8)), 560, 10, 0); } } bytes = ms.ToArray(); } } return(new FileContentResult(bytes, "application/pdf")); }
public async Task <Guid> SubmitWorkItem(HTMLtoPDFJob job) { iTextSharp.text.Rectangle pageSize = PageSize.A4; if (job == null) { throw new Exception("html to pdf job is null"); } switch (job.paperSize) { case PaperSize.a1: pageSize = PageSize.A1; break; case PaperSize.a2: pageSize = PageSize.A2; break; case PaperSize.a3: pageSize = PageSize.A3; break; case PaperSize.a4: pageSize = PageSize.A4; break; case PaperSize.a5: pageSize = PageSize.A5; break; case PaperSize.a6: pageSize = PageSize.A6; break; case PaperSize.a7: pageSize = PageSize.A7; break; case PaperSize.a8: pageSize = PageSize.A8; break; case PaperSize.a9: pageSize = PageSize.A9; break; case PaperSize.letter: pageSize = PageSize.LETTER; break; default: pageSize = PageSize.A4; break; } try { _context.Jobs.Add(job); _context.SaveChanges(); } catch (DbEntityValidationException ex) { string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage)); throw new DbEntityValidationException(errorMessages); } var task = Task.Factory.StartNew(t => { HTMLtoPDFJob ebJob = (HTMLtoPDFJob)t; string htmlStream = ""; string outputFileName = Guid.NewGuid().ToString("N") + ".pdf"; string tempfile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { File.WriteAllBytes(tempfile + ".html", job.FileContent); htmlStream = new StreamReader(tempfile + ".html").ReadToEnd(); if (!string.IsNullOrEmpty(htmlStream)) { var fsOut = new MemoryStream(); var stringReader = new StringReader(htmlStream); Document document = new Document(pageSize, 5, 5, 5, 5); //Document setup var pdfWriter = PdfAWriter.GetInstance(document, fsOut); pdfWriter.SetTagged(); pdfWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_7); pdfWriter.CreateXmpMetadata(); pdfWriter.AddViewerPreference(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE); pdfWriter.Info.Put(new PdfName("Producer"), new PdfString("©" + DateTime.Now.Year.ToString() + " Robobraille.org")); //PDF/A-1A Conformance //pdfWriter = PdfAWriter.GetInstance(document, fsOut, PdfAConformanceLevel.PDF_A_1A); document.Open(); document.AddCreationDate(); //Custom tag processor var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory(); tagProcessors.AddProcessor(HTML.Tag.HTML, new HTMLTagProcessor(document)); tagProcessors.AddProcessor(HTML.Tag.TITLE, new HTMLTagProcessor(document)); tagProcessors.AddProcessor(HTML.Tag.TABLE, new TableTagProcessor()); tagProcessors.AddProcessor(HTML.Tag.TH, new THTagProcessor()); string colorProfilePath = null; string defaultCSSPath = null; try { colorProfilePath = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data/colors/sRGB.profile"); defaultCSSPath = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data/css/default.css"); } catch (Exception e) { colorProfilePath = Path.Combine(ConfigurationManager.AppSettings.Get("ProjectDirectory"), "App_Data/colors/sRGB.profile"); defaultCSSPath = Path.Combine(ConfigurationManager.AppSettings.Get("ProjectDirectory"), "App_Data/css/default.css"); } //Setup color profile var cssResolver = new StyleAttrCSSResolver(); if (colorProfilePath != null && defaultCSSPath != null) { ICC_Profile icc = ICC_Profile.GetInstance(new FileStream(colorProfilePath, FileMode.Open, FileAccess.Read)); pdfWriter.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc); var xmlWorkerHelper = XMLWorkerHelper.GetInstance(); cssResolver.AddCssFile(defaultCSSPath, true);// CSS with default style for all converted docs } //Register system fonts var xmlWorkerFontProvider = new XMLWorkerFontProvider(); Environment.SpecialFolder specialFolder = Environment.SpecialFolder.Fonts; string path = Environment.GetFolderPath(specialFolder); DirectoryInfo directoryInfo = new DirectoryInfo(path); FileInfo[] fontFiles = directoryInfo.GetFiles(); foreach (var fontFile in fontFiles) { if (fontFile.Extension == ".ttf") { xmlWorkerFontProvider.Register(fontFile.FullName); } } //HTML & CSS parsing var cssAppliers = new CssAppliersImpl(xmlWorkerFontProvider); var htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); PdfWriterPipeline pdfWriterPipeline = new PdfWriterPipeline(document, pdfWriter); HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, pdfWriterPipeline); CssResolverPipeline cssResolverPipeline = new CssResolverPipeline(cssResolver, htmlPipeline); XMLWorker xmlWorker = new XMLWorker(cssResolverPipeline, true); XMLParser xmlParser = new XMLParser(xmlWorker); xmlParser.Parse(stringReader); document.Close(); //Data as byte array byte[] fileData = fsOut.ToArray(); try { string mime = "application/pdf"; string fileExtension = ".pdf"; ebJob.DownloadCounter = 0; ebJob.ResultFileExtension = fileExtension; ebJob.ResultMimeType = mime; ebJob.ResultContent = fileData; ebJob.Status = JobStatus.Done; ebJob.FinishTime = DateTime.Now; _context.Jobs.Attach(ebJob); _context.Entry(job).State = EntityState.Modified; _context.SaveChanges(); } catch (Exception ex) { RoboBrailleProcessor.SetJobFaulted(job, _context); throw ex; } } else { RoboBrailleProcessor.SetJobFaulted(job, _context); //Error No HTML file to convert throw new Exception("Error No HTML file to convert"); } } catch (Exception e) { RoboBrailleProcessor.SetJobFaulted(job, _context); //ignore throw e; } }, job); return(job.Id); }
//将html字符串转为字节数组(代码来自百度) private byte[] ConvertHtmlTextToPDF(string htmlText) { if (string.IsNullOrEmpty(htmlText)) { return(null); } //避免當htmlText無任何html tag標籤的純文字時,轉PDF時會掛掉,所以一律加上<p>標籤 //htmlText = "<p>" + htmlText + "</p>"; try { MemoryStream outputStream = new MemoryStream(); //要把PDF寫到哪個串流 byte[] data = Encoding.UTF8.GetBytes(htmlText); //字串轉成byte[] MemoryStream msInput = new MemoryStream(data); // 设置页面 iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(GetPdfSize(75), GetPdfSize(100), 1); pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xFF); Document doc = new Document(pageSize, 0, 0, 0, 0); //document.SetMargins(0f, 0f, 0f, 0f); doc.SetPageSize(pageSize); //Document doc = new Document(); //要寫PDF的文件,建構子沒填的話預設直式A4 PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); //指定文件預設開檔時的縮放為100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //開啟Document文件 doc.Open(); #region 图片的处理 CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS()); var cssResolver = new StyleAttrCSSResolver(cssFiles); var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory(); tagProcessors.RemoveProcessor(HTML.Tag.IMG); // remove the default processor tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor(m_ImageXYDic)); // use new processor var hpc = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider())); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors var charset = Encoding.UTF8; var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer)); var pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); var worker = new XMLWorker(pipeline, true); var xmlParser = new XMLParser(true, worker, charset); xmlParser.Parse(new StringReader(htmlText)); #endregion //使用XMLWorkerHelper把Html parse到PDF檔裡 XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //將pdfDest設定的資料寫到PDF檔 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); outputStream.Close(); return(outputStream.ToArray()); } catch (Exception ex) { throw new ApplicationException("转PDF时异常", ex); } }
public static byte[] HTMLToPdf(string htmlContent) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); StringWriter sw = new StringWriter(new StringBuilder(htmlContent)); HtmlTextWriter hw = new HtmlTextWriter(sw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, ms); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); byte[] Result = ms.ToArray(); return(Result); HtmlAgilityPack.HtmlDocument hd = new HtmlAgilityPack.HtmlDocument(); hd.OptionWriteEmptyNodes = true; //autoclose hr, br etc hd.OptionOutputAsXml = true; //MJW extension to preserve case of server tags hd.LoadHtml(htmlContent); #if (DEBUG) string tmpFile = Path.GetTempFileName(); System.IO.File.WriteAllText(tmpFile, hd.DocumentNode.OuterHtml); System.Diagnostics.Debug.WriteLine(tmpFile); #endif using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) using (TextReader reader = new StringReader(hd.DocumentNode.OuterHtml)) using (Document document = new Document(PageSize.A4, 30, 30, 30, 30)) using (PdfWriter writer = PdfWriter.GetInstance(document, stream)) using (var srHtml = new StringReader(hd.DocumentNode.OuterHtml)) { CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS()); var cssResolver = new StyleAttrCSSResolver(cssFiles); cssResolver.AddCss(@"code { padding: 2px 4px; }", "utf-8", true); var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory(); tagProcessors.RemoveProcessor(HTML.Tag.IMG); // remove the default processor tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use our new processor var charset = Encoding.UTF8; var hpc = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider())); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(document, writer)); var pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); var worker = new XMLWorker(pipeline, true); var xmlParser = new XMLParser(true, worker, charset); document.Open(); xmlParser.Parse(reader); document.Close(); return(stream.ToArray()); } }
/// <summary> /// 產生PDF byte[] /// </summary> /// <param name="htmlText"></param> /// <param name="ds"></param> /// <param name="exportFile">匯出檔案</param> /// <returns></returns> public FileContentResult exportPDF(string htmlText, IDocSetting ds, bool exportFile = false) { byte[] buf = null; string actionName = "exportPDF"; setFileContentType(fileType.pdf); try { if (string.IsNullOrEmpty(htmlText)) { return(null); } //避免當htmlText無任何html tag標籤的純文字時,轉PDF時會掛掉,所以一律加上<p>標籤 //htmlText = "<p>" + htmlText + "</p>"; string[] pageHtml = System.Text.RegularExpressions.Regex.Split(htmlText, ds.pageSplit); Document doc = new Document(iTextSharp.text.PageSize.A4);//要寫PDF的文件,建構子沒填的話預設直式A4 if (ds.SetMargins) { doc.SetMargins(ds.marginLeft, ds.marginRight, ds.marginTop, ds.marginBottom); } //指定文件預設開檔時的縮放為100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //開啟Document文件 MemoryStream outputStream = new MemoryStream();//要把PDF寫到哪個串流 PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); doc.Open(); foreach (string str in pageHtml) { if (str == "\r\n" && pageHtml.Length > 1) { continue; } doc.NewPage(); int page = 1; string text = string.Format("{0}" + str + "{1}", "<p>", "</p>"); byte[] data = Encoding.UTF8.GetBytes(text);//字串轉成byte[] MemoryStream msInput = new MemoryStream(data); //使用XMLWorkerHelper把Html parse到PDF檔裡 Stream fs = null; string sourcePath = ""; string sourceFile = ""; if (!string.IsNullOrWhiteSpace(ds.cssFile)) { sourcePath = System.Web.Hosting.HostingEnvironment.MapPath("~\\StyleSheet\\"); sourceFile = System.IO.Path.Combine(sourcePath, ds.cssFile); fs = System.IO.File.OpenRead(sourceFile); } /*------------------------- Cxr繪圖 2018.09.13 [下] -------------------------*/ #region Cxr //1.版面配置CSS CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(XMLWorkerHelper.GetCSS(File.OpenRead(sourceFile))); // [File.OpenRead] 新增 [StyleAttrCSSResolver] StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); //2.重新撰寫底層Image功能Tag DefaultTagProcessorFactory tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory(); tagProcessors.RemoveProcessor(HTML.Tag.IMG); // remove the default processor tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use new processor //3.重新編譯 //HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider())); HtmlPipelineContext hpc = new HtmlPipelineContext(new CssAppliersImpl(new UnicodeFontFactory())); hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer)); CssResolverPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline); XMLWorker worker = new XMLWorker(pipeline, true); XMLParser xmlParser = new XMLParser(true, worker, Encoding.UTF8); xmlParser.Parse(new StringReader(text)); #endregion /*------------------------- Cxr繪圖 2018.09.13 [上] -------------------------*/ /* 2018.09.13 恢復舊有功能 * //使用XMLWorkerHelper把Html parse到PDF檔裡 * XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, fs, Encoding.UTF8, new UnicodeFontFactory()); * //將pdfDest設定的資料寫到PDF檔 * PdfAction action = PdfAction.GotoLocalPage(page, pdfDest, writer); * writer.SetOpenAction(action); */ msInput.Close(); page++; } doc.Close(); outputStream.Close(); //回傳PDF檔案 buf = outputStream.ToArray(); } catch (Exception ex) { RESPONSE_MSG.message = "產生PDF發生錯誤,請洽資訊人員,錯誤訊息如下所示:" + ex.Message; RESPONSE_MSG.status = RESPONSE_STATUS.EXCEPTION; LogTool.SaveLogMessage(ex, actionName, csName); } return(retunFile(buf)); }