From db3be670d4a27ba22e163a17956d009a6aa19343 Mon Sep 17 00:00:00 2001 From: Joost Lubach Date: Tue, 9 Jul 2019 10:18:19 +0200 Subject: [PATCH] Added support for inserting pages --- CHANGELOG.md | 4 ++++ lib/document.js | 47 +++++++++++++++++++++++++++++++++++++++++++++ lib/line_wrapper.js | 2 +- package.json | 2 +- 4 files changed, 53 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9926fc669..56f3a909f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ ### Unreleased - Fix infinite loop when text is positioned after page right margin +### [v0.11.0] - 2019-07-09 [Joost Lubach] + +- Added support for inserting pages + ### [v0.10.0] - 2019-06-06 - Fix links to pages within the document diff --git a/lib/document.js b/lib/document.js index 7143bc244..d37534274 100644 --- a/lib/document.js +++ b/lib/document.js @@ -147,6 +147,53 @@ class PDFDocument extends stream.Readable { return this; } + insertPage(at, options) { + // end the current page if needed + if (options == null) { + ({ options } = this); + } + if (!this.options.bufferPages) { + throw new Error("Cannot insert pages without option 'bufferPages'") + } + + // create a page object + this.page = new PDFPage(this, options); + this._pageBuffer.splice(at, 0, this.page); + + // add the page to the object store + const pages = this._root.data.Pages.data; + pages.Kids.splice(at, 0, this.page.dictionary); + pages.Count++; + + // reset x and y coordinates + this.x = this.page.margins.left; + this.y = this.page.margins.top; + + // flip PDF coordinate system so that the origin is in + // the top left rather than the bottom left + this._ctm = [1, 0, 0, 1, 0, 0]; + this.transform(1, 0, 0, -1, 0, this.page.height); + + this.emit('pageAdded'); + + return this; + } + + addPageAfterThis(options) { + if (!this.options.bufferPages) { + this.addPage(options); + return; + } + + const index = this._pageBuffer.indexOf(this.page); + if (index === -1) { + this.addPage(options); + return; + } + + this.insertPage(index + 1, options); + } + bufferedPageRange() { return { start: this._pageBufferStart, count: this._pageBuffer.length }; } diff --git a/lib/line_wrapper.js b/lib/line_wrapper.js index d37817d71..16598a3c7 100644 --- a/lib/line_wrapper.js +++ b/lib/line_wrapper.js @@ -305,7 +305,7 @@ class LineWrapper extends EventEmitter { return false; } - this.document.addPage(); + this.document.addPageAfterThis(); this.column = 1; this.startY = this.document.page.margins.top; this.maxY = this.document.page.maxY(); diff --git a/package.json b/package.json index 50ad7a1cd..85a8743f4 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "document", "vector" ], - "version": "0.10.0", + "version": "0.11.0", "homepage": "http://pdfkit.org/", "author": { "name": "Devon Govett",