본문 바로가기
React.js

react PDF 다운로드

by whoyoung90 2023. 10. 11.
반응형

> @react-pdf/renderer

React 진영에서 PDF를 편하게 만들어주는 라이브러리라는 점이 장점이다.

최근 업데이트도 활발히 진행되고 있는 라이브러리이지만, 미리보기 구현이 아쉬웠다.

 

다운로드 이전에 미리보기 화면이 해당 내용을 순수하게 보여주는게 아니라,

라이브러리에서 특정 view를 고정시켜 두었기 때문에 production으로 사용하기에 고민되었다.

순수 다운로드 기능으로만 사용하기에는 아주 적합한 라이브러리 🤔

 

> html2canvas+ jspdf

현재 보이는 화면에 대한 스크린샷을 찍어서 이를 pdf로 변환해주는 방식이다.

How to generate PDF from HTML in React / Node.js app

 

How to generate PDF from HTML in React / Node.js app

Explore the pros and cons of generating PDFs from HTML, from simple CSS print rules to using libraries like html2canvas, jsPDF, and Puppeteer.

startup-house.com

html ⇒ html2canvas ⇒ canvas에 html의 스냅샷 추가 ⇒ jspdf ⇒ pdf

 

기존 Vue 프로젝트에서 PDF 다운로드 관련 라이브러리로 html2pdf.js를 사용하였는데,

결국 이 라이브러리도 html2canvas, jspdf 두 라이브러리에 의존성을 갖고 만들어진 것으로 확인하였다.

해당 구현을 위한 근원적인(?) 라이브러리답게 높은 사용량이 아주 마음에 들었다!

 

미리보기 상태에서 해당 화면을 html2canvas 로 canvas로 변환한 뒤, 이미지 형태로 추출한다.

해당 이미지를 jspdf 를 이용하여 pdf 문서에 페이지별로 적당하게 잘라서 이미지를 추가하고 이를 저장하거나 blob 형태로 저장할수도 있다고 한다.

 

function Container() {
  return (
    <>
      <article id="pdf-download-id">
        pdf 내용
      </article>
      <PdfDownloader rootElementId="pdf-download-id" fileName="파일이름" />
    </>
  )
}
// 라이브러리 로직을 독립된 컴포넌트로 분리
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";

type fileType = {
  rootElementId: string;
  fileName: string;
};

function PdfDownloader({ rootElementId, fileName }: fileType) {
  const downloadPdfDocument = async () => {
    const input = document.getElementById(rootElementId);
    try {
      const canvas = await html2canvas(input as HTMLElement, { scale: 1.5 }); // 해상도 scale
      const imgData = canvas.toDataURL("image/png");

      // 마지막 인자가 compressPDF
      const pdf = new jsPDF("p", "mm", "a4", true);
      const imgWidth = 210;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;

      pdf.addImage(imgData, "JPEG", 0, 0, imgWidth, imgHeight);
      pdf.save(`${fileName}.pdf`);
    } catch (err) {
      alert("다운로드 실패");
    }
  };
  return <button onClick={downloadPdfDocument}>PDF 내려받기</button>;
}
export default PdfDownloader;

 

[참조 URL]

https://dev.to/mohammadfaisal/download-html-as-a-pdf-in-react-4g7a?utm_source=oneoneone

https://velog.io/@juno7803/html-to-pdf

https://velog.io/@yung315/React-PDF%EB%8B%A4%EC%9A%B4

https://devmemory.tistory.com/98

반응형

댓글