文档彩票走势图>>Spire.PDF教程-文档操作>>【教程】Spire.PDF教程:C# 如何在PDF中创建目录
【教程】Spire.PDF教程:C# 如何在PDF中创建目录
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"); }
截图: