EagleBear2002 的博客

这里必须根绝一切犹豫,这里任何怯懦都无济于事

在 Acrobat 中生成 PDF 的目录页

TODO: 填坑

文档级 JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
var levelCount = [0, 0, 0, 0, 0, 0, 0]; // 用于记录各级标题的计数

function PrintBookmarks(bm, nLevel) {
if (nLevel != 0) { // don't print the root
bmReport.absIndent = bmTab * (nLevel - 1);
bm.execute();

// 添加层级序号,从二级标题开始编号
var title = getNumberedTitle(bm.name, nLevel);

var pageNum = (bm.doc.pageNum + 1).toString();

// 计算标题和页码的字符长度,包括中文字符
var titleLen = countCharacters(title);
var pageNumLen = countCharacters(pageNum);

// var rptnum = Math.floor((totalWidth - titleWidth - pageNumWidth) / measureTextWidth('.'));
var dots = '.'.repeat(50 - titleLen - pageNumLen); // 总宽度为50,减去标题长度和页码长度,计算出点号的个数
bmReport.writeText(title + dots + pageNum, { align: "right" });
// bmReport.vspace(12); // 增大行间距
}
if (bm.children != null)
for (var i = 0; i < bm.children.length; i++)
PrintBookmarks(bm.children[i], nLevel + 1);
}

// 获取层级序号,从二级标题开始编号
function getNumberedTitle(title, nLevel) {
if (nLevel === 1) {
return title;
}

levelCount[nLevel]++; // 当前层级计数增加

// 生成层级序号
var numberedTitle = "";
for (var i = 2; i <= nLevel; i++) {
numberedTitle += levelCount[i] + ".";
}

// 添加标题内容
numberedTitle += " " + title;
return numberedTitle;
}

// 计算字符长度,包括中文字符
function countCharacters(str) {
var count = 0;
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 127) {
count += 2; // 中文字符占两个字符长度
} else {
count += 1;
}
}
return count;
}

bmTab = 15; // 调整缩进的距离,使目录更美观
bmReport = new Report();
bmReport.size = 2;
bmReport.writeText(this.title);
bmReport.writeText(" ");
bmReport.size = 1.5;
bmReport.writeText("目录");
bmReport.writeText(" ");
bmReport.size = 1;
PrintBookmarks(this.bookmarkRoot, 0);
global.bmRep = bmReport; // make global

// 使用try-catch块确保目录页的生成不会出错
global.wrtDoc = app.setInterval(
'try {' +
' reportDoc = global.bmRep.open("Listing of Bookmarks");' +
' console.println("Executed Report.open");' +
' app.clearInterval(global.wrtDoc);' +
' delete global.wrtDoc;' +
' console.println("Executed App.clearInterval");' +
' reportDoc.info.title = "Bookmark Listings";' +
' reportDoc.info.Author = "List Bookmark Sequence";' +
'} catch (e) {console.println("Waiting...: " + e);}', 100);