컴포넌트만 예쁘게 인쇄할 수 있는 라이브러리~
실버채가 썼던 것이 생각나서 써보았다.
yarn add react-to-print
설치하고 사용할 컴포넌트에서
import ReactToPrint from "react-to-print";
import { useRef } from "react";
...
const componentRef = useRef(null);
... // HTML 부분
<ReactToPrint
trigger={() => <S.Button>프린트</S.Button>}
content={() => componentRef.current}
/>
ref 하나 선언하고 ,
프린트 버튼을 만들 부분에서 <ReactToPrint />를 가져온다!
이 부분이 바로 버튼이 되는데, trigger 안에 버튼을 그대로 넣어주면 된다. (지금 나는 emotion을 사용해 커스텀한 버튼을 가져온 것)
content엔 위에서 쓴 ref를 적어준다.
<div ref={componentRef}>
(인쇄할 컴포넌트)
</div>
컴포넌트가 여러개라서 div 하나로 묶은 뒤 거기에 ref를 걸었다.
컴포넌트에 바로 ref를 걸어도 된다!
인쇄할 컴포넌트에 ref 걸면 끝
이제 저 위에서 만든 버튼을 누르면 인쇄 창이 뿅 뜬다.

여기 나오는 화면의 사이즈나 마진 등은 css로 조절할 수 있다.
근데 margin이 있으니까 URL이랑 날짜 등이 나온다 -ㅅ-
// npm react-to-print에서 퍼옴
@media all {
.page-break {
display: none;
}
}
@media print {
html, body {
height: initial !important;
overflow: initial !important;
-webkit-print-color-adjust: exact;
}
}
@media print {
.page-break {
margin-top: 1rem;
display: block;
page-break-before: auto;
}
}
@page {
size: auto;
margin: 20mm;
}
이건 react-to-print에서 가져온건데 이렇게 하면 마진때문인지 URL이랑 생겨서... 참고만했다.
@page {
size: auto;
margin: 10mm;
}
@media print {
@page {
margin-top: 0;
margin-bottom: 0;
}
body {
padding-top: 72px;
padding-bottom: 72px;
}
}
이렇게 쓰니 여백은 생기되 URL, 날짜는 뜨지 않는다.
+++ 0919
onClick이벤트를 버튼에 붙이면 적용이 안된다!!!
<ReactToPrint
trigger={() => <S.Button onClick={printFunc}>프린트</S.Button>} // 여기 onClick적용이 안됨
content={() => componentRef.current}
onAfterPrint={printFunc} // 이렇게 붙여줘야한다.
/>
onAfterPrint에 붙여줬더니 잘 된다^_^ (프린트 이벤트 후에 작동한다)
Name Type Description
bodyClass? | string | One or more class names to pass to the print window, separated by spaces |
content | function | A function that returns a component reference value. The content of this reference value is then used for print |
copyStyles? | boolean | Copy all <style> and <link type="stylesheet" /> tags from <head> inside the parent window into the print window. (default: true) |
documentTitle? | string | Set the title for printing when saving as a file |
fonts? | { family: string, source: string }[] | You may optionally provide a list of fonts which will be loaded into the printing iframe. This is useful if you are using custom fonts |
onAfterPrint? | function | Callback function that triggers after the print dialog is closed regardless of if the user selected to print or cancel |
onBeforeGetContent? | function | Callback function that triggers before the library gathers the page's content. Either returns void or a Promise. This can be used to change the content on the page before printing |
onBeforePrint? | function | Callback function that triggers before print. Either returns void or a Promise. Note: this function is run immediately prior to printing, but after the page's content has been gathered. To modify content before printing, use onBeforeGetContent instead |
onPrintError? | function | Callback function (signature: `function(errorLocation: 'onBeforePrint' |
pageStyle? | string or function | We set some basic styles to help improve page printing. Use this to override them and provide your own. If given as a function it must return a string |
print? | function | If passed, this function will be used instead of window.print to print the content. This function is passed the HTMLIFrameElement which is the iframe used internally to gather content for printing. When finished, this function must return a Promise. Use this to print in non-browser environments such as Electron |
removeAfterPrint? | boolean | Remove the print iframe after action. Defaults to false |
suppressErrors? | boolean | When passed, prevents console logging of errors |
trigger? | function | A function that returns a React Component or Element. Note: under the hood, we inject a custom onClick prop into the returned Component/Element. As such, do not provide an onClick prop to the root node returned by trigger, as it will be overwritten |
nonce? | string | Set the nonce attribute for whitelisting script and style -elements for CSP (content security policy) |
https://www.npmjs.com/package/react-to-print
react-to-print
Print React components in the browser. Latest version: 2.14.7, last published: 5 months ago. Start using react-to-print in your project by running `npm i react-to-print`. There are 185 other projects in the npm registry using react-to-print.
www.npmjs.com
https://www.geeksforgeeks.org/how-to-remove-url-from-printing-the-page/
How to Remove URL from Printing the Page ? - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
두목 코드가 짱짱 도움이 됐다! 너무 고마워... ㅎㅎ

'프론트엔드✏️ > 개인공부' 카테고리의 다른 글
[react-query] QueryClient, - 작성 중 (0) | 2022.09.20 |
---|---|
useEffect vs useLayoutEffect (1) | 2022.09.19 |
[react-query, ] invalidateQueries, 에러 박스 (1) | 2022.09.16 |
[react-query] 검색 기능 (0) | 2022.09.15 |
[react-csv] react 엑셀 파일로 내보내기 (0) | 2022.09.07 |