文档目录可以帮助读者快速检索并跳转到文档中的指定章节。有了目录以后,阅览起文档来就方便了许多,尤其是篇幅较大的文档。本文将介绍如何使用Spire.PDF for Java给PDF文档添加目录。
import com.spire.pdf.*;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.annotations.*;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;
public class TableOfContent {
public static void main(String[] args) throws Exception
{
//加载PDF文档
PdfDocument doc = new PdfDocument("sample (1).pdf");
int pageCount = doc.getPages().getCount();
//插入一个新的页面到第一页,用于绘制目录
PdfPageBase tocPage = doc.getPages().insert(0);
//设置目录标题
String title = "目录";
PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("宋体", Font.BOLD,20));
PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
Point2D location = new Point2D.Float((float) tocPage.getCanvas().getClientSize().getWidth() / 2, (float) titleFont.measureString(title).getHeight());
tocPage.getCanvas().drawString(title, titleFont, PdfBrushes.getCornflowerBlue(), location, centerAlignment);
//绘制目录内容,并设置目录字体、样式以及绘制位置
PdfTrueTypeFont titlesFont = new PdfTrueTypeFont(new Font("宋体", Font.PLAIN,14));
String[] titles = new String[pageCount];
for (int i = 0; i < titles.length; i++) {
titles[i] = String.format("第%1$s页", i + 1);
}
float y = (float)titleFont.measureString(title).getHeight() + 10;
float x = 0;
for (int i = 1; i <= pageCount; i++) {
String text = titles[i - 1];
Dimension2D titleSize = titlesFont.measureString(text);
PdfPageBase navigatedPage = doc.getPages().get(i);
String pageNumText = (String.valueOf(i+1));
Dimension2D pageNumTextSize = titlesFont.measureString(pageNumText);
tocPage.getCanvas().drawString(text, titlesFont, PdfBrushes.getCadetBlue(), 0, y);
float dotLocation = (float)titleSize.getWidth() + 2 + x;
float pageNumlocation = (float)(tocPage.getCanvas().getClientSize().getWidth() - pageNumTextSize.getWidth());
for (float j = dotLocation; j < pageNumlocation; j++) {
if (dotLocation >= pageNumlocation) {
break;
}
tocPage.getCanvas().drawString(".", titlesFont, PdfBrushes.getGray(), dotLocation, y);
dotLocation += 3;
}
tocPage.getCanvas().drawString(pageNumText, titlesFont, PdfBrushes.getCadetBlue(), pageNumlocation, y);
//给目录添加动作以链接到其在PDF文档中对应的位置
Rectangle2D titleBounds = new Rectangle2D.Float(0,y,(float)tocPage.getCanvas().getClientSize().getWidth(),(float)titleSize.getHeight());
PdfDestination Dest = new PdfDestination(navigatedPage, new Point2D.Float(-doc.getPageSettings().getMargins().getTop(), -doc.getPageSettings().getMargins().getLeft()));
PdfActionAnnotation action = new PdfActionAnnotation(titleBounds, new PdfGoToAction(Dest));
action.setBorder(new PdfAnnotationBorder(0));
((PdfNewPage) ((tocPage instanceof PdfNewPage) ? tocPage : null)).getAnnotations().add(action);
y += titleSize.getHeight() + 10;
}
//保存结果文档
doc.saveToFile("addTableOfContent.pdf");
doc.close();
}
}
生成目录: