Skip to content

Canvas size is not updated when adding PDF page with different size than initial canvas size #2538

@kayahr

Description

@kayahr

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

Image

Actual output

Image

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions