Created
July 24, 2024 11:49
-
-
Save eoguvo/7d4ac9f2c154b59e79e4b7583e217dd8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jsPDF from "jspdf"; | |
import html2canvas from "html2canvas"; | |
import { ServicePdfComponentsImage } from "@core/Services/Pdf/Components"; | |
type ImagesStructure = { | |
id: string; | |
positions: [ | |
{ | |
page: number; | |
x: number; | |
y: number; | |
width: number; | |
height: number; | |
} | |
] | |
}; | |
const ServicePdfHelperImage = function (doc: jsPDF) { | |
const images = {} as Record<string, ImagesStructure>; | |
const push = function ({ id, x, y, width, height }: { id: string, x: number, y: number, width: number, height: number }) { | |
const alreadyExists = id in images; | |
const currentPosition = { | |
page: doc.getCurrentPageInfo().pageNumber, | |
x, | |
y, | |
width, | |
height, | |
}; | |
if (alreadyExists) { | |
images[id].positions.push(currentPosition); | |
return; | |
} | |
images[id] = { | |
id, | |
positions: [currentPosition], | |
}; | |
}; | |
const exec = async function () { | |
const start = performance.now(); | |
const imagesArray = Object.values(images); | |
const promises = imagesArray.map(async function ({ id, positions }) { | |
const element = document.getElementById(id); | |
if (!element) { | |
console.error(`[ServicePdfHelperImage] no target element with ${id}`); | |
return; | |
} | |
const canvasQuality = 1; | |
const canvasFormat = "image/png"; | |
const canvasOptions = { useCORS: true }; | |
const canvasImage = await html2canvas(element, canvasOptions); | |
const canvasImageSource = canvasImage.toDataURL(canvasFormat, canvasQuality); | |
for (const position of positions) { | |
const { x, y, width, height, page } = position; | |
doc.setPage(page); | |
ServicePdfComponentsImage({ | |
doc, | |
id, | |
source: canvasImageSource, | |
format: "PNG", | |
x, | |
y, | |
width, | |
height, | |
}); | |
} | |
}); | |
await Promise.allSettled(promises); | |
console.debug(`${imagesArray.length + 1} Images loaded in ${performance.now() - start} ms`); | |
}; | |
return { | |
push, | |
exec, | |
}; | |
}; | |
export type ServicePdfHelperImageFunction = ReturnType<typeof ServicePdfHelperImage>; | |
export default ServicePdfHelperImage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment