Skip to content

Instantly share code, notes, and snippets.

@eoguvo
Created July 24, 2024 11:49
Show Gist options
  • Save eoguvo/7d4ac9f2c154b59e79e4b7583e217dd8 to your computer and use it in GitHub Desktop.
Save eoguvo/7d4ac9f2c154b59e79e4b7583e217dd8 to your computer and use it in GitHub Desktop.
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