-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Open
Description
When using node-canvas to create a PDF with different page sizes or orientations (landscape, portrait) then canvas.width and canvas.height is not updated accordingly. It stays at the initial canvas size and does not report the current page size.
Reproduction
import { createCanvas } from "canvas";
import { writeFile } from "node:fs/promises";
function drawCross(ctx) {
const { width, height } = ctx.canvas;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(width, height);
ctx.moveTo(width, 0);
ctx.lineTo(0, height);
ctx.strokeStyle = "#000";
ctx.stroke();
}
// Create PDF with first page in landscape format
const canvas = createCanvas(1024, 768, "pdf");
const ctx = canvas.getContext("2d");
drawCross(ctx);
// Adding new page in portrait format
ctx.addPage(768, 1024);
drawCross(ctx);
await writeFile("test.pdf", canvas.toBuffer());Expected output
Actual output
Second page is wrong because the reported canvas size does not match the currrent page size
Workaround
In node-canvas v2 it was possible to workaround this problem by correcting the canvas size manually after adding the new page:
ctx.addPage(768, 1024);
canvas.width = 768;
canvas.height = 1024;But with node-canvas v3 the PDF is completely reset when changing the width/height.
This workaround seems to work but is quite hacky:
ctx.addPage(768, 1024);
Object.defineProperties(canvas, {
width: { value: 768 },
height: { value: 1024 }
});Environment
- Node 24.10.0
- Canvas 3.2.0
- Debian 13
Metadata
Metadata
Assignees
Labels
No labels