From 07e4f551522eb5e55fd2c13dc851f435d687c3c7 Mon Sep 17 00:00:00 2001 From: Olli Etuaho Date: Tue, 23 Jan 2024 12:54:52 +0200 Subject: [PATCH] Prevent adding identity transforms to the document This makes the resulting PDF files smaller. It's cumbersome to filter out all commands that could result in identity transforms in code that's using PDFKit, so it makes sense to have the check in the transform() function. --- CHANGELOG.md | 1 + lib/mixins/vector.js | 4 ++++ tests/unit/vector.spec.js | 22 ++++++++++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18884dc3f..2700583a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - Add subset for PDF/UA - Fix for line breaks in list items (#1486) - Fix for soft hyphen not being replaced by visible hyphen if necessary (#457) +- Optimize output files by ignoring identity transforms ### [v0.14.0] - 2023-11-09 diff --git a/lib/mixins/vector.js b/lib/mixins/vector.js index 226a0940c..c0426261b 100644 --- a/lib/mixins/vector.js +++ b/lib/mixins/vector.js @@ -289,6 +289,10 @@ export default { transform(m11, m12, m21, m22, dx, dy) { // keep track of the current transformation matrix + if (m11 === 1 && m12 === 0 && m21 === 0 && m22 === 1 && dx === 0 && dy === 0) { + // Ignore identity transforms + return this; + } const m = this._ctm; const [m0, m1, m2, m3, m4, m5] = m; m[0] = m0 * m11 + m2 * m12; diff --git a/tests/unit/vector.spec.js b/tests/unit/vector.spec.js index d97aa4d82..1d777603a 100644 --- a/tests/unit/vector.spec.js +++ b/tests/unit/vector.spec.js @@ -164,4 +164,26 @@ describe('Vector Graphics', () => { }); }); }); + + describe('translate', () => { + test('identity transform is ignored', () => { + const docData = logData(document); + const vectorStream = Buffer.from(`1 0 0 -1 0 792 cm\n1 0 0 1 0 0 cm\n`, 'binary'); + + document + .translate(0, 0); + document.end(); + + expect(docData).not.toContainChunk([ + `5 0 obj`, + `<< +/Length 33 +>>`, + `stream`, + vectorStream, + `\nendstream`, + `endobj` + ]); + }); + }); });