import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
public class PDFBookmarkUtil {
/**
*@param outlines 书签文件的路径
*@param sPdfPath 需要生成书签的文件
*@param filename 生成书签后的文件路径
*/
public static void createPdf(Map<Integer, String> outlines, String sPdfPath, String filename) throws DocumentException, IOException {
//可以创建新的文件,也可以直接操作源文件,添加书签
// step 1
Document document = new Document();
// step 2 输出文件
PdfCopy writer = new PdfCopy(document, new FileOutputStream(filename)); // step 3
writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);//设置打开pdf文件时显示书签
document.open();
// step 4 逐页读入pdf文件并写入输出文件
PdfReader reader = new PdfReader(sPdfPath);
int n = reader.getNumberOfPages();
for (int page = 1; page <= n; page++) {
writer.addPage(writer.getImportedPage(reader, page));
}
writer.freeReader(reader);
// step 5 添加书签
PdfOutline root = writer.getRootOutline();
//数据遍历,添加书签
for (Map.Entry<Integer, String> entry : outlines.entrySet()) {
String sectionTitle = entry.getValue();
int page = entry.getKey() + 1;
//标识书签点击后的跳转动作,通过它设置跳转的页码
PdfAction action = PdfAction.gotoLocalPage(page,new PdfDestination(PdfDestination.FIT), writer);//设置书签动作
new PdfOutline(root, action, sectionTitle, false); //一级章节标题;
}
document.close();
}
}