11/**
22 * https://github.com/mozilla/pdf.js/blob/3b94e9fdce616a9b4899800559cbca15169acca6/examples/node/pdf2png/pdf2png.mjs
33 */
4- import * as Canvas from 'canvas'
54import { readFileSync } from 'node:fs'
65import { dirname , join } from 'node:path'
7- import { getDocument } from 'pdfjs-dist'
6+ import { getDocument } from 'pdfjs-dist/legacy/build/pdf.mjs '
87
9- const PDFJS_DIR = dirname ( require . resolve ( 'pdfjs-dist' ) )
10- const C_MAP_URL = join ( PDFJS_DIR , '../cmaps/' )
11-
12- // Where the standard fonts are located.
13- const STANDARD_FONT_DATA_URL = join ( PDFJS_DIR , '../standard_fonts/' )
8+ const PDFJS_DIR = join ( dirname ( require . resolve ( 'pdfjs-dist' ) ) , '..' )
149
1510export async function pdfToPng (
1611 pdf : string | Buffer
1712) : Promise < Buffer [ ] > {
13+
1814 // Load PDF
1915 const data = new Uint8Array ( Buffer . isBuffer ( pdf ) ? pdf : readFileSync ( pdf ) )
2016 const loadingTask = getDocument ( {
2117 data,
22- cMapUrl : C_MAP_URL ,
23- cMapPacked : true ,
24- standardFontDataUrl : STANDARD_FONT_DATA_URL
18+ // Where the standard fonts are located.
19+ standardFontDataUrl : join ( PDFJS_DIR , 'standard_fonts/' ) ,
20+ // Some PDFs need external cmaps.
21+ cMapUrl : join ( PDFJS_DIR , 'cmaps/' ) ,
22+ cMapPacked : true
2523 } )
2624
2725 const pdfDocument = await loadingTask . promise
@@ -31,18 +29,19 @@ export async function pdfToPng(
3129 const images : Buffer [ ] = [ ]
3230 for ( let page = 1 ; page <= numPages ; page += 1 ) {
3331 const pdfPage = await pdfDocument . getPage ( page )
32+ const canvasFactory = pdfDocument . canvasFactory
3433
3534 const viewport = pdfPage . getViewport ( { scale : 1.0 } )
36- const canvasAndContext = Canvas . createCanvas ( viewport . width , viewport . height )
35+ // @ts -expect-error unknown method on Object
36+ const canvasAndContext = canvasFactory . create ( viewport . width , viewport . height )
3737
3838 await pdfPage . render ( {
39- canvasContext : canvasAndContext . getContext ( '2d' ) as never ,
39+ canvasContext : canvasAndContext . context ,
4040 viewport
4141 } ) . promise
4242
43+ images . push ( canvasAndContext . canvas . toBuffer ( 'image/png' ) )
4344 pdfPage . cleanup ( )
44-
45- images . push ( canvasAndContext . toBuffer ( 'image/png' ) )
4645 }
4746
4847 return images
0 commit comments