본문 바로가기
개발/React

이미지 화면 동적으로 프린트하기 window.print()

by yo.na 2024. 7. 21.

✔ 시작

이미지파일 위에 동적으로 사용자 정보를 출력하려고 한다.

새 창으로 프린트 할 화면을 띄우고, 그 화면을 프린트하는 방법을 구현하기로 선택했다.

 

환경

React,

Next,

Typescript

✔ 과정

export default function Print({
  정보1
  imageUrl,
}: TProps){

  const handlePrint = (): void => {
    const printWindow = window.open('', '_blank');

    if (printWindow) {
      const htmlContent = `
      <html>
      <head>
        <style>
        // 이 영역에 css 스타일 추가
        @page { size: A4 landscape; margin: 0; }
          @media print {
          }
        </style>
      </head>
      <body>
        <div>
          <div>
            <span>${정보1}</span>
          </div>
          <div>
            <img
              id="print-image"
              src=${imageUrl}
              alt="logo"
            />
          </div>
        </div>
      </body>
    </html>
    `;
      printWindow.document.open();
      printWindow.document.write(htmlContent);
      printWindow.document.close();

      // 이미지가 로드될 때까지 기다리고 프린트
      const img = printWindow.document.getElementById('print-image');
      if (img) {
        img.onload = function () {
          printWindow.print();
          printWindow.close();
        };
      }
    }
  };

  return (
    <>
      <button onClick={handlePrint}>
        프린트
      </button>
    </>
  );
}

 

1. Print 컴포넌트에 동적으로 그려야 할 정보들을 Props 로 넘겨준다.

2. Props 로 받아온 이미지주소를 img 태그 src에 넣어주고 출력할 화면을 htmlContent에 넣는다.

3. 이미지 위에 받아온 정보들이 원하는 위치에 나오도록 Css 로 위치를 잡아준다 (style 태그).

4. 새 창을 띄워서 해당 창에 원하는 화면을 그리고, 그 창에서 프린트를 해준다.

 

✔ 결과

원하는 이미지에 사용자의 이름과 날짜를 출력하는 기능 구현 완료!

프린트 버튼을 누르면 새 창이 뜨고, 아래와 같이 실제 인쇄 창이 뜬다.