virtual public void SetUp() { LoggerFactory.GetInstance().SetLogger(new SysoLogger(3)); files = new CssFilesImpl(); StyleAttrCSSResolver resolver = new StyleAttrCSSResolver(files); string u = RESOURCES + "/css/style.css"; resolver.AddCssFile(u.Replace("%20", " "), false); // fix url conversion of space (%20) for File Dictionary <String, String> attr = new Dictionary <String, String>(); t = new Tag("body", attr); }
static protected void TransformHtml2Pdf(FileStream inputHtml, Document doc, PdfWriter pdfWriter) { CssFilesImpl cssFiles = new CssFilesImpl(); cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS()); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles); String Css1 = "https://specialtyonlinestg.cardinalhealth.com/CardinalHealthSpecialty/themes/html/SS_SPDCardinalHealth/css/globalStyles.css?version=RI_20121023"; String Css2 = "https://specialtyonlinestg.cardinalhealth.com/CardinalHealthSpecialty/themes/html/SS_SPDCardinalHealth/css/SPDCSS/CAHPHReconciliationPortletView.css?version=AC_20120717"; try { cssResolver.AddCssFile(Css1, true); cssResolver.AddCssFile(Css2, true); } catch (CssResolverException e) { // TODO Auto-generated catch block } HtmlPipelineContext htmlContext = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider())); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); htmlContext.SetPageSize(new Rectangle(doc.Left, doc.Bottom, doc.Right, doc.Top)); // Pipelines PdfWriterPipeline pdf = new PdfWriterPipeline(doc, pdfWriter); HtmlPipeline html = new HtmlPipeline(htmlContext, pdf); CssResolverPipeline css = new CssResolverPipeline(cssResolver, html); XMLWorker worker = new XMLWorker(css, true); XMLParser parser = new XMLParser(worker, Encoding.UTF8); parser.Parse(inputHtml, Encoding.UTF8); }
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); }
public static byte[] export_as_pdf(Guid applicationId, Guid?currentUserId, bool isUser, DownloadedFileMeta meta, string title, string description, List <string> keywords, List <KeyValuePair <Guid, string> > wikiTitles, Dictionary <Guid, List <KeyValuePair <string, string> > > wikiParagraphs, Dictionary <string, string> metaData, List <string> authors, Guid?coverId, Guid?coverOwnerNodeId, string password, HttpContext context) { bool hasCustomCover = coverId.HasValue && coverOwnerNodeId.HasValue && currentUserId.HasValue; List <WikiPDFText> wikiCover = hasCustomCover ? new List <WikiPDFText>() : get_default_cover(applicationId, isUser, title, metaData, authors); string strKeywords = string.Join(" - ", keywords); WikiPDFText wikiTitle = new WikiPDFText(applicationId, @"<br><br><p style='text-align:center;'><strong><span style='color:DarkSlateGray;'>" + title + "</span></strong></p><br><br>"); List <WikiPDFText> wikiDesc = convert_div_to_p(applicationId, new List <WikiPDFText>() { new WikiPDFText(applicationId, string.IsNullOrEmpty(description) ? "" : @"<br><p class='NodeAbs'>" + description + "</p><br>") }); WikiPDFText wikiKeywords = new WikiPDFText(applicationId, string.IsNullOrEmpty(strKeywords) ? "" : @"<br><p> " + strKeywords + " </p><br>"); string pdfTitles = string.Empty; WikiPDFText wikiPDFTitles = null; List <WikiPDFText> strHTMLParagraphs = new List <WikiPDFText>(); foreach (KeyValuePair <Guid, string> t in wikiTitles) { if (!wikiParagraphs.ContainsKey(t.Key) || wikiParagraphs[t.Key].Count == 0) { continue; } bool hasTitle = !string.IsNullOrEmpty(t.Value); int counter = 0; if (hasTitle) { pdfTitles += "<p><a href='#" + t.Key.ToString() + "'>" + t.Value + "</a></p><br>"; pdfTitles += ProviderUtil.list_to_string <string>(wikiParagraphs[t.Key].Where( u => !string.IsNullOrEmpty(u.Key) && !string.IsNullOrEmpty(u.Value)).Select( p => "<p><a style='color:gray;' href='#" + t.Key.ToString() + (++counter).ToString() + "'>" + p.Key + "</a></p><br>").ToList <string>(), ' '); } wikiPDFTitles = new WikiPDFText(applicationId, pdfTitles); counter = 0; WikiPDFText mt = !hasTitle ? null : new WikiPDFText(applicationId, @"<br><a name='" + t.Key.ToString() + "'><strong style='color:#00a;'>" + t.Value + "</strong></a>"); List <KeyValuePair <string, string> > prgrs = wikiParagraphs[t.Key].Where( u => !string.IsNullOrEmpty(u.Value)).Select(x => x).ToList(); WikiPDFText tempParagraphs = new WikiPDFText(applicationId, ProviderUtil.list_to_string <string>(prgrs.Select(u => u.Value).ToList(), ' ')); if (mt != null && tempParagraphs.IsProbablyRTL) { mt.set_is_rtl(true); } if (mt != null) { strHTMLParagraphs.Add(mt); } foreach (KeyValuePair <string, string> kvp in prgrs) { WikiPDFText pp = new WikiPDFText(applicationId, kvp.Value); if (!string.IsNullOrEmpty(kvp.Key)) { WikiPDFText pt = new WikiPDFText(applicationId, "<p><a style='color:#444;' name='" + t.Key.ToString() + (++counter).ToString() + "'><strong>" + kvp.Key + "</strong></a></p>"); if (pp.IsProbablyRTL) { pt.set_is_rtl(true); } strHTMLParagraphs.Add(pt); } strHTMLParagraphs.Add(pp); } } strHTMLParagraphs = convert_div_to_p(applicationId, strHTMLParagraphs); using (MemoryStream mem = new MemoryStream()) { using (Document pdfDoc = new Document(PageSize.A4)) { BaseFont baseFont = BaseFont.CreateFont( PublicMethods.map_path("~/Fonts/windows/IRANSans.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(baseFont, size: 9); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, mem); PageEventHelper pageEvents = new PageEventHelper(applicationId, title, font, meta); pdfWriter.PageEvent = pageEvents; pdfWriter.RgbTransparencyBlending = true; pdfDoc.Open(); StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(); cssResolver.AddCssFile(PublicMethods.map_path("~/CSS/pdf.css"), true); PdfPTable mainTable = new PdfPTable(1) { WidthPercentage = 100, RunDirection = PdfWriter.RUN_DIRECTION_RTL }; mainTable.SplitLate = false; PdfPCell coverCell = new PdfPCell() { FixedHeight = 750, RunDirection = PdfWriter.RUN_DIRECTION_RTL, HorizontalAlignment = Element.ALIGN_CENTER }; PdfPCell titlesCell = new PdfPCell { Border = 0, RunDirection = PdfWriter.RUN_DIRECTION_RTL, HorizontalAlignment = Element.ALIGN_RIGHT, PaddingRight = 20f, PaddingLeft = 20f, BackgroundColor = BaseColor.LIGHT_GRAY }; for (int c = 0; c < wikiCover.Count; c++) { _add_to_table(applicationId, context, mainTable, cssResolver, wikiCover[c], font, coverCell); } //_add_to_table(applicationId, context, mainTable, cssResolver, wikiTitle, font); if (!string.IsNullOrEmpty(description)) { for (int c = 0; c < wikiDesc.Count; c++) { _add_to_table(applicationId, context, mainTable, cssResolver, wikiDesc[c], font); } } if (!string.IsNullOrEmpty(strKeywords)) { _add_to_table(applicationId, context, mainTable, cssResolver, wikiKeywords, font); } //_add_to_table(applicationId, context, mainTable, cssResolver, wikiPDFTitles, font, titlesCell); for (int c = 0; c < strHTMLParagraphs.Count; c++) { _add_to_table(applicationId, context, mainTable, cssResolver, strHTMLParagraphs[c], font); } pdfDoc.Add(mainTable); pdfDoc.Close(); byte[] finalContent = mem.ToArray(); if (hasCustomCover) { finalContent = add_custom_cover(applicationId, currentUserId.Value, finalContent, coverId.Value, coverOwnerNodeId.Value); } return(string.IsNullOrEmpty(password) ? finalContent : PDFUtil.set_password(finalContent, password)); } } }