Java 给PDF添加一级书签

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();
}

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值