이전 회사에서 작업 시 , 특정 화면 혹은 특정 모달내의 화면을 PDF로 다운받는 기능을 구현한 경우가 있다.
난 해당 기능은 jsPDF라이브러리와 html2canvas라이브러리로 간단히 구현했다.
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";
// 다운받기 원하는 엘리먼트에 id를 지정해준다.
export default function onPdfDownload(
rootElementId: any,
downloadFileName: any
) {
const input = document.getElementById(rootElementId);
if (input)
html2canvas(input).then((canvas) => {
const imgData = canvas.toDataURL("image/png");
const pdf = new jsPDF("p", "mm");
const imgWidth = 210;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
const pageHeight = 295;
let heightLeft = imgHeight;
let position = 0;
heightLeft -= pageHeight;
pdf.addImage(imgData, "JPEG", 0, 10, imgWidth, imgHeight);
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
pdf.addPage();
pdf.addImage(imgData, "JPEG", 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
pdf.save(`${downloadFileName}.pdf`);
});
}
rootElementId는 PDF로 다운 받을 엘리먼트의 id이며,
downloadFileName는 다운받는 파일 이름이다.