public void manipulatePdf(string htmlSource, string pdfDest, string resourceLoc) { // Base URI is required to resolve the path to source files ConverterProperties converterProperties = new ConverterProperties().SetBaseUri(resourceLoc); using (var htmlStream = File.OpenRead(htmlSource)) { if (File.Exists(pdfDest)) { File.Delete(pdfDest); } using (var pdfStream = File.OpenWrite(pdfDest)) { IDictionary <string, int?> priorityMappings = new Dictionary <string, int?>(); priorityMappings.Add("p", 1); priorityMappings.Add("h1", 2); OutlineHandler customOutlineHandler = new CustomOutlineHandler().PutAllTagPriorityMappings(priorityMappings); customOutlineHandler.SetDestinationNamePrefix("custom-prefix-"); converterProperties.SetOutlineHandler(customOutlineHandler); HtmlConverter.ConvertToPdf(htmlStream, pdfStream, converterProperties); } } // Create custom outline handler }
/// <summary> /// Creates the PDF file. /// </summary> /// <param name="html">the HTML file as a byte array</param> /// <param name="baseUri">the base URI</param> /// <param name="dest">the path to the resulting PDF</param> public void CreatePdf(byte[] html, String baseUri, String dest) { ConverterProperties properties = new ConverterProperties(); properties.SetBaseUri(baseUri); OutlineHandler outlineHandler = OutlineHandler.CreateStandardHandler(); properties.SetOutlineHandler(outlineHandler); HtmlConverter.ConvertToPdf(new MemoryStream(html), new FileStream(dest, FileMode.Create), properties); }
/// <summary> /// Creates the PDF file. /// </summary> /// <param name="html">the HTML file as a byte array</param> /// <param name="baseUri">the base URI</param> /// <param name="dest">the path to the resulting PDF</param> public void CreatePdf(byte[] html, String baseUri, String dest) { ConverterProperties properties = new ConverterProperties(); properties.SetBaseUri(baseUri); OutlineHandler outlineHandler = new OutlineHandler(); outlineHandler.PutTagPriorityMapping("h1", 1); outlineHandler.PutTagPriorityMapping("p", 2); properties.SetOutlineHandler(outlineHandler); HtmlConverter.ConvertToPdf(new MemoryStream(html), new FileStream(dest, FileMode.Create), properties); }
public static byte[] ConvertToPdf(byte[] html) { byte[] pdf = null; using (var ms = new MemoryStream()) { ConverterProperties properties = new ConverterProperties(); // properties.SetBaseUri(""); properties.SetOutlineHandler(OutlineHandler.CreateStandardHandler()); PdfDocument pdfDocument = new PdfDocument(new PdfWriter(ms)); PageSize pageSize = PageSize.Default; string metaPageSize = HtmlHelper.ObtenerMetaContent(html, RiskConstants.META_PAGE_SIZE); switch (metaPageSize.ToUpper()) { case "A3": pageSize = PageSize.A3; break; case "A4": pageSize = PageSize.A4; break; case "A5": pageSize = PageSize.A5; break; case "A6": pageSize = PageSize.A6; break; case "LEGAL": pageSize = PageSize.LEGAL; break; case "LETTER": pageSize = PageSize.LETTER; break; case "EXECUTIVE": pageSize = PageSize.EXECUTIVE; break; default: pageSize = PageSize.Default; break; } string metaPageOrientation = HtmlHelper.ObtenerMetaContent(html, RiskConstants.META_PAGE_ORIENTATION); if (metaPageOrientation.Equals(RiskConstants.ORIENTACION_HORIZONTAL, StringComparison.OrdinalIgnoreCase)) { pageSize = pageSize.Rotate(); } pdfDocument.SetDefaultPageSize(pageSize); Document document = HtmlConverter.ConvertToDocument(new MemoryStream(html), pdfDocument, properties); document.Close(); pdf = ms.ToArray(); } return(pdf); }
public IActionResult Create(string pdfHtmlString, string saveName = null) { #region Parameters // Global Config string fontFamily = Configuration["PdfConfig:GlobalConfig:FontFamily"]; // Path Config string descPath = Configuration["PdfConfig:PathConfig:DescPath"]; string logPath = Configuration["PdfConfig:PathConfig:LogPath"]; // MetaData Config string title = Configuration["PdfConfig:MetaData:Title"]; string author = Configuration["PdfConfig:MetaData:Author"]; string creator = Configuration["PdfConfig:MetaData:Creator"]; string keywords = Configuration["PdfConfig:MetaData:Keywords"]; string subject = Configuration["PdfConfig:MetaData:Subject"]; // Header Config string headerText = Configuration["PdfConfig:Header:Text"]; float headerFontSize = Convert.ToSingle(Configuration["PdfConfig:Header:FontSize"]); string headerFontColor = Configuration["PdfConfig:Header:FontColor"]; string headerImageSource = Configuration["PdfConfig:Header:Image:Source"]; float headerImageWidth = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Width"]); float headerImagePositionX = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Position:Left"]); float headerImagePositionY = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Position:Top"]); // Footer Config string footerText = Configuration["PdfConfig:Footer:Text"]; double footerFontSize = Convert.ToDouble(Configuration["PdfConfig:Footer:FontSize"]); string footerFontColor = Configuration["PdfConfig:Footer:FontColor"]; string footerImageSource = Configuration["PdfConfig:Footer:Image:Source"]; float footerImageWidth = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Width"]); float footerImagePositionX = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Position:Left"]); float footerImagePositionY = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Position:Top"]); #endregion #region Properties & Setting // Configure properties for converter | 配置转换器 ConverterProperties properties = new ConverterProperties(); // Resources path, store images/fonts for example | 资源路径, 存放如图片/字体等资源 string resources = Host.WebRootPath + (osInfo.Platform == PlatformID.Unix ? "/src/font/" : "\\src\\font\\"); // PDF saved path | 生成的PDF文件存放路径 string desc = string.Empty; if (osInfo.Platform == PlatformID.Unix) { if (!Directory.Exists(descPath)) { Directory.CreateDirectory(descPath); } desc = descPath + (saveName ?? DateTime.Now.ToString("yyyyMMdd-hhmmss-ffff")) + ".pdf"; } else { descPath = "D:\\Pdf\\"; if (!Directory.Exists(descPath)) { Directory.CreateDirectory(descPath); } desc = descPath + (saveName ?? DateTime.Now.ToString("yyyyMMdd-hhmmss-ffff")) + ".pdf"; } FontProvider fp = new FontProvider(); // Add Standard fonts libs without chinese support | 添加标准字体库 // fp.AddStandardPdfFonts(); fp.AddDirectory(resources); properties.SetFontProvider(fp); // Set base uri to resource folder | 设置基础uri properties.SetBaseUri(resources); PdfWriter writer = new PdfWriter(desc); PdfDocument pdfDoc = new PdfDocument(writer); // Set PageSize | 设置页面大小 pdfDoc.SetDefaultPageSize(PageSize.A4); // Set Encoding | 设置文本编码方式 pdfDoc.GetCatalog().SetLang(new PdfString("UTF-8")); //Set the document to be tagged | 展示文档标签树 pdfDoc.SetTagged(); pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true)); //https://developers.itextpdf.com/content/itext-7-examples/converting-html-pdf/pdfhtml-header-and-footer-example // create pdf font using custom resources | 自定义字体 PdfFont sourcehansanscn = PdfFontFactory.CreateFont(resources + fontFamily, PdfEncodings.IDENTITY_H); Dictionary <string, object> header = new Dictionary <string, object>() { { "text", headerText }, { "fontSize", headerFontSize }, { "fontColor", headerFontColor }, { "source", Host.WebRootPath + headerImageSource }, { "width", headerImageWidth }, { "left", headerImagePositionX }, { "top", headerImagePositionY } }; Dictionary <string, object> footer = new Dictionary <string, object>() { { "text", footerText }, { "fontSize", footerFontSize }, { "fontColor", footerFontColor }, { "source", Host.WebRootPath + footerImageSource }, { "width", footerImageWidth }, { "left", footerImagePositionX }, { "top", footerImagePositionY } }; // Header handler | 页头处理 PdfHeader headerHandler = new PdfHeader(header, sourcehansanscn); // Footer handler | 页脚处理 PdfFooter footerHandler = new PdfFooter(footer, sourcehansanscn); // Assign event-handlers pdfDoc.AddEventHandler(PdfDocumentEvent.START_PAGE, headerHandler); pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, footerHandler); // Setup custom tagworker factory for better tagging of headers | 设置标签处理器 DefaultTagWorkerFactory tagWorkerFactory = new DefaultTagWorkerFactory(); properties.SetTagWorkerFactory(tagWorkerFactory); // Setup default outline(bookmark) handler | 设置默认大纲(书签)处理器 // We used the createStandardHandler() method to create a standard handler. // This means that pdfHTML will look for <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>. // The bookmarks will be created based on the hierarchy of those tags in the HTML file. // To enable other tags, read the folllowing article for more details. // https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-4-creating-reports-using-pdfhtml OutlineHandler outlineHandler = OutlineHandler.CreateStandardHandler(); properties.SetOutlineHandler(outlineHandler); // Bookmark | 书签 // https://developers.itextpdf.com/content/itext-7-examples/itext-7-bookmarks-tocs/toc-first-page // https://developers.itextpdf.com/content/best-itext-questions-stackoverview/actions-and-annotations/itext7-how-create-hierarchical-bookmarks // https://developers.itextpdf.com/content/itext-7-building-blocks/chapter-6-creating-actions-destinations-and-bookmarks // https://developers.itextpdf.com/examples/actions-and-annotations/clone-named-destinations // PdfOutline outline = null; // outline = CreateOutline(outline, pdfDoc, "bookmark", "bookmark"); // Meta tags | 文档属性标签 PdfDocumentInfo pdfMetaData = pdfDoc.GetDocumentInfo(); pdfMetaData.SetTitle(title); pdfMetaData.SetAuthor(author); pdfMetaData.AddCreationDate(); pdfMetaData.GetProducer(); pdfMetaData.SetCreator(creator); pdfMetaData.SetKeywords(keywords); pdfMetaData.SetSubject(subject); #endregion // Start convertion | 开始转化 //Document document = // HtmlConverter.ConvertToDocument(pdfHtmlString, pdfDoc, properties); IList <IElement> elements = HtmlConverter.ConvertToElements(pdfHtmlString, properties); Document document = new Document(pdfDoc); CJKSplitCharacters splitCharacters = new CJKSplitCharacters(); document.SetFontProvider(fp); document.SetSplitCharacters(splitCharacters); document.SetProperty(Property.SPLIT_CHARACTERS, splitCharacters); foreach (IElement e in elements) { try { document.Add((AreaBreak)e); } catch { document.Add((IBlockElement)e); } } // Close and release document | 关闭并释放文档资源 document.Close(); return(Content("SUCCESS")); }