pdf-lib-read-3-images-from-fs: 695.754ms
jspdf-read-3-images-from-fs: 2.687s
import { jsPDF } from "jspdf"; | |
import Sharp from "sharp"; | |
import fs from "fs"; | |
import fsp from "fs/promises"; | |
import { PDFDocument } from 'pdf-lib'; | |
const testDir = "./test-input" | |
const testImages = ["landscape-1.jpeg", "landscape-zoomed-1.jpeg", "portrait-bw-1.jpeg"] | |
async function testPdflib(num:number){ | |
console.time("pdf-lib-read-3-images-from-fs") | |
for (let t = 0; t < num; t+=3) { | |
await Promise.all(testImages.map(async (image, idx) => { | |
const file = fs.readFileSync(`${testDir}/${image}`, { encoding: 'base64' }) | |
const doc = await PDFDocument.create(); | |
const imagee = await doc.embedJpg(file); | |
const page = doc.addPage([imagee.width, imagee.height]); | |
page.drawImage(imagee, { | |
x: 0, | |
y: 0, | |
width: imagee.width, | |
height: imagee.height, | |
}); | |
const pdfBytes = await doc.save(); | |
await fsp.writeFile(`test-output/output-${t + idx}.pdf`, pdfBytes); | |
})) | |
} | |
console.timeEnd("pdf-lib-read-3-images-from-fs") | |
} | |
async function testJspdf(num : number){ | |
console.time("jspdf-read-3-images-from-fs") | |
for (let t = 0; t < num; t+=3) { | |
await Promise.all(testImages.map(async (image, idx) => { | |
const img = Sharp(`${testDir}/${image}`) | |
const file = await (await img.toBuffer()).toString('base64') | |
const imgHeight = await img.metadata().then((meta) => meta.height) || 500 | |
const imgWidth = await img.metadata().then((meta) => meta.width) || 500 | |
const doc = new jsPDF({ | |
unit: "px", | |
format: [+imgWidth, +imgHeight] | |
}) | |
// image to pdf without changing pdf dimensions | |
doc.addImage(file, 'JPG', 0, 0,doc.internal.pageSize.getHeight(), doc.internal.pageSize.getWidth()) | |
const pdfBytes = doc.output() | |
await fsp.writeFile(`test-output/output-${t + idx}.pdf`, pdfBytes); | |
})) | |
} | |
console.timeEnd("jspdf-read-3-images-from-fs") | |
} | |
async function main() { | |
testJspdf(100) | |
testPdflib(100) | |
} | |
main() | |
time take to produce 100 pdfs