Skip to content

Instantly share code, notes, and snippets.

@akshatsethi2
Last active December 26, 2022 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akshatsethi2/fe9d42985e000287ce057269ee9bee9d to your computer and use it in GitHub Desktop.
Save akshatsethi2/fe9d42985e000287ce057269ee9bee9d to your computer and use it in GitHub Desktop.
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()

pdf-lib-read-3-images-from-fs: 695.754ms

jspdf-read-3-images-from-fs: 2.687s

@akshatsethi2
Copy link
Author

time take to produce 100 pdfs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment