React React-to-Print에 대해 알아봅니다.
참고) https://www.npmjs.com/package/react-to-print
npm install react-to-print
import { useRef } from "react";
import { useReactToPrint } from "react-to-print";
// 출력할 컴포넌트
const PrintView = () => {
// 출력 대상 요소를 가리킬 ref
const contentRef = useRef<HTMLDivElement>(null);
// 프린트 기능 hook
const reactToPrintFn = useReactToPrint({
contentRef, // ref로 가리킨 요소를 출력
documentTitle: "견적서", // 문서 제목
});
return (
<div>
<MiniBtn
text="견적서 출력하기"
onClick={reactToPrintFn}
/>
{/* 출력 대상 영역 */}
<div ref={contentRef}>
<QuotationDocumentView />
</div>
</div>
);
};
export default PrintView;
: 프린트 전용 css를 따로 만들 수 있다!
print:
접두사를 사용해 프린트 전용 스타일 적용 가능.<div ref={contentRef} className="print:p-8">
<QuotationDocumentView />
</div>
/* global.css */
/* 프린트 시 문서 스타일 설정 */
@media print {
/* 폰트 */
* {
font-family:
"Pretendard"
}
/* placeholder 숨기기 */
::placeholder {
color: transparent !important;
}
::-webkit-input-placeholder {
color: transparent !important;
}
:-ms-input-placeholder {
color: transparent !important;
}
::-ms-input-placeholder {
color: transparent !important;
}
/* 페이지 나눔 설정 */
p {
page-break-inside: avoid; /* 요소 내부에서 페이지 나눔 방지 */
break-inside: avoid;
}
tr {
page-break-inside: avoid; /* 테이블 행이 잘리지 않도록 */
break-inside: avoid;
}
/* 페이지 여백 설정 */
@page {
margin: 32px;
}
}
=> 높이가 내용에 맞게 자동으로 늘어나지 않음!!! textarea의 실제 내용을 모두 출력할 수 없음!!!
프린트할 때 <textarea>를 일반 텍스트 블록(div, pre 등)으로 교체해서 출력
<div className="flex flex-col gap-3">
<h3 className="Heading-3">메모</h3>
{/* 입력용 textarea - 화면에서만 표시 */}
<textarea
placeholder="메모를 입력하세요."
value={value}
onChange={(e) => setValue(e.target.value)}
className="w-full min-h-50 print:hidden"
/>
{/* 프린트용 div - 프린트에서만 표시 */}
<div className="textarea hidden print:block whitespace-pre-wrap w-full min-h-50">
{value}
</div>
</div>
whitespace-pre-wrap
: 줄바꿈 및 공백 유지.