Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The doc.image() method must scale image by 72/96 to automatically convert pixels to points. #1266

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 15 additions & 12 deletions lib/mixins/images.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
41 changes: 41 additions & 0 deletions tests/unit/image.spec.js
Original file line number Diff line number Diff line change
@@ -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'
]);
});

});