通过html生成pdf并生成书签

通过html生成pdf,可使用[睿印](https://gitee.com/Rayin/rayin) 工具包,睿印java工具包是集成openhtmltopdf,pdfbox的开源工具包,集成了thymeleaf 动态脚本,并可自动加载字体,默认支持中文显示。

1. 首先新建java maven项目,引入jar包
```xml
<dependency>
  <groupId>ink.rayin</groupId>
  <artifactId>rayin-htmladapter-openhtmltopdf</artifactId>
  <version>1.0.8</version>
</dependency>
```
2. 新建html,保存至test/resources下,命名为element1.html
```html
<!DOCTYPE html>
<html lang="zh-CN" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"/>
    <style>
       body {
                  font-family: FangSong,HanaMinB;
                  line-height: 1.2;
                  /*设置背景色*/
                  /*background: #00FF00 ;*/
                  /*设置背景图片*/
                  /*background-image:url(data:image/gif;base64,AAAA) no-repeat fixed top;*/
              }
              /** 指定pdf纸张大小 **/
              @page {
                  size: A4 ;
                  margin: 1cm;
                  /*margin-bottom: 1cm;*/
                  /*border: thin solid black;*/
              }

              .page_break { page-break-after:always;}

              .seclev2 {
                text-indent:20pt;
              }
              .seclev2c {
                   text-indent:40pt;
               }
            a {
                text-decoration:none;
             }
         a:link {
            color:#000000;
         }
         a:visited {color:#00FF00;}
    </style>
</head>
<body>
<!-- 该部分为书签生成使用到的tag href #后的名称对应的下方的id 名称-->
<bookmarks>
    <bookmark name="第一章" href="#section1">
        <bookmark name="1.1 xxx" href="#subsec11"/>
        <bookmark name="1.2 xxx" href="#subsec12"/>
        <bookmark name="1.3 xxx" href="#subsec13"/>
    </bookmark>
    <bookmark name="第二章" href="#section2">
        <bookmark name="2.1 xxxx" href="#subsec21"/>
        <bookmark name="2.2 xxxx" href="#subsec22"/>
        <bookmark name="2.3 xxx" href="#subsec23"/>
    </bookmark>
    <bookmark name="第三章" href="#section3">
        <bookmark name="3.1 xxx" href="#subsec31"/>
        <bookmark name="3.2 xxx" href="#subsec32"/>
        <bookmark name="3.3 xxx" href="#subsec33"/>
    </bookmark>
</bookmarks>

<div style="page-break-after:always;"></div>
<div id="section1" class="seclev1"><h1>第一章</h1></div>
<div id="subsec11" class="seclev2"><h2>1.1 xxxx</h2>
    <div>内容</div>
</div>

<div id="subsec12" class="seclev2"><h2>1.2 xxxx</h2>
    <div>内容</div>
</div>

<div id="subsec13" class="seclev2"><h2>1.3 xxxx</h2>
    <div>内容</div>
</div>
<div style="page-break-after:always;"></div>
<div id="section2" ><h1>第二章</h1></div>
<div id="subsec21" class="seclev2"><h2>2.1 xxxx</h2>
    <div>内容</div>
</div>
<div id="subsec22" class="seclev2"><h2>2.2 xxxx</h2>
    <div>内容</div>
</div>

<div id="subsec23" class="seclev2"><h2>2.3 xxxx</h2>
    <div>内容</div>
</div>

<div style="page-break-after:always;"></div>
<div id="section3"><h1>第三章</h1></div>
<div id="subsec31" class="seclev2"><h2>3.1 xxxx</h2>
    <div>内容</div>
</div>
<div id="subsec32" class="seclev2"><h2>3.2 xxxx</h2>
    <div>内容</div>
</div>
<div id="subsec33" class="seclev2"><h2>3.3 xxxx</h2>
    <div>内容</div>
</div>
</body>
</html>

```

3. 项目test中新建测试类
```java
@Slf4j
public class PDFGeneratorOpenhtmltopdfTest {
    static PdfGenerator pdfGenerator;
    static  {
        try {
            pdfGenerator = new PdfBoxGenerator();
            pdfGenerator.init();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void markbooksTest() throws Exception {
        log.info("markbooksTest start time:" + new Timestamp(System.currentTimeMillis()));

        String outputFileClass = ResourceUtil.getResourceAbsolutePathByClassPath("");

        // 生成pdf路径
        // generate pdf path
        String outputFile = new File(outputFileClass)
                .getParentFile().getParent()
                + "/tmp/"
                + "markbooks_"+System.currentTimeMillis() + ".pdf";

        //数据参数可以为空
        pdfGenerator.generatePdfFileByHtmlAndData(ResourceUtil.getResourceAbsolutePathByClassPath("element1.html"),null,outputFile);

        log.info("markbooksTest end time:" + new Timestamp(System.currentTimeMillis()));
    }
}
```
4. 生成PDF如下
![带书签的pdf](https://upload-images.jianshu.io/upload_images/20159874-3be7164bdc884337.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

至此大功告成!


## pdfbox读取pdf书签
生成的pdf标签也可以通过pdfbox来读取。
```java
@Test
public void bookmarksTest() throws IOException {
        PDDocument pdfWithBookmarks = PDDocument.load(ResourceUtil.getResourceAsStream("bookmark.pdf"));
        PDDocumentOutline pdo = pdfWithBookmarks.getDocumentCatalog().getDocumentOutline();
        printBookmark(pdfWithBookmarks, pdo, "");
        pdfWithBookmarks.close();
 }
 
//递归获取书签
 public void printBookmark(PDDocument pd, PDOutlineNode bookmark, String indentation) throws IOException{
        PDOutlineItem current = bookmark.getFirstChild();
        while (current != null) {
            PDPage currentPage = current.findDestinationPage(pd);
            // 获取书签对应对的页码
            Integer pageNumber = pd.getDocumentCatalog().getPages().indexOf(currentPage) + 1;

            System.out.println(indentation + current.getTitle() + "----------------" + pageNumber);
            printBookmark(pd, current, indentation + "    ");
            current = current.getNextSibling();
        }
 }
```

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值