文档目录可以帮助读者快速检索并跳转到文档中的指定章节。有了目录以后,阅览起文档来就方便了许多,尤其是篇幅较大的文档。本文将介绍如何使用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();
}
}
生成目录: