轉帖|使用教程|編輯:黃竹雯|2019-01-17 11:20:34.000|閱讀 1184 次
概述:
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
Spire.PDF是一個專業的PDF組件,能夠獨立地創建、編寫、編輯、操作和閱讀PDF文件,支持 .NET、Java、WPF和Silverlight。
對于大型PDF文件,使用目錄可以讓文檔更容易訪問。通常,在PDF文檔中目錄被放在第一個頁面。使用Spire.PDF, 我們可以添加新的空白頁到現有的PDF文檔中,然后再創建目錄。下面我們將通過詳細的代碼來實現。
//加載PDF示例文檔 PdfDocument doc = new PdfDocument(); doc.LoadFromFile("Spire.pdf"); //獲取PDF頁數 int pageCount = doc.Pages.Count; //在第一頁插入空白頁 PdfPageBase tocPage = doc.Pages.Insert(0); //添加標題,并設置字體、樣式和位置 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); //設置目錄文本內容 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); //添加動作 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"); }
截圖:
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn