Html2PDF 비율 수정

쏘뽀끼·2024년 12월 24일
0

react

목록 보기
21/25

기능 구현을 하면서 html2PDF 라이브러리를 사용해서 pdf다운로드 하는 법을 구현했다.

사용방법

  1. 설치하기 🔍
npm install html2pdf.js

위 명령어를 터미널에 입력해서 다운로드 한다.




  1. 사용하기 🍥

사용하고자 하는 컴포넌트에서 사용해주면 된다.

(예시)

import React, {useRef} from 'react';
import html2pdf from 'html2pdf.js';

const PdfGenerator = ()=>{

//PDF로 변환할 영역을 참조하기 위한 ref 
const contentRef = useRef();


const handleDownload = ()=>{
const element = contentRef.current;// 변환할 요소를 ref에서 가져오기
const options = {
margin:1,
filename: 'example.pdf',
image: {type: 'jpeg', quality: 0,98},
html2canvas: {scale:2},
jsPDF: {unit: 'in', format: 'letter', orientation: 'portrait'},
};

 html2pdf().set(options).from(element).save();
 };
 
 return (
 <div>
  <div ref={contentRef} style={{padding: '20px', background: '#f9f9f9'}}>
   <h1> PDF Example </h1>
   <p> This content will be converted to a PDF. </button>
  </div>
  );
};



이렇게 사용하면 생각보다 간단하게 pdf다운로드 기능을 구현할 수 있다.

그런데 내가 겪은 문제점은 비율을 조절하는 것이었다.
페이지의 내용이 짤리거나 조절을 하더라도 원하는 데로 되지 않았다.
a4용지 사이즈에 새로방향으로 원하는 내용이 알맞은 비율로 들어가야만 했다.
margin값이나 html요소에 css style을 지정해도 원하는 데로 되지 않았다.

🍯 해결방법

  1. A4 비율 설정
const a4Width = 210;//a4너비 (mm)
const a4Height = 297 //a4 높이(mm)
const a4Scale = a4Height/a4Width;//비율 계산
  1. pdf의 너비 및 높이 지정
    contentRef.current.clientWidth로 선택한 HTML 요소의 실제 너비를 가져온다.
    이를 mm단위로 변환 (1px = 0.264583mm)하고 비율을 반영해 PDF크기를 설정한다.
const w = contnetRef.current.clientWidth * 0.264583; // px -> mm 변환

이 값을 A4의 비율에 맞춰 높이를 설정한다.

const h = w* a4Scale;// 높이 계산



최종코드

import React, { useRef } from 'react';
import html2pdf from 'html2pdf.js';

const PdfGenerator = () => {
  const contentRef = useRef<HTMLDivElement>(null);

  const downloadPDF = () => {
    setTimeout(() => {
      if (contentRef.current) {
        const a4Width = 210; // A4 너비 (mm)
        const a4Height = 297; // A4 높이 (mm)
        const a4Scale = a4Height / a4Width;
        const scaleFactor = 0.8; // PDF 크기 비율 (원하는 대로 조정 가능)
        const w = contentRef.current.clientWidth * 0.264583 * scaleFactor; // px -> mm 변환 및 비율 적용
        const h = w * a4Scale; // 높이 계산

        const opt = {
          margin: [3, 5, 3, 5],
          filename: 'quotation.pdf',
          pagebreak: { mode: 'avoid-all' },
          html2canvas: { scale: 3, useCORS: true, dpi: 300, letterRendering: true, allowTaint: false },
          image: { type: 'jpeg', quality: 0.98 },
          jsPDF: { unit: 'mm', format: [w, h], orientation: 'portrait' },
        };

        html2pdf().from(contentRef.current).set(opt).save();
      }
    }, 100);
  };

  return (
    <div>
      <div ref={contentRef} style={{ padding: '20px', background: '#f4f4f4', color: '#333' }}>
        <h1>PDF Example</h1>
        <p>This content will be converted to a PDF.</p>
      </div>
      <button onClick={downloadPDF}>Download PDF</button>
    </div>
  );
};

export default PdfGenerator;

이렇게 수정했더니 원하는 비율로 알맞게 pdf를 다운로드 할 수 있었다!

0개의 댓글