diff --git a/lib/mixins/images.js b/lib/mixins/images.js index 37fb898b..644ba66a 100644 --- a/lib/mixins/images.js +++ b/lib/mixins/images.js @@ -36,24 +36,27 @@ export default { this.page.xobjects[image.label] = image.obj; } - let w = options.width || image.width; - let h = options.height || image.height; + const imageWidth = image.width * 0.75, // scale by 72/ 96 to convert from pixels to points. + imageHeight = image.height * 0.75; + + let w = options.width || imageWidth, + h = options.height || imageHeight; if (options.width && !options.height) { - const wp = w / image.width; - w = image.width * wp; - h = image.height * wp; + const wp = w / imageWidth; + w = imageWidth * wp; + h = imageHeight * wp; } else if (options.height && !options.width) { - const hp = h / image.height; - w = image.width * hp; - h = image.height * hp; + const hp = h / imageHeight; + w = imageWidth * hp; + h = imageHeight * hp; } else if (options.scale) { - w = image.width * options.scale; - h = image.height * options.scale; + w = imageWidth * options.scale; + h = imageHeight * options.scale; } else if (options.fit) { [bw, bh] = options.fit; bp = bw / bh; - ip = image.width / image.height; + ip = imageWidth / imageHeight; if (ip > bp) { w = bw; h = bw / ip; @@ -64,7 +67,7 @@ export default { } else if (options.cover) { [bw, bh] = options.cover; bp = bw / bh; - ip = image.width / image.height; + ip = imageWidth / imageHeight; if (ip > bp) { h = bh; w = bh * ip; diff --git a/tests/unit/image.spec.js b/tests/unit/image.spec.js new file mode 100644 index 00000000..f38e5725 --- /dev/null +++ b/tests/unit/image.spec.js @@ -0,0 +1,41 @@ +import PDFDocument from '../../lib/document'; +import { logData } from './helpers'; + +describe('Image', () => { + let document; + + beforeEach(() => { + document = new PDFDocument({ compress: false }); + }); + + test('The image must be scaled to convert pixels to points', () => { + const docData = logData(document), + image = document.openImage('tests/images/bee.jpg'), + scale = 72 / 96; + + const stream = Buffer.from( + `1 0 0 -1 0 792 cm +q +${image.width * scale} 0 0 -${image.height * scale} 72 372 cm +/I1 Do +Q +`, + 'binary' + ); + + document.image(image); + document.end(); + + expect(docData).toContainChunk([ + '5 0 obj', + `<< +/Length 55 +>>`, + 'stream', + stream, + '\nendstream', + 'endobj' + ]); + }); + +});