// loads TOC structure from an XPathNavigator private void LoadToc(XPathNavigator navigator, string parent, string parentVersion) { int i = -1; XPathNodeIterator interator = navigator.SelectChildren( TocXPath.Topic, String.Empty); while (interator.MoveNext()) { XPathNavigator current = interator.Current; string id = current.GetAttribute(TocAttr.Id, String.Empty); if (!String.IsNullOrEmpty(id)) { // For the root namespace container, we change the id to // the group id, which is same as the file name... if (String.Equals(id, "R:Project", StringComparison.OrdinalIgnoreCase)) { id = current.GetAttribute(TocAttr.File, String.Empty); } TocInfo info = new TocInfo(parent, parentVersion, ++i); _toc.Add(id, info); LoadToc(current, id, _topicVersion); } } }
//===================================================================== // Loads TOC structure from an XPathNavigator private void LoadToc(XPathNavigator navigator, string parent, string parentVersion) { // EFW - Reworked to support sortOrder attribute int sortOrder = 0; XPathNodeIterator interator = navigator.SelectChildren(TocXPath.Topic, String.Empty); while (interator.MoveNext()) { XPathNavigator current = interator.Current; string id = current.GetAttribute(TocAttr.Id, String.Empty); // If a sort order is defined, start from that value string order = current.GetAttribute(TocAttr.SortOrder, String.Empty); if (!String.IsNullOrEmpty(order) && Int32.TryParse(order, out int tempOrder)) { sortOrder = tempOrder; } if (!String.IsNullOrEmpty(id)) { TocInfo info = new TocInfo(parent, parentVersion, sortOrder++); // EFW - Work around a bug in Sandcastle that can result in duplicate IDs // by using the indexer to add the topic rather than Add() which throws // an exception when the duplicate is encountered. _toc[id] = info; LoadToc(current, id, _topicVersion); } } }
public static void Run() { // ExStart:AddTOC // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments(); // Load an existing PDF files Document doc = new Document(dataDir + "AddTOC.pdf"); // Get access to first page of PDF file Page tocPage = doc.Pages.Insert(1); // Create object to represent TOC information TocInfo tocInfo = new TocInfo(); TextFragment title = new TextFragment("Table Of Contents"); title.TextState.FontSize = 20; title.TextState.FontStyle = FontStyles.Bold; // Set the title for TOC tocInfo.Title = title; tocPage.TocInfo = tocInfo; // Create string objects which will be used as TOC elements string[] titles = new string[4]; titles[0] = "First page"; titles[1] = "Second page"; titles[2] = "Third page"; titles[3] = "Fourth page"; for (int i = 0; i < 2; i++) { // Create Heading object Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1); TextSegment segment2 = new TextSegment(); heading2.TocPage = tocPage; heading2.Segments.Add(segment2); // Specify the destination page for heading object heading2.DestinationPage = doc.Pages[i + 2]; // Destination page heading2.Top = doc.Pages[i + 2].Rect.Height; // Destination coordinate segment2.Text = titles[i]; // Add heading to page containing TOC tocPage.Paragraphs.Add(heading2); } dataDir = dataDir + "TOC_out.pdf"; // Save the updated document doc.Save(dataDir); // ExEnd:AddTOC Console.WriteLine("\nTOC added successfully to an existing PDF.\nFile saved at " + dataDir); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); // Load an existing PDF files Document doc = new Document(dataDir + "input.pdf"); // Get access to first page of PDF file Page tocPage = doc.Pages.Insert(1); // Create object to represent TOC information TocInfo tocInfo = new TocInfo(); TextFragment title = new TextFragment("Table Of Contents"); title.TextState.FontSize = 20; title.TextState.FontStyle = FontStyles.Bold; // Set the title for TOC tocInfo.Title = title; tocPage.TocInfo = tocInfo; // Create string objects which will be used as TOC elements string[] titles = new string[4]; titles[0] = "First page"; titles[1] = "Second page"; titles[2] = "Third page"; titles[3] = "Fourth page"; for (int i = 0; i < 2; i++) { // Create Heading object Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1); TextSegment segment2 = new TextSegment(); heading2.TocPage = tocPage; heading2.Segments.Add(segment2); // Specify the destination page for heading object heading2.DestinationPage = doc.Pages[i + 2]; // Destination page heading2.Top = doc.Pages[i + 2].Rect.Height; // Destination coordinate segment2.Text = titles[i]; // Add heading to page containing TOC tocPage.Paragraphs.Add(heading2); } // Save the updated document doc.Save(dataDir + "TOC_Output.pdf"); }
private void btnCreateTOC_Click(object sender, EventArgs e) { try { if (lstTitles.Items.Count > 0) { Document doc = new Document(txtPDF.Text); Page tocPage = doc.Pages.Insert(1); // Create object to represent TOC information TocInfo tocInfo = new TocInfo(); TextFragment title = new TextFragment("Table Of Contents"); title.TextState.FontSize = 20; title.TextState.FontStyle = FontStyles.Bold; // Set the title for TOC tocInfo.Title = title; tocPage.TocInfo = tocInfo; foreach (var item in lstTitles.Items) { TextFragmentAbsorber absorber = new TextFragmentAbsorber(item.ToString()); doc.Pages.Accept(absorber); Page targetPage = doc.Pages[absorber.TextFragments[1].Page.Number]; // Create Heading object Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1); TextSegment segment2 = new TextSegment(); heading2.TocPage = tocPage; heading2.Segments.Add(segment2); // Specify the destination page for heading object heading2.DestinationPage = targetPage; // Destination page heading2.Top = targetPage.Rect.Height; // Destination coordinate segment2.Text = item.ToString(); // Add heading to page containing TOC tocPage.Paragraphs.Add(heading2); } doc.Save("Toc_out.pdf"); MessageBox.Show("PDF with TOC has been created.", "Success"); } else { MessageBox.Show("Please extract titles from PDF document first.", "Titles are not extracted"); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } }
public static void Run() { //ExStart: CustomizePageNumbesWhileAddingTOC //Sometimes when we add TOC into PDF document it is required to customize the page numbering in the TOC. //For exapmle we need add some prefix before page number like "P1, P2, P3 ...". // For such case Aspose.PDF for .NET provides PageNumbersPrefix property of TocInfo class. //Code snippet below shows how to use this feature. string inFile = RunExamples.GetDataDir_AsposePdf_WorkingDocuments() + "42824.pdf"; string outFile = RunExamples.GetDataDir_AsposePdf_WorkingDocuments() + "42824_out.pdf"; // Load an existing PDF files Document doc = new Document(inFile); // Get access to first page of PDF file Aspose.Pdf.Page tocPage = doc.Pages.Insert(1); // Create object to represent TOC information TocInfo tocInfo = new TocInfo(); TextFragment title = new TextFragment("Table Of Contents"); title.TextState.FontSize = 20; title.TextState.FontStyle = FontStyles.Bold; // Set the title for TOC tocInfo.Title = title; tocInfo.PageNumbersPrefix = "P"; tocPage.TocInfo = tocInfo; for (int i = 1; i < doc.Pages.Count; i++) { // Create Heading object Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1); TextSegment segment2 = new TextSegment(); heading2.TocPage = tocPage; heading2.Segments.Add(segment2); // Specify the destination page for heading object heading2.DestinationPage = doc.Pages[i + 1]; // Destination page heading2.Top = doc.Pages[i + 1].Rect.Height; // Destination coordinate segment2.Text = "Page " + i.ToString(); // Add heading to page containing TOC tocPage.Paragraphs.Add(heading2); } // Save the updated document doc.Save(outFile); //ExEnd: CustomizePageNumbesWhileAddingTOC }
// loads TOC structure from an XPathNavigator private void LoadToc(XPathNavigator navigator, string parent, string parentVersion) { int i = -1; XPathNodeIterator interator = navigator.SelectChildren(TocXPath.Topic, string.Empty); while (interator.MoveNext()) { XPathNavigator current = interator.Current; string id = current.GetAttribute(TocAttr.Id, string.Empty); if (!string.IsNullOrEmpty(id)) { TocInfo info = new TocInfo(parent, parentVersion, ++i); _toc.Add(id, info); LoadToc(current, id, _topicVersion); } } }
public static void Run() { //ExStart: CustomizePageNumbesWhileAddingTOC string inFile = RunExamples.GetDataDir_AsposePdf_WorkingDocuments() + "42824.pdf"; string outFile = RunExamples.GetDataDir_AsposePdf_WorkingDocuments() + "42824_out.pdf"; // Load an existing PDF files Document doc = new Document(inFile); // Get access to first page of PDF file Aspose.Pdf.Page tocPage = doc.Pages.Insert(1); // Create object to represent TOC information TocInfo tocInfo = new TocInfo(); TextFragment title = new TextFragment("Table Of Contents"); title.TextState.FontSize = 20; title.TextState.FontStyle = FontStyles.Bold; // Set the title for TOC tocInfo.Title = title; tocInfo.PageNumbersPrefix = "P"; tocPage.TocInfo = tocInfo; for (int i = 1; i < doc.Pages.Count; i++) { // Create Heading object Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1); TextSegment segment2 = new TextSegment(); heading2.TocPage = tocPage; heading2.Segments.Add(segment2); // Specify the destination page for heading object heading2.DestinationPage = doc.Pages[i + 1]; // Destination page heading2.Top = doc.Pages[i + 1].Rect.Height; // Destination coordinate segment2.Text = "Page " + i.ToString(); // Add heading to page containing TOC tocPage.Paragraphs.Add(heading2); } // Save the updated document doc.Save(outFile); //ExEnd: CustomizePageNumbesWhileAddingTOC }
protected override void RegisterTocToContext(TocItemViewModel toc, FileModel model, IDocumentBuildContext context) { var key = model.Key; // Add current folder to the toc mapping, e.g. `a/` maps to `a/toc` var directory = ((RelativePath)key).GetPathFromWorkingFolder().GetDirectoryPath(); context.RegisterToc(key, directory); var tocInfo = new TocInfo(key); if (toc.Homepage != null) { if (PathUtility.IsRelativePath(toc.Homepage)) { var pathToRoot = ((RelativePath)model.File + (RelativePath)toc.Homepage).GetPathFromWorkingFolder(); tocInfo.Homepage = pathToRoot; } } context.RegisterTocInfo(tocInfo); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments(); string outFile = dataDir + "HiddenPageNumbers_out.pdf"; Document doc = new Document(); Page tocPage = doc.Pages.Add(); TocInfo tocInfo = new TocInfo(); TextFragment title = new TextFragment("Table Of Contents"); title.TextState.FontSize = 20; title.TextState.FontStyle = FontStyles.Bold; tocInfo.Title = title; //Add the list section to the sections collection of the Pdf document tocPage.TocInfo = tocInfo; //Define the format of the four levels list by setting the left margins and //text format settings of each level tocInfo.IsShowPageNumbers = false; tocInfo.FormatArrayLength = 4; tocInfo.FormatArray[0].Margin.Right = 0; tocInfo.FormatArray[0].TextState.FontStyle = FontStyles.Bold | FontStyles.Italic; tocInfo.FormatArray[1].Margin.Left = 30; tocInfo.FormatArray[1].TextState.Underline = true; tocInfo.FormatArray[1].TextState.FontSize = 10; tocInfo.FormatArray[2].TextState.FontStyle = FontStyles.Bold; tocInfo.FormatArray[3].TextState.FontStyle = FontStyles.Bold; Page page = doc.Pages.Add(); //Add four headings in the section for (int Level = 1; Level != 5; Level++) { Heading heading2 = new Heading(Level); TextSegment segment2 = new TextSegment(); heading2.TocPage = tocPage; heading2.Segments.Add(segment2); heading2.IsAutoSequence = true; segment2.Text = "this is heading of level " + Level; heading2.IsInList = true; page.Paragraphs.Add(heading2); } doc.Save(outFile); // ExEnd:1 }
public override void UpdateHref(FileModel model, IDocumentBuildContext context) { var toc = (TocItemViewModel)model.Content; var key = model.Key; // Add current folder to the toc mapping, e.g. `a/` maps to `a/toc` var directory = ((TypeForwardedToRelativePath)key).GetPathFromWorkingFolder().GetDirectoryPath(); context.RegisterToc(key, directory); UpdateTocItemHref(toc, model, context); var tocInfo = new TocInfo(key); if (toc.Homepage != null) { if (TypeForwardedToPathUtility.IsRelativePath(toc.Homepage)) { var pathToRoot = ((TypeForwardedToRelativePath)model.File + (TypeForwardedToRelativePath)toc.Homepage).GetPathFromWorkingFolder(); tocInfo.Homepage = pathToRoot; } } context.RegisterTocInfo(tocInfo); }
public RelativeInfo(TocInfo tocInfo, FileAndType article) { TocInfo = tocInfo; TocPathRelativeToArticle = tocInfo.OutputPath.RemoveWorkingFolder().MakeRelativeTo(GetOutputPath(article)); }
/// <summary> /// Responsible to merge different pdf documents and generate into one single PDF /// along with the bookmark and table of content /// </summary> /// <returns> Path of the PDF document </returns> public string GeneratePDF() { // Used to keep a track of current generated PDF page number int pdfPageNo = 2; // Used to create bookmark and Table of content List <TOC> toc = new List <TOC>(); if (!Directory.Exists(PDFFolderPath)) { Directory.CreateDirectory(PDFFolderPath); } //aspose words license //var AsposeLicenseFilePath = "C://Users//Aditya//.nuget//packages//aspose.pdf//19.9.0//lib//net4.0 - client//Aspose.Pdf.lic"; //if (System.IO.File.Exists(AsposeLicenseFilePath)) //{ // Aspose.Pdf.License WordsLic = new Aspose.Pdf.License(); // WordsLic.SetLicense(AsposeLicenseFilePath); //} if (File.Exists(PDFFilePath)) { File.Delete(PDFFilePath); } // Used to maintaint the list of all the documents to be merged. List <String> inputDocs = new List <String>(); // Fetches all the documents from the specified DocumentFolderPath foreach (string file in Directory.EnumerateFiles(DocumentFolderPath, "*.pdf")) { inputDocs.Add(file); } Document targetDoc = new Document(); Document doc; for (int i = 0; i < inputDocs.Count; i++) { doc = new Document(inputDocs[i]); toc.Add(new TOC { BookmarkName = Path.GetFileName(doc.FileName), PageNo = pdfPageNo }); // Add the pages of the source documents to the target document targetDoc.Pages.Add(doc.Pages); #region Code to generate Blank page between two documents Page pageI = targetDoc.Pages.Insert(pdfPageNo); TextFragment textI = new TextFragment("Blank Page"); pageI.Paragraphs.Add(textI); // Create a bookmark object OutlineItemCollection pdfOutlineI = new OutlineItemCollection(targetDoc.Outlines); pdfOutlineI.Title = "Blank Page"; pdfOutlineI.Italic = true; pdfOutlineI.Bold = true; // Add bookmark in the document's outline collection. targetDoc.Outlines.Add(pdfOutlineI); pdfPageNo = pdfPageNo + doc.Pages.Count; pdfPageNo++; #endregion } #region Code to generate Table of Content string html = "";// above html HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(html); Page tocPage = targetDoc.Pages.Insert(1); tocPage.Background = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.White); // Create object to represent TOC information TocInfo tocInfo = new TocInfo(); TextFragment title = new TextFragment("Table Of Contents"); title.TextState.FontSize = 20; title.TextState.FontStyle = FontStyles.Bold; // Set the title for TOC tocInfo.Title = title; tocPage.TocInfo = tocInfo; foreach (var item in toc) { // Create Heading object Heading heading2 = new Heading(1); TextSegment segment2 = new TextSegment(); segment2 = new TextSegment(); heading2.TocPage = tocPage; heading2.Segments.Add(segment2); // Specify the destination page for heading object heading2.DestinationPage = targetDoc.Pages[item.PageNo]; // Destination page heading2.Top = targetDoc.Pages[item.PageNo].Rect.Height; // Destination coordinate segment2.Text = item.BookmarkName; // Add heading to page containing TOC tocPage.Paragraphs.Add(heading2); } #endregion targetDoc.Save(PDFFilePath); #region Code to bookmark the pages // For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.Pdf-for-.NET // Open document PdfBookmarkEditor bookmarkEditor = new PdfBookmarkEditor(); bookmarkEditor.BindPdf(PDFFilePath); // Create bookmark of a range of pages foreach (var item in toc) { bookmarkEditor.CreateBookmarkOfPage(item.BookmarkName, item.PageNo); } // Save updated PDF file bookmarkEditor.Save(PDFFilePath); #endregion return(PDFFilePath); }
/// <summary> /// Applies Microsoft Help System transformation to the output document. /// </summary> /// <param name="document">The <see cref="XmlDocument"/> to apply transformation to.</param> /// <param name="key">Topic key of the output document.</param> public override void Apply(XmlDocument document, string key) { ModifyAttribute(document, "id", "mainSection"); ModifyAttribute(document, "class", "members"); FixHeaderBottomBackground(document, "nsrBottom", "headerBottom"); XmlElement html = document.DocumentElement; XmlElement head = html.SelectSingleNode(Help2XPath.Head) as XmlElement; if (head == null) { head = document.CreateElement(Help2XPath.Head); if (!html.HasChildNodes) { html.AppendChild(head); } else { html.InsertBefore(head, html.FirstChild); } } else { XmlNode hxNode = head.SelectSingleNode(Help2XPath.HxRuntime); if (hxNode != null) { head.RemoveChild(hxNode); } } AddMHSMeta(document, head, MHSMetaName.SelfBranded, _selfBranded.ToString().ToLower()); AddMHSMeta(document, head, MHSMetaName.ContentType, MHSDefault.Reference); AddMHSMeta(document, head, MHSMetaName.TopicVersion, _topicVersion); string locale = _locale; string id = Guid.NewGuid().ToString(); XmlNode xmlIsland = head.SelectSingleNode(Help2XPath.Xml); if (xmlIsland != null) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); if (!nsmgr.HasNamespace(Help2Namespace.Prefix)) { nsmgr.AddNamespace(Help2Namespace.Prefix, Help2Namespace.Uri); } XmlElement elem = xmlIsland.SelectSingleNode(Help2XPath.TocTitle, nsmgr) as XmlElement; if (elem != null) { AddMHSMeta(document, head, MHSMetaName.Title, elem.GetAttribute(Help2Attr.Title)); } foreach (XmlElement keyword in xmlIsland.SelectNodes(String.Format(Help2XPath.Keyword, Help2Value.K), nsmgr)) { AddMHSMeta(document, head, MHSMetaName.Keywords, keyword.GetAttribute(Help2Attr.Term), true); } foreach (XmlElement keyword in xmlIsland.SelectNodes(String.Format(Help2XPath.Keyword, Help2Value.F), nsmgr)) { AddMHSMeta(document, head, MHSMetaName.F1, keyword.GetAttribute(Help2Attr.Term), true); } foreach (XmlElement lang in xmlIsland.SelectNodes(String.Format(Help2XPath.Attr, Help2Value.DevLang), nsmgr)) { AddMHSMeta(document, head, MHSMetaName.Category, Help2Value.DevLang + ":" + lang.GetAttribute(Help2Attr.Value), true); } elem = xmlIsland.SelectSingleNode(String.Format(Help2XPath.Attr, Help2Value.Abstract), nsmgr) as XmlElement; if (elem != null) { AddMHSMeta(document, head, MHSMetaName.Description, elem.GetAttribute(Help2Attr.Value)); } elem = xmlIsland.SelectSingleNode(String.Format(Help2XPath.Attr, Help2Value.AssetID), nsmgr) as XmlElement; if (elem != null) { id = elem.GetAttribute(Help2Attr.Value); } if (String.IsNullOrEmpty(locale)) { elem = xmlIsland.SelectSingleNode(String.Format(Help2XPath.Attr, Help2Value.Locale), nsmgr) as XmlElement; if (elem != null) { locale = elem.GetAttribute(Help2Attr.Value); } } head.RemoveChild(xmlIsland); } if (String.IsNullOrEmpty(locale)) { locale = MHSDefault.Locale; } AddMHSMeta(document, head, MHSMetaName.Locale, locale); AddMHSMeta(document, head, MHSMetaName.TopicLocale, locale); AddMHSMeta(document, head, MHSMetaName.Id, id); if (_toc.ContainsKey(id)) { TocInfo tocInfo = _toc[id]; AddMHSMeta(document, head, MHSMetaName.TocParent, tocInfo.Parent); if (tocInfo.Parent != MHSDefault.TocParent) { AddMHSMeta(document, head, MHSMetaName.TocParentVersion, tocInfo.ParentVersion); } AddMHSMeta(document, head, MHSMetaName.TocOrder, tocInfo.Order.ToString()); } //FixFooter(document); }
public void RegisterTocInfo(TocInfo toc) { _tableOfContents[toc.TocFileKey] = toc; }
/// <summary> /// Applies Microsoft Help System transformation to the output document. /// </summary> /// <param name="document">The <see cref="XmlDocument"/> to apply transformation to.</param> /// <param name="key">Topic key of the output document.</param> public override void Apply(XmlDocument document, string key) { _document = document; XmlElement html = _document.DocumentElement; _head = html.SelectSingleNode(Help2XPath.Head); if (_head == null) { _head = document.CreateElement(Help2XPath.Head); if (!html.HasChildNodes) { html.AppendChild(_head); } else { html.InsertBefore(_head, html.FirstChild); } } else { // !EFW - Remove the unnecessary Help 2 CSS link element from the header XmlNode hxLink = _head.SelectSingleNode(Help2XPath.HxLink); if (hxLink != null) { _head.RemoveChild(hxLink); } } // Apply some fix-ups if not branding aware if (_head.SelectSingleNode("meta[@name='BrandingAware']") == null) { ModifyAttribute("id", "mainSection"); ModifyAttribute("class", "members"); } AddMHSMeta(MHSMetaName.SelfBranded, _selfBranded.ToString().ToLowerInvariant()); AddMHSMeta(MHSMetaName.TopicVersion, _topicVersion); string locale = _locale; string id = Guid.NewGuid().ToString(); _xml = _head.SelectSingleNode(Help2XPath.Xml); if (_xml != null) { XmlNamespaceManager nsmgr = new XmlNamespaceManager(_document.NameTable); if (!nsmgr.HasNamespace(Help2Namespace.Prefix)) { nsmgr.AddNamespace(Help2Namespace.Prefix, Help2Namespace.Uri); } XmlElement elem = _xml.SelectSingleNode(Help2XPath.TocTitle, nsmgr) as XmlElement; if (elem != null) { AddMHSMeta(MHSMetaName.Title, elem.GetAttribute(Help2Attr.Title)); } foreach (XmlElement keyword in _xml.SelectNodes(String.Format(CultureInfo.InvariantCulture, Help2XPath.Keyword, Help2Value.K), nsmgr)) { AddMHSMeta(MHSMetaName.Keywords, keyword.GetAttribute(Help2Attr.Term), true); } foreach (XmlElement keyword in _xml.SelectNodes(String.Format(CultureInfo.InvariantCulture, Help2XPath.Keyword, Help2Value.F), nsmgr)) { AddMHSMeta(MHSMetaName.F1, keyword.GetAttribute(Help2Attr.Term), true); } foreach (XmlElement lang in _xml.SelectNodes(String.Format(CultureInfo.InvariantCulture, Help2XPath.Attr, Help2Value.DevLang), nsmgr)) { AddMHSMeta(MHSMetaName.Category, Help2Value.DevLang + ":" + lang.GetAttribute(Help2Attr.Value), true); } elem = _xml.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, Help2XPath.Attr, Help2Value.Abstract), nsmgr) as XmlElement; if (elem != null) { AddMHSMeta(MHSMetaName.Description, elem.GetAttribute(Help2Attr.Value)); } elem = _xml.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, Help2XPath.Attr, Help2Value.AssetID), nsmgr) as XmlElement; if (elem != null) { id = elem.GetAttribute(Help2Attr.Value); } if (String.IsNullOrEmpty(locale)) { elem = _xml.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, Help2XPath.Attr, Help2Value.Locale), nsmgr) as XmlElement; if (elem != null) { locale = elem.GetAttribute(Help2Attr.Value); } } // !EFW - Remove the XML data island as it serves no purpose _head.RemoveChild(_xml); } if (String.IsNullOrEmpty(locale)) { locale = MHSDefault.Locale; } AddMHSMeta(MHSMetaName.Locale, locale); AddMHSMeta(MHSMetaName.TopicLocale, locale); AddMHSMeta(MHSMetaName.Id, id); if (_toc.ContainsKey(id)) { TocInfo tocInfo = _toc[id]; AddMHSMeta(MHSMetaName.TocParent, tocInfo.Parent); if (tocInfo.Parent != MHSDefault.TocParent) { AddMHSMeta(MHSMetaName.TocParentVersion, tocInfo.ParentVersion); } AddMHSMeta(MHSMetaName.TocOrder, tocInfo.Order.ToString(CultureInfo.InvariantCulture)); } }
protected void btnMergeAllFiles_Click(object sender, EventArgs e) { try { //delete file if already exists... if (File.Exists(Server.MapPath("~/Uploads/Catalog.pdf"))) { File.Delete(Server.MapPath("~/Uploads/Catalog.pdf")); } // create new document to save the catalog... Document doc = new Document(); //get all the applications in the directory string[] pdfFiles = Directory.GetFiles(Server.MapPath("~/Uploads"), "*.pdf") .Select(path => Path.GetFileName(path)) .ToArray(); if (pdfFiles.Count() == 0) { msg.Text = "<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>There is currently no application available.</div>"; return; } else { foreach (string val in pdfFiles) { //get the pdf document.. Document application = new Document(Server.MapPath("~/Uploads/" + val)); //merge the pages in catalog document... doc.Pages.Add(application.Pages); } //====================================== Adding Table of Content Starts ========================================= //add TOC page... Aspose.Pdf.Page tocPage = doc.Pages.Insert(1); //add watermark on table of content AddWaterMark(tocPage); // Create object to represent TOC information TocInfo tocInfo = new TocInfo(); TextFragment title = new TextFragment("Table Of Contents"); title.TextState.FontSize = 20; title.TextState.FontStyle = FontStyles.Bold; // Set the title for TOC tocInfo.Title = title; tocPage.TocInfo = tocInfo; for (int i = 0; i < pdfFiles.Count(); i++) { // Create Heading object Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1); TextSegment segment2 = new TextSegment(); heading2.TocPage = tocPage; heading2.Segments.Add(segment2); // Specify the destination page for heading object heading2.DestinationPage = doc.Pages[i + 2]; // Destination page heading2.Top = doc.Pages[i + 2].Rect.Height; // Destination coordinate segment2.Text = "Application Form No. " + (i + 1).ToString(); // Add heading to page containing TOC tocPage.Paragraphs.Add(heading2); } //===================================== TOC Ends ========================================== //save the final catalog file... string catalogpath = Server.MapPath("~/Catalogs/Catalog.pdf"); doc.Save(catalogpath); msg.Text = "<div class='alert alert-success'><button data-dismiss='alert' class='close' type='button'>×</button>Applications have been saved in catalog.</div>"; //show success message } } catch (Exception exp) { msg.Text = "<div class='alert alert-danger'><button data-dismiss='alert' class='close' type='button'>×</button>Exception Occured:" + exp.Message + "</div>"; } }
//===================================================================== // Loads TOC structure from an XPathNavigator private void LoadToc(XPathNavigator navigator, string parent, string parentVersion) { // EFW - Reworked to support sortOrder attribute int sortOrder = 0, tempOrder; XPathNodeIterator interator = navigator.SelectChildren(TocXPath.Topic, String.Empty); while(interator.MoveNext()) { XPathNavigator current = interator.Current; string id = current.GetAttribute(TocAttr.Id, String.Empty); // If a sort order is defined, start from that value string order = current.GetAttribute(TocAttr.SortOrder, String.Empty); if(!String.IsNullOrEmpty(order) && Int32.TryParse(order, out tempOrder)) sortOrder = tempOrder; if(!String.IsNullOrEmpty(id)) { TocInfo info = new TocInfo(parent, parentVersion, sortOrder++); // EFW - Work around a bug in Sandcastle that can result in duplicate IDs // by using the indexer to add the topic rather than Add() which throws // an exception when the duplicate is encountered. _toc[id] = info; LoadToc(current, id, _topicVersion); } } }
private void btnCreatePDF_Click(object sender, EventArgs e) { try { if (lstTitles.Items.Count > 0) { Dictionary <string, List <int> > titles = new Dictionary <string, List <int> >(); List <string> ts = new List <string>(); Document doc = new Document(txtPDF.Text); foreach (Page page in doc.Pages) { TextFragmentAbsorber absorber = new TextFragmentAbsorber(); page.Accept(absorber); if (titles.Where(x => x.Key == absorber.TextFragments[1].Text).ToList().Count > 0) { titles[absorber.TextFragments[1].Text].Add(absorber.TextFragments[1].Page.Number); ts.Remove(absorber.TextFragments[1].Text); } else { titles.Add(absorber.TextFragments[1].Text, new List <int>() { absorber.TextFragments[1].Page.Number }); ts.Add(absorber.TextFragments[1].Text); } } // Get chapters which are more than 1 page var pages = titles.Where(x => x.Value.Count > 1).Select(x => x.Value).ToList(); List <int> ps = new List <int>(); if (pages.Count > 0) { foreach (var page in pages) { Document newDoc = new Document(); foreach (var p in page) { newDoc.Pages.Add(doc.Pages[p]); ps.Add(p); } newDoc.Save("newPDF_" + DateTime.Now.Millisecond + ".pdf"); } // Delete extracted pages from existing PDF doc.Pages.Delete(ps.ToArray()); doc.Save("tmp.pdf"); } // Create TOC for remaining pages doc = new Document("tmp.pdf"); Page tocPage = doc.Pages.Insert(1); // Create object to represent TOC information TocInfo tocInfo = new TocInfo(); TextFragment title = new TextFragment("Table Of Contents"); title.TextState.FontSize = 20; title.TextState.FontStyle = FontStyles.Bold; // Set the title for TOC tocInfo.Title = title; tocPage.TocInfo = tocInfo; foreach (var s in ts) { TextFragmentAbsorber absorber = new TextFragmentAbsorber(s); doc.Pages.Accept(absorber); Page targetPage = doc.Pages[absorber.TextFragments[1].Page.Number]; // Create Heading object Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1); TextSegment segment2 = new TextSegment(); heading2.TocPage = tocPage; heading2.Segments.Add(segment2); // Specify the destination page for heading object heading2.DestinationPage = targetPage; // Destination page heading2.Top = targetPage.Rect.Height; // Destination coordinate segment2.Text = s; // Add heading to page containing TOC tocPage.Paragraphs.Add(heading2); } doc.Save("Toc_" + DateTime.Now.Millisecond + ".pdf"); File.Delete("tmp.pdf"); MessageBox.Show("PDF with TOC has been created.", "Success"); } else { MessageBox.Show("Please extract titles from PDF document first.", "Titles are not extracted"); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } }