如何使用pdfmake制作目录?

时间:2016-04-12 15:41:15

标签: javascript pdfmake

是否可以使用pdfmake制作内容表(TOC)?该库将为我生成PDF,但我不知道某个对象将在哪个页面上呈现。当然这取决于页面大小,方向等。一些内容将流向下一页。我看不出如何提前计算一章的结尾。

考虑这个文件定义:

var dd = {
    footer: function(currentPage, pageCount) { return currentPage.toString() + ' of ' + pageCount; },
    content: [
        'Table of contents\n\n',
        'Chapter 1 ....... ?',
        'Chapter 2 ....... ?',
        'Chapter 3 ....... ?',
        'Chapter 4 ....... ?',
        {
            text: '',
            pageBreak: 'after'
        },
        {
            text: 'Chapter 1: is on page 2',
            pageBreak: 'after'
        },
        {
            stack: [
                'Chapter 2: is on page 3\n',
                'A LOT OF ROWS 2\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n',
                'A LOT OF ROWS 2\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n',
                'A LOT OF ROWS 2\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n',
                'A LOT OF ROWS 2\nWill go to the next page if this line contains a lot of text. Will go to the next page if this line contains a lot of text. Will go to the next page if this line contains a lot of text.'
                ],
            pageBreak: 'after'
        },
        {
            text: 'chapter 3: is on page 5',
            pageBreak: 'after'
        },
        {
            text: 'chapter 4: is on page 6'
        },
  ]
}

最容易测试的是在操场上粘贴这个dd对象:http://pdfmake.org/playground.html

有关如何创建TOC的任何想法?

1 个答案:

答案 0 :(得分:4)

虽然直到最近才支持此功能,但现在可以执行

var docDefinition = {
  content: [
    {
      toc: {
        // id: 'mainToc'  // optional
        title: {text: 'INDEX', style: 'header'}
      }
    },
    {
      text: 'This is a header',
      style: 'header',
      tocItem: true, // or tocItem: 'mainToc' if is used id in toc
      // or tocItem: ['mainToc', 'subToc'] for multiple tocs
    }
  ]
}

来源:https://github.com/bpampuch/pdfmake#table-of-contents


请注意,这在最近的0.1.28版本中尚未公布。但我想它会包含在下一个中,同时您可以轻松地从源代码构建:

git clone https://github.com/bpampuch/pdfmake.git
cd pdfmake
npm install # or: yarn
git submodule update --init  libs/FileSaver.js
npm run build # or: yarn run build

来源:https://github.com/bpampuch/pdfmake#building-from-sources


只要您至少有一个tocItem,我就可以确认上述ToC示例在该情况下是有效的。由于空的ToC表,零tocItemtoc当前将抛出异常。