本文介绍使用spire.pdf for java来读取pdf中的书签。
import com.spire.pdf.*;
import com.spire.pdf.bookmarks.pdfbookmark;
import com.spire.pdf.bookmarks.pdfbookmarkcollection;
import java.io.filewriter;
import java.io.ioexception;
public class getbookmark {
public static void main(string[] args) {
//加载包含书签的pdf文档
pdfdocument pdf = new pdfdocument();
pdf.loadfromfile("addbookmarks.pdf");
//获取书签集合
pdfbookmarkcollection bookmarkcollection = pdf.getbookmarks();
//实例化stringbuilder类
stringbuilder stringbuilder = new stringbuilder();
//定义方法获取书签
getbookmarktitle(bookmarkcollection, stringbuilder);
//声明txt文件,并将获得的多级书签写入到文件.txt
filewriter writer;
try {
writer = new filewriter("读取的书签.txt");
writer.write(stringbuilder.tostring());
writer.flush();
} catch (ioexception e) {
e.printstacktrace();
}
pdf.dispose();
}
//定义方法获取书签标题
static void getbookmarktitle(pdfbookmarkcollection bookmarkcollection, stringbuilder stringbuilder)
{
if (bookmarkcollection.getcount()> 0)
{
for(int i = 0 ; i< bookmarkcollection.getcount(); i )
{
pdfbookmark parentbookmark = bookmarkcollection.get(i);
stringbuilder.append(parentbookmark.gettitle());
//递归文档多级书签
getbookmarktitle(parentbookmark, stringbuilder);
}
}
}
}
书签读取结果: