【教程】Spire.PDF教程:C# 如何在PDF中创建目录

下载Spire.PDF最新试用版

对于大型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");}

截图:

create table of contents on PDF
想要购买正版授权,或者获取更多Spire.PDF相关信息的朋友可以点击” 咨询在线客服 “~

标签:文档管理PDFOffice文档处理

声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2019年1月13日
下一篇 2019年1月13日

相关推荐

发表回复

登录后才能评论