文檔首頁>>Spire.PDF教程-文檔操作>>【教程】Spire.PDF教程:C# 如何在PDF中創(chuàng)建目錄
【教程】Spire.PDF教程:C# 如何在PDF中創(chuàng)建目錄
Spire.PDF是一個(gè)專業(yè)的PDF組件,能夠獨(dú)立地創(chuàng)建、編寫、編輯、操作和閱讀PDF文件,支持 .NET、Java、WPF和Silverlight。
對(duì)于大型PDF文件,使用目錄可以讓文檔更容易訪問。通常,在PDF文檔中目錄被放在第一個(gè)頁面。使用Spire.PDF, 我們可以添加新的空白頁到現(xiàn)有的PDF文檔中,然后再創(chuàng)建目錄。下面我們將通過詳細(xì)的代碼來實(shí)現(xiàn)。
//加載PDF示例文檔 PdfDocument doc = new PdfDocument(); doc.LoadFromFile("Spire.pdf"); //獲取PDF頁數(shù) int pageCount = doc.Pages.Count; //在第一頁插入空白頁 PdfPageBase tocPage = doc.Pages.Insert(0); //添加標(biāo)題,并設(shè)置字體、樣式和位置 string title = "目錄"; PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("宋體", 16, FontStyle.Bold),true); PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle); PointF location = new PointF(tocPage.Canvas.ClientSize.Width / 2, titleFont.MeasureString(title).Height); tocPage.Canvas.DrawString(title, titleFont, PdfBrushes.Black, location, centerAlignment); //設(shè)置目錄文本內(nèi)容 PdfTrueTypeFont titlesFont = new PdfTrueTypeFont(new Font("宋體", 10),true); String[] titles = new String[pageCount]; for (int i = 0; i < titles.Length; i++) { titles[i] = string.Format("文件第{0}頁", i + 1); } float y = titleFont.MeasureString(title).Height + 10; float x = 0; for (int i = 1; i <= pageCount; i++) { string text = titles[i - 1]; SizeF titleSize = titlesFont.MeasureString(text); PdfPageBase navigatedPage = doc.Pages[i]; string pageNumText = (i + 1).ToString(); SizeF pageNumTextSize = titlesFont.MeasureString(pageNumText); tocPage.Canvas.DrawString(text, titlesFont, PdfBrushes.Black, 0, y); float dotLocation = titleSize.Width + 2 + x; float pageNumlocation = tocPage.Canvas.ClientSize.Width - pageNumTextSize.Width; for (float j = dotLocation; j < pageNumlocation; j++) { if (dotLocation >= pageNumlocation) { break; } tocPage.Canvas.DrawString(".", titlesFont, PdfBrushes.Black, dotLocation, y); dotLocation += 2; } tocPage.Canvas.DrawString(pageNumText, titlesFont, PdfBrushes.Black, pageNumlocation, y); //添加動(dòng)作 location = new PointF(0, y); RectangleF titleBounds = new RectangleF(location, new SizeF(tocPage.Canvas.ClientSize.Width, titleSize.Height)); PdfDestination Dest = new PdfDestination(navigatedPage, new PointF(-doc.PageSettings.Margins.Top, -doc.PageSettings.Margins.Left)); PdfActionAnnotation action = new PdfActionAnnotation(titleBounds, new PdfGoToAction(Dest)); action.Border = new PdfAnnotationBorder(0); (tocPage as PdfNewPage).Annotations.Add(action); y += titleSize.Height + 10; //保存已添加目錄文檔 string output = "目錄文檔.pdf"; doc.SaveToFile(output, FileFormat.PDF); System.Diagnostics.Process.Start("目錄文檔.pdf"); }
截圖: