Skip to content

Multiple canvas contexts are created unnecessarily instead of reusing existing contexts during HTML-to-PDF conversion #3900

@Ruthwik000

Description

@Ruthwik000

Problem :
When jsPDF converts HTML to PDF, it creates a brand-new and drawing context for every element (images, divs, table rows). Each canvas can use several megabytes of memory. As you process more elements, memory usage spikes and the browser slows down or crashes.

Solution :
Reuse one (or a few) canvases instead of making new ones.
Create a Canvas Pool
Keep a Map where the key is width×height and the value is a single of that size.
Get & Reset
Before rendering each element, request a canvas from the pool.
Call ctx.clearRect(0,0,w,h) to wipe old content.
Render & Add to PDF
Render your element onto the reused canvas.
Convert canvas.toDataURL() and call pdf.addImage(...).
Cleanup
After pdf.save(), set each canvas’s width and height to 0 and clear the pool so memory is released immediately.

Why It Works :
Memory: One canvas reused instead of dozens—cuts memory by ~90%.
Speed: Avoids expensive canvas creation—PDF builds ~20–30% faster.
Stability: Prevents crashes on large or image-heavy PDFs.

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