/// <summary> /// Merge pdf files. /// </summary> /// <param name="sourceFiles">PDF files being merged.</param> /// <returns></returns> public static byte[] MergeFiles(string htmlDocument, IList <byte[]> sourceFiles, string pdfConverterLicenseKey) { PdfConverter pdfConverter = new PdfConverter { PdfStandardSubset = PdfStandardSubset.Pdf_A_1b }; if (String.IsNullOrEmpty(pdfConverterLicenseKey) == false) { pdfConverter.LicenseKey = pdfConverterLicenseKey; } Winnovative.WnvHtmlConvert.PdfDocument.Document doc = pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlDocument); try { if (sourceFiles != null) { foreach (var file in sourceFiles) { using (var fileStream = new MemoryStream(file)) { doc.AppendDocument(new Winnovative.WnvHtmlConvert.PdfDocument.Document(fileStream)); } } } return(doc.Save()); } finally { doc.Close(); } }
public byte[] pdf(System.Text.StringBuilder head) { PdfConverter pdfConverter = new PdfConverter(); Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromHtmlString(head.ToString()); MemoryStream pdfStream = new MemoryStream(); return(pdfDocument.Save()); }
private Document CrearDocumentoPDF(PdfConverter pdfConverter, string htmlOutput) { //realizo una primera conversion del html. byte[] byteArray = pdfConverter.GetPdfBytesFromHtmlString(htmlOutput); pdfConverter.PostConvertActionEvent += new PostConvertActionHandler(this.pdfConverter_PostConvertActionEvent2); Document result = pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlOutput); pdfConverter.PostConvertActionEvent -= this.pdfConverter_PostConvertActionEvent2; return(result); }
public static Document GenerarHtmlaDocumento(string Url, PdfPageSize Tamaño) { PdfConverter pdfConvertidor = new PdfConverter(); PDFPageOrientation pdfPageOrientation; pdfConvertidor.LicenseKey = "UXpjcWBkcWlmcWd/YXFiYH9gY39oaGho"; pdfPageOrientation = PDFPageOrientation.Portrait; pdfConvertidor.PdfDocumentOptions.PdfPageSize = Tamaño; pdfConvertidor.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; pdfConvertidor.PdfDocumentOptions.PdfPageOrientation = pdfPageOrientation; string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; string baseUrl = thisPageURL; return(pdfConvertidor.GetPdfDocumentObjectFromHtmlString(Url, baseUrl)); }
public byte[] ProcesarTemplate(List <string> listHtmlOutput) { PdfConverter pdfConverter = this.CreatePdfConverter(); List <Document> listDocuments = new List <Document>(); foreach (string html in listHtmlOutput) { //Document _docPdf = CrearDocumentoPDF(pdfConverter, html, string.Empty); Document _docPdf = pdfConverter.GetPdfDocumentObjectFromHtmlString(html); PrivateFontCollection pfc = new PrivateFontCollection(); pfc.AddFontFile(string.Format("{0}\\Verdana.ttf", PathFuente)); _docPdf.AddFont(new Font(pfc.Families[0], 12.0f), true); listDocuments.Add(_docPdf); } int indice = 0; Document mergedDocument = listDocuments[indice]; mergedDocument.AutoCloseAppendedDocs = true; foreach (Document _docItem in listDocuments) { if (indice > 0) { mergedDocument.AppendDocument(_docItem); } indice++; } mergedDocument.RemovePage(0); mergedDocument.RemovePage(0); byte[] bytPdfMerged = null; try { bytPdfMerged = mergedDocument.Save(); } finally { mergedDocument.Close(); } return(bytPdfMerged); }
public byte[] ProcesarTemplate(string htmlOutput) { PdfConverter pdfConverter = this.CreatePdfConverter(); //Document _docPdf = CrearDocumentoPDF(pdfConverter, htmlOutput); Document _docPdf = pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlOutput); //byte[] bytePDF = pdfConverter.GetPdfBytesFromHtmlString(htmlOutput); byte[] bytePDF; try { bytePDF = _docPdf.Save(); } finally { _docPdf.Close(); } return(bytePDF); }
protected void btnToPdf_Click(object sender, EventArgs e) { var pdfConverter = new PdfConverter(); pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Landscape; pdfConverter.HtmlViewerWidth = 1280; pdfConverter.LicenseKey = "MxgBEwAAEwcEARMBHQMTAAIdAgEdCgoKCg=="; string sHtml = ""; if (Request.Url.ToString().IndexOf("?") > 0) { sHtml = getHtml(Request.Url + "&pdf=true&cid=" + customerId); } else { sHtml = getHtml(Request.Url + "?pdf=true&cid=" + customerId); } Document mergedDoc = pdfConverter.GetPdfDocumentObjectFromHtmlString(sHtml); byte[] pdfBytes = null; try { pdfBytes = mergedDoc.Save(); } finally { mergedDoc.Close(); } if (pdfBytes != null) { //Save document in documents. Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", string.Format("attachment; filename=Itemrapport_{0:ddMMyyyy}.pdf", DateTime.Now)); Response.BinaryWrite(pdfBytes); Response.End(); } }
private Document CrearDocumentoPDF(PdfConverter pdfConverter, string htmlOutput, string textFooterOpt) { //Creo el evento, PostConvert, para detectar la cantidad de paginas, luego de agregar Footer y Header. pdfConverter.PostConvertActionEvent += new PostConvertActionHandler(this.pdfConverter_PostConvertActionEvent); HtmlTag tag; HtmlParser parse = new HtmlParser(htmlOutput); if (pdfConverter.PdfDocumentOptions.ShowFooter) { if (!TextoPieDePagina) { this.AddFooter(pdfConverter); } else { while (parse.ParseNext("iframe", out tag)) { // See if this anchor links to us string visibleOnFooterValue; bool _visibleOnFooterValue = false; if (!string.IsNullOrEmpty(tag.Content)) { //htmlOutput = htmlOutput.Remove(tag.PostStart, tag.PostEnd); if (tag.Attributes.TryGetValue("visibleOnFooter", out visibleOnFooterValue)) { if (bool.TryParse(visibleOnFooterValue, out _visibleOnFooterValue)) { if (_visibleOnFooterValue) { this.AddFooter(pdfConverter, tag.Content); break; } } } } } } } parse = new HtmlParser(htmlOutput); while (parse.ParseNext("iframe", out tag)) { // See if this anchor links to us string visibleOnHeaderValue; bool _visibleOnHeaderValue = false; if (!string.IsNullOrEmpty(tag.Content)) { htmlOutput = htmlOutput.Remove(tag.PostStart, tag.PostEnd); if (tag.Attributes.TryGetValue("visibleOnHeader", out visibleOnHeaderValue)) { if (bool.TryParse(visibleOnHeaderValue, out _visibleOnHeaderValue)) { if (_visibleOnHeaderValue) { AddHeader(pdfConverter, tag.Content); break; } } } } } //realizo una primera conversion del html. //byte[] byteArray = pdfConverter.GetPdfBytesFromHtmlString(htmlOutput); Document result1 = pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlOutput); //elimino el evento PostConvert, ya que no necesito realizar otra consulta en el PDF. pdfConverter.PostConvertActionEvent -= this.pdfConverter_PostConvertActionEvent; //En caso de que la primera conversion, retorne nro impart de paginas, me veo obligado a agregar una pagina mas en blanco. int _cantidad = 0; PaginaVaciaAgregada = false; if (int.TryParse(CantidadPaginas, out _cantidad)) { if (_cantidad % 2 != 0) { //cantidad impar. //agregamos un salto de pagina, para imprimir el otro cuerpo en hoja aparte. htmlOutput += "<div style=\"page-break-before: always\"> </div>"; //Imprimo en la hoja, la numeracion, par. _cantidad += 1; PaginaVaciaAgregada = true; } } // reemplazo el tag de cantidad de paginas, con la variable inicializada en el evento postConvert. htmlOutput = htmlOutput.Replace("[{cantidadhojas}]", _cantidad.ToString()); //realizo la conversion definitiva. pdfConverter.PostConvertActionEvent += new PostConvertActionHandler(this.pdfConverter_PostConvertActionEvent2); Document result = pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlOutput); pdfConverter.PostConvertActionEvent -= this.pdfConverter_PostConvertActionEvent2; return(result); }
public Document ProcesarDocumentoPDF(List <string> listHtmlOutput) { PdfConverter pdfConverter = this.CreatePdfConverter(); List <Document> listDocuments = new List <Document>(); foreach (string html in listHtmlOutput) { //esta es la version que imprime con la fuente distorsionada //Document _docPdf = CrearDocumentoPDF(pdfConverter, html, string.Empty); string htmlOutput = html; HtmlTag tag; HtmlParser parse = new HtmlParser(htmlOutput); if (pdfConverter.PdfDocumentOptions.ShowFooter) { if (!TextoPieDePagina) { this.AddFooter(pdfConverter); } else { while (parse.ParseNext("iframe", out tag)) { // See if this anchor links to us string visibleOnFooterValue; bool _visibleOnFooterValue = false; if (!string.IsNullOrEmpty(tag.Content)) { //htmlOutput = htmlOutput.Remove(tag.PostStart, tag.PostEnd); if (tag.Attributes.TryGetValue("visibleOnFooter", out visibleOnFooterValue)) { if (bool.TryParse(visibleOnFooterValue, out _visibleOnFooterValue)) { if (_visibleOnFooterValue) { this.AddFooter(pdfConverter, tag.Content); break; } } } } } } } parse = new HtmlParser(htmlOutput); while (parse.ParseNext("iframe", out tag)) { // See if this anchor links to us string visibleOnHeaderValue; bool _visibleOnHeaderValue = false; if (!string.IsNullOrEmpty(tag.Content)) { htmlOutput = htmlOutput.Remove(tag.PostStart, tag.PostEnd); if (tag.Attributes.TryGetValue("visibleOnHeader", out visibleOnHeaderValue)) { if (bool.TryParse(visibleOnHeaderValue, out _visibleOnHeaderValue)) { if (_visibleOnHeaderValue) { AddHeader(pdfConverter, tag.Content); break; } } } } } //PrivateFontCollection pfc = new PrivateFontCollection(); //pfc.AddFontFile(string.Format("{0}\\Verdana.ttf", PathFuente)); Document _docPdf = pdfConverter.GetPdfDocumentObjectFromHtmlString(html); //_docPdf.AddFont(new Font(pfc.Families[0], 12.0f), true); listDocuments.Add(_docPdf); } int indice = 0; Document mergedDocument = listDocuments[indice]; mergedDocument.AutoCloseAppendedDocs = true; foreach (Document _docItem in listDocuments) { if (indice > 0) { mergedDocument.AppendDocument(_docItem); } indice++; } return(mergedDocument); }
private Document CreateExecutiveSummaryPdf(string executiveSummaryHTML, string headerText, string contentPath, SummaryReportHeaderType reportHeaderType) { var pdfConvertorExecutiveSummary = new PdfConverter(); pdfConvertorExecutiveSummary.PrepareRenderPdfPageEvent += pdfConvertorExecutiveSummary_PrepareRenderPdfPageEvent; pdfConvertorExecutiveSummary.LicenseKey = LICENSE_KEY; pdfConvertorExecutiveSummary.PdfDocumentOptions.EmbedFonts = true; pdfConvertorExecutiveSummary.PdfDocumentOptions.LeftMargin = 56; pdfConvertorExecutiveSummary.PdfDocumentOptions.RightMargin = 30; pdfConvertorExecutiveSummary.PdfDocumentOptions.TopMargin = 10; pdfConvertorExecutiveSummary.PdfDocumentOptions.BottomMargin = 0; pdfConvertorExecutiveSummary.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConvertorExecutiveSummary.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.NoCompression; pdfConvertorExecutiveSummary.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait; AddSummaryFooter(pdfConvertorExecutiveSummary, contentPath, reportHeaderType); if (string.IsNullOrEmpty(executiveSummaryHTML)) { executiveSummaryHTML = "<html><body></body></html>"; } var executiveSummaryPdf = pdfConvertorExecutiveSummary.GetPdfDocumentObjectFromHtmlString(executiveSummaryHTML); pdfConvertorExecutiveSummary.PrepareRenderPdfPageEvent -= pdfConvertorExecutiveSummary_PrepareRenderPdfPageEvent; return executiveSummaryPdf; }
private Document CreateActionPlanPdf(string actionPlanHtml, string headerText, string clientLogoFilename) { var pdfConverterActionPlan = new PdfConverter(); pdfConverterActionPlan.LicenseKey = LICENSE_KEY;// "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; pdfConverterActionPlan.PdfDocumentOptions.EmbedFonts = true; pdfConverterActionPlan.PdfDocumentOptions.LeftMargin = 20; pdfConverterActionPlan.PdfDocumentOptions.RightMargin = 20; pdfConverterActionPlan.PdfDocumentOptions.TopMargin = 10; pdfConverterActionPlan.PdfDocumentOptions.BottomMargin = 0; pdfConverterActionPlan.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverterActionPlan.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.NoCompression; pdfConverterActionPlan.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Landscape; AddHeader(pdfConverterActionPlan, headerText, clientLogoFilename); AddReportFooter(pdfConverterActionPlan); var actionPlanPdf = pdfConverterActionPlan.GetPdfDocumentObjectFromHtmlString(actionPlanHtml); actionPlanPdf.Pages.Remove(actionPlanPdf.Pages.Count - 1); return actionPlanPdf; }
/// <summary> /// Maak PDF van html invoer /// </summary> /// <param name="htmlTabel">HTML invoer</param> /// <param name="LijstHeader">Lijstgegevens (Naam, subcode etc)</param> /// <param name="HtmlFooter">Aangepaste Footer in HTML code</param> /// <param name="Landscape">Landscape (default = false)</param> /// <param name="Headernr">Header nummer (default = 1)</param> public void MakePdf(string htmlTabel, HeaderFooter LijstHeader, string LijstFooter, bool Landscape, int Headernr) { PdfConverter pdfConverter = new PdfConverter(); pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE="; pdfConverter.LicenseKey = "EpyMnY6OnYyPjJ2Jk42djoyTjI+ThISEhA=="; if (Landscape) { pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Landscape; } // HTML Totaalplaatje genereren string fullHtml = string.Empty; switch (Headernr) { case 0: // No Header fullHtml = htmlContainerNoInfoBlock; break; default: fullHtml = htmlContainer; //fullHtml = fullHtml.Replace("logo.png", pathlogo); fullHtml = fullHtml.Replace("{lijst}", LijstHeader.LijstNaam); fullHtml = fullHtml.Replace("{bestandscode}", LijstHeader.LijstCode); //"Bezetting: per project per week"); fullHtml = fullHtml.Replace("{periode}", LijstHeader.UI_Startdatum.ToLongDateString() + " - " + LijstHeader.UI_Einddatum.ToLongDateString()); for (int c = 0; c <= 5; c++) { fullHtml = fullHtml.Replace( "{l" + c.ToString() + "}", (c < LijstHeader.UISettings.Count ? LijstHeader.UISettings[c][0] : "")); fullHtml = fullHtml.Replace( "{r" + c.ToString() + "}", (c < LijstHeader.UISettings.Count ? LijstHeader.UISettings[c][1] : "")); } break; } fullHtml = fullHtml.Replace("/*stylesheet*/", htmlStyleSheet); fullHtml = fullHtml.Replace("{tabellen}", htmlTabel); // Header en footer toevoegen AddHeaderElements(pdfConverter, LijstFooter); // HTML: PDF creeren string outFilePath = System.IO.Path.Combine(xHtmlFolder, LijstHeader.LijstCode + ".pdf"); // PDF maken //pdfConverter.SavePdfFromHtmlStringToFile(fullHtml, outFilePath);// xHtmlFolder); // TEST JURACI Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromHtmlString(fullHtml); AlternatieveHeader(pdfDocument, pdfConverter, LijstHeader.LijstCode);// + " " + LijstHeader.LijstNaam); pdfDocument.Save(outFilePath); System.Diagnostics.Process.Start(outFilePath); // Oude files opruimen string dirName = System.IO.Path.GetDirectoryName(outFilePath); try { Directory.GetFiles(dirName) .Select(f => new FileInfo(f)) .Where(f => f.LastAccessTime < DateTime.Now.AddDays(-31) && f.Name.Length == 21 && f.Name.Substring(0, 1) == "d" && f.Name.Substring(7, 1) == "t" && f.Name.Substring(14, 1) == "r" && f.Name.Substring(17) == ".pdf" && f.Name.Substring(f.Name.Length - 4) == ".pdf" ) .ToList() .ForEach(f => f.Delete()); } catch { } }
/// <summary> /// Converts the specified html documents to a single pdf file. /// </summary> /// <param name="htmlDocuments"></param> /// <param name="pdfAttachments"></param> /// <param name="pdfConverterLicenseKey"></param> /// <returns></returns> public static byte[] ConvertHtmlToPdf(IEnumerable <string> htmlDocuments, ICollection <PdfAttachment> pdfAttachments, string pdfConverterLicenseKey) { //TODO: Add the ability to customize layout and margins. PdfConverter pdfConverter = new PdfConverter { PdfStandardSubset = PdfStandardSubset.Pdf_A_1b }; if (String.IsNullOrEmpty(pdfConverterLicenseKey) == false) { pdfConverter.LicenseKey = pdfConverterLicenseKey; } Winnovative.WnvHtmlConvert.PdfDocument.Document doc = null; try { if (htmlDocuments != null) { foreach (var htmlDocument in htmlDocuments) { if (doc == null) { doc = pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlDocument); } else { doc.AppendDocument(pdfConverter.GetPdfDocumentObjectFromHtmlString(htmlDocument)); } } } if (doc == null) { throw new InvalidOperationException("No PDF Document Object was created."); } //Use iTextSharp to add all attachments if (pdfAttachments != null && pdfAttachments.Any()) { var reader = new PdfReader(doc.Save()); using (var outputPdfStream = new MemoryStream()) { var stamper = new PdfStamper(reader, outputPdfStream); foreach (var pdfAttachment in pdfAttachments) { stamper.AddFileAttachment(pdfAttachment.Description, pdfAttachment.Data, pdfAttachment.FileName, pdfAttachment.FileDisplayName); } stamper.Close(); outputPdfStream.Flush(); return(outputPdfStream.GetBuffer()); } } else { return(doc.Save()); } } finally { if (doc != null) { doc.Close(); } } }
/// <summary> /// Function Creates PDF from HTML WITH TOC and Header-Footer /// </summary> /// <param name="PDFPath"></param> private void CreatePDF(string PDFPath) { #region Private Variables PdfConverter pdfConverter = new PdfConverter(); int mappingsTableIdx = 0; Document document = new Document(); //New document to be used for adding blank pages Document mergedDocument = new Document(); //New Document to merge Header and Pdfdocument string coverImg = string.Empty; float tocEntryMaxRight = 0.0f; int cntAddIndxForPage = 0; List<string> lstHeader = new List<string>(); int pageNum = 0; string strHeader = string.Empty; List<int> lstBlankPage = new List<int>(); #endregion // show the bookmarks when the document is opened pdfConverter.PdfViewerPreferences.PageMode = ViewerPageMode.UseNone; // set page margins pdfConverter.PdfDocumentOptions.TopMargin = 20; pdfConverter.PdfDocumentOptions.BottomMargin = 20; pdfConverter.PdfDocumentOptions.LeftMargin = 20; pdfConverter.PdfDocumentOptions.RightMargin = 20; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter11x17; pdfConverter.PdfDocumentOptions.FitWidth = false; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait; pdfConverter.AvoidImageBreak = true; pdfConverter.AvoidTextBreak = true; // Inform the converter about the HTML elements for which we want the location in PDF // The HTML ID of each entry in the table of contents is of form TOCEntry_{EntryIndex}_ID // the HTML ID of each target of a table of contents entry is of form TOCEntry_{EntryIndex}_Target_ID // Both toc entries and toc entries targets locations in PDF will be retrieved // and therefore the number of IDs is twice TOC entries number pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[2 * countTOC]; for (int tocEntryIndex = 1; tocEntryIndex <= countTOC; tocEntryIndex++) { // add the HTML ID of the TOC entry element to the list of elements for which we want the PDF location string tocEntryID = String.Format(PDFConstants.Instance.TOCENTRYID, tocEntryIndex); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryID; // add the HTML ID of the TOC entry target element to the list of elements for which we want the PDF location string tocEntryTargetID = String.Format(PDFConstants.Instance.TOCTARGETID , tocEntryIndex); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryTargetID; } // set bookmark options pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { PDFConstants.Instance.HTMLBookmarkTag }; // the URL of the HTML document to convert string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; string htmlBookFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/data"), "temp.html"); // show header in rendered PDF pdfConverter.PdfDocumentOptions.ShowHeader = true; //Add pages to header Document coverImg = Path.Combine(HttpContext.Current.Server.MapPath("~/Images"), "Cover.jpg"); Document header = pdfConverter.GetPdfDocumentObjectFromHtmlString(string.Format(PDFConstants.Instance.HTMLCoverImageTag,coverImg ) + PDFConstants.Instance. HTMLMETAContentTag); // call the converter and get a Document object from URL Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(htmlBookFilePath); pdfDocument.ViewerPreferences.CenterWindow = true; // Create a font used to write the page numbers in the table of contents PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font("Times New Roman", PAGE_NUMBER_FONT_SIZE, FontStyle.Regular, GraphicsUnit.Point), true); #region Generate TOC & Add to PDF // get the right edge of the table of contents where to position the page numbers for (int tocEntryIdx = 1; tocEntryIdx <= countTOC; tocEntryIdx++) { string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); if (tocEntryLocation != null) { if (tocEntryLocation.PdfRectangles[0].Rectangle.Right > tocEntryMaxRight) tocEntryMaxRight = tocEntryLocation.PdfRectangles[0].Rectangle.Right; } } // Add page number for each entry in the table of contents for (int tocEntryIdx = 1; tocEntryIdx <= countTOC; tocEntryIdx++) { string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx); string tocEntryTargetID = String.Format("TOCEntry_{0}_Target_ID", tocEntryIdx); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); HtmlElementMapping tocEntryTargetLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryTargetID); // get the TOC entry page and bounds PdfPage tocEntryPdfPage = pdfDocument.Pages[tocEntryLocation.PdfRectangles[0].PageIndex]; RectangleF tocEntryPdfRectangle = tocEntryLocation.PdfRectangles[0].Rectangle; if (tocEntryLocation.HtmlElementCssClassName.Equals("h1")) { while (pageNum < tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1 + cntAddIndxForPage) { pageNum++; lstHeader.Add(strHeader); } if ((tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1 + cntAddIndxForPage) % 2 == 0) { pdfDocument.Pages.Insert(tocEntryTargetLocation.PdfRectangles[0].PageIndex + cntAddIndxForPage, document.AddPage(PageSize.Letter11x17, Margins.Empty)); lstBlankPage.Add(tocEntryTargetLocation.PdfRectangles[0].PageIndex + cntAddIndxForPage + 1); cntAddIndxForPage++; } strHeader = tocEntryLocation.HtmlElementText; } // get the page number of target where the TOC entry points int tocEntryTargetPageNumber = tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1 + cntAddIndxForPage; // add dashed line from text entry to the page number LineElement lineToNumber = new LineElement(tocEntryPdfRectangle.Right + 5, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F, tocEntryMaxRight + 200, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F); lineToNumber.LineStyle.LineWidth = 1; lineToNumber.LineStyle.LineDashStyle = LineDashStyle.Dot; lineToNumber.ForeColor = Color.Black; tocEntryPdfPage.AddElement(lineToNumber); // create the page number text element to the right of the TOC entry TextElement pageNumberTextEement = new TextElement(tocEntryMaxRight + 205, tocEntryPdfRectangle.Y, -1, tocEntryPdfRectangle.Height, tocEntryTargetPageNumber.ToString(), pageNumberFont); pageNumberTextEement.TextAlign = HorizontalTextAlign.Left; pageNumberTextEement.VerticalTextAlign = VerticalTextAlign.Middle; pageNumberTextEement.ForeColor = Color.Black; // add the page number to the right of the TOC entry tocEntryPdfPage.AddElement(pageNumberTextEement); } #endregion #region Create index at End of the Document int TOC_INDEX_COUNT = NewIndexList.Count; pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[2 * TOC_INDEX_COUNT]; int mappingsEntryTableIdx = 0; for (int tocEntryIndex = 1; tocEntryIndex <= TOC_INDEX_COUNT; tocEntryIndex++) { // add the HTML ID of the TOC entry element to the list of elements for which we want the PDF location string tocEntryID = String.Format("#TOCIndex_{0}_ID", NewIndexList[tocEntryIndex - 1].ToString()); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsEntryTableIdx++] = tocEntryID; string tocEntryTargetID = String.Format("#TOCIndex_{0}_Target_ID", NewIndexList[tocEntryIndex - 1].ToString()); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsEntryTableIdx++] = tocEntryTargetID; } // call the converter and get a Document object from URL Document pdfDocumentI = pdfConverter.GetPdfDocumentObjectFromUrl(htmlBookFilePath); // Create a font used to write the page numbers in the table of contents PdfFont pageNumberFontI = pdfDocument.Fonts.Add(new Font("Arial", PAGE_NUMBER_FONT_SIZE, FontStyle.Bold, GraphicsUnit.Point), true); // get the right edge of the Index where to position the page numbers float tocEntryMaxRightI = 0.0f; for (int tocEntryIdx = 1; tocEntryIdx <= TOC_INDEX_COUNT; tocEntryIdx++) { string tocEntryID = String.Format("TOCIndex_{0}_ID", tocEntryIdx); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); if (tocEntryLocation != null) { if (tocEntryLocation.PdfRectangles[0].Rectangle.Right > tocEntryMaxRightI) tocEntryMaxRightI = tocEntryLocation.PdfRectangles[0].Rectangle.Right; } } // Add page number for each entry in the Index for (int tocEntryIdx = 1; tocEntryIdx <= TOC_INDEX_COUNT; tocEntryIdx++) { string tocEntryID = String.Format("TOCIndex_{0}_ID", NewIndexList[tocEntryIdx - 1].ToString()); string tocEntryTargetID = String.Format("TOCIndex_{0}_Target_ID", NewIndexList[tocEntryIdx - 1].ToString()); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); HtmlElementMapping tocEntryTargetLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryTargetID); // get the TOC entry page and bounds PdfPage tocEntryPdfPage = pdfDocument.Pages[tocEntryLocation.PdfRectangles[0].PageIndex + cntAddIndxForPage]; RectangleF tocEntryPdfRectangle = tocEntryLocation.PdfRectangles[0].Rectangle; // get the page number of target where the TOC entry points int tocEntryTargetPageNumber = tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1; for (int i = 0; i < lstBlankPage.Count; i++) { if (lstBlankPage[i] <= tocEntryTargetPageNumber) { tocEntryTargetPageNumber++; } } // add dashed line from text entry to the page number LineElement lineToNumber = new LineElement(tocEntryPdfRectangle.Right + 5, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F, tocEntryMaxRight, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F); lineToNumber.LineStyle.LineWidth = 1; lineToNumber.LineStyle.LineDashStyle = LineDashStyle.Dot; lineToNumber.ForeColor = Color.Black; tocEntryPdfPage.AddElement(lineToNumber); // create the page number text element to the right of the TOC entry TextElement pageNumberTextEement = new TextElement(tocEntryMaxRight + 5, tocEntryPdfRectangle.Y, -1, tocEntryPdfRectangle.Height, tocEntryTargetPageNumber.ToString(), pageNumberFont); pageNumberTextEement.TextAlign = HorizontalTextAlign.Left; pageNumberTextEement.VerticalTextAlign = VerticalTextAlign.Middle; pageNumberTextEement.ForeColor = Color.Black; // add the page number to the right of the TOC entry tocEntryPdfPage.AddElement(pageNumberTextEement); } #endregion #region Set Header On Each Pages // the width is given by the PDF page width float altHeaderFooterWidth = pdfDocument.Pages[0].ClientRectangle.Width; float altHeaderHeight = pdfConverter.PdfHeaderOptions.HeaderHeight; //Add Header Chapter for last chapter in Header list for (int pages = lstHeader.Count; pages < pdfDocument.Pages.Count; pages++) { lstHeader.Add(strHeader); } //Remove Unnecessary Header Line from Header Document for (int pageIndex = 0; pageIndex < header.Pages.Count; pageIndex++) { Template tmpHeaderTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altHeaderHeight); PdfPage pdfPage = header.Pages[pageIndex]; pdfPage.CustomHeaderTemplate = tmpHeaderTemplate; pdfPage.ShowHeaderTemplate = true; } //Iterate through pages and add header details on each page.. i.e. Chapter Name, Page Number for (int pageIndex = 0; pageIndex < pdfDocument.Pages.Count; pageIndex++) { // create the alternate header template Template altHeaderTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altHeaderHeight); TextElement txtHeader = new TextElement(10, altHeaderHeight, lstHeader[pageIndex].ToString(), pageNumberFont, Color.Black); altHeaderTemplate.AddElement(txtHeader); TextElement txtPageNumber = new TextElement(altHeaderFooterWidth - 50, altHeaderHeight, (pageIndex + 1).ToString(), pageNumberFont, Color.Black); altHeaderTemplate.AddElement(txtPageNumber); PdfPage pdfPage = pdfDocument.Pages[pageIndex]; pdfPage.CustomHeaderTemplate = altHeaderTemplate; pdfPage.ShowHeaderTemplate = true; } #endregion mergedDocument.AppendDocument(header); mergedDocument.AppendDocument(pdfDocument); try { mergedDocument.Save(PDFPath); } finally { // close the Documents to realease all the resources mergedDocument.Close(); header.Close(); pdfDocument.Close(); document.Close(); pdfDocumentI.Close(); lstBlankPage.Clear(); TOC_INDEX_COUNT = 0; FreeResources(); } }
public Document GeneratePdfDocumentUsingComponent(string sHtml, string headerLeft, string footer, bool putHeaderDate = true) { PdfConverter pdfConverter = new PdfConverter(); pdfConverter = GeneratePdfConverter(headerLeft, footer, putHeaderDate); return pdfConverter.GetPdfDocumentObjectFromHtmlString(sHtml); }