This repository has been archived by the owner on Aug 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
54 lines (47 loc) · 2 KB
/
index.js
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
const hummus = require('hummus')
const writeOutline = require('./src/writeOutline')
const addTOCPages = require('./src/addTOCPages')
const countPages = require('./src/countPages')
const countOutline = require('./src/countOutline')
const getTOCText = require('./src/getTOCText')
const translatePageNumbers = require('./src/translatePageNumbers')
const writeLinks = require('./src/writeLinks')
module.exports = (inFile, outFile, origOutline, font = null) => {
// Start new PDF to contain TOC pages only
const newPDFWriter = hummus.createWriter(outFile)
const outlineSize = countOutline(origOutline)
const howManyPages = countPages(outlineSize)
const tocText = getTOCText(origOutline, howManyPages)
const tocPageSize = addTOCPages(newPDFWriter, tocText, font)
newPDFWriter.appendPDFPagesFromPDF(inFile)
newPDFWriter.end()
// End TOC PDF
// Start final PDF containing bookmarks as well as TOC pages
const mergingWriter = hummus.createWriterToModify(outFile)
const ctx = mergingWriter.getObjectsContext()
const events = mergingWriter.getEvents()
const copyCtx = mergingWriter.createPDFCopyingContextForModifiedFile()
const parser = copyCtx.getSourceDocumentParser()
// translate numbers from index to PDF object IDs
const translatedOutline = origOutline.map(childOutline => translatePageNumbers(parser, childOutline, howManyPages))
// write bookmarks
const outline = writeOutline(ctx, translatedOutline)
// create link annotations for TOC to locations in file
for (let i = 0; i < howManyPages; i++) {
writeLinks(ctx, copyCtx, parser, i, tocText, howManyPages, tocPageSize)
}
// before writer closes, add outline to PDF
events.on('OnCatalogWrite', e => {
let d = e.catalogDictionaryContext
if (outline !== null) {
d.writeKey('Outlines')
.writeObjectReferenceValue(outline)
.writeKey('PageMode')
.writeNameValue('UseOutlines')
}
})
// force update, in case it is necessary
mergingWriter.requireCatalogUpdate()
mergingWriter.end()
// End Final PDF
}