Automattic / Automattic/node-canvas

Image is not embedded in PDF when using target size parameters in drawImage()

Open
#1,462 3 comments 7 reactions 0 assignees View on GitHub
Bug
Dominant language
JavaScript
Stars
10.7k
Forks
1.2k
Avg merge
4d 8h
Merged PRs (30d)
1

Description

## Issue

When rendering an image into a PDF and specifying the target size parameters in `drawImage` then the original image is not embedded. Instead a new image with the target size in pixels is created and embedded into the PDF.

So when rendering a 2048x2048 pixel image into a 50x50 PDF with `drawImage(image, 0, 0, 50, 50)` then the PDF contains an image with a pixel size of 50x50. So print quality is very bad.

I think this is wrong because the target width and height defines the area where to place the image in the PDF (So it uses PDF size unit, not pixels). It does not mean that the image must be scaled down to this size in pixels.

## Steps to Reproduce

```js
const fs = require("fs");
const { Canvas, Image } = require("canvas");

const img = new Image();
img.dataMode = Image.MODE_MIME | Image.MODE_IMAGE;
img.src = "test.jpeg"; // Some 2048x2048 image

const canvas = new Canvas(50, 50, "pdf");
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, 50, 50);

const buffer = canvas.toBuffer();
fs.writeFileSync("test.pdf", buffer);
```

## Your Environment
* canvas@2.5.0
* Node v10.15.2 on Debian Linux 10

## Expected result

I expect a PDF displaying the original test.jpeg which has to be embedded into the PDF.

## Actual result

The image is scaled down to 50x50 pixels and this new image is embedded into the PDF instead.

## Workaround

The problem only occurs when the target size parameters are specified. So it works when I remove them and use a scale transformation instead:

```js
ctx.save();
ctx.scale(50 / img.width, 50 / img.height);
ctx.drawImage(img, 0, 0);
ctx.restore();
```

I guess this is something that node-canvas could do automatically?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.