사과먹는중
당근먹는하니
귀엽고 행복해
당근먹는하니
전체 방문자
오늘
어제
  • 분류 전체보기 (274)
    • 다람쥐🐿 (26)
    • C++ 공부빵야 (7)
    • 공부👻 (5)
    • 프론트엔드✏️ (228)
      • 코드캠프 (120)
      • 팀 프로젝트✨ (31)
      • 개인공부 (67)
    • 프론트엔드 - 바닐라js (7)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • typescript
  • React-hook-form
  • 코드캠프
  • 프론트엔드
  • 코딩
  • 팀프로젝트
  • 코딩 부트캠프
  • HTML
  • 팀 프로젝트
  • 배열
  • 리액트
  • graphql
  • emotion
  • 공통 컴포넌트
  • next.js
  • CSS
  • 팀플
  • 회고
  • ssg
  • JS
  • 배포
  • 알고리즘
  • 프로그래머스
  • 자바스크립트
  • javascript
  • javascrpit
  • react
  • refreshtoken
  • 부트캠프
  • algorithm

최근 댓글

최근 글

티스토리

250x250
반응형
hELLO · Designed By 정상우.
당근먹는하니
프론트엔드✏️/개인공부

[react-to-print] 리액트 컴포넌트 프린트하기 💌

[react-to-print] 리액트 컴포넌트 프린트하기 💌
프론트엔드✏️/개인공부

[react-to-print] 리액트 컴포넌트 프린트하기 💌

2022. 9. 16. 16:40
728x90
반응형

 

 컴포넌트만 예쁘게 인쇄할 수 있는 라이브러리~

실버채가 썼던 것이 생각나서 써보았다. 

 

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

 

두목 코드가 짱짱 도움이 됐다! 너무 고마워... ㅎㅎ

728x90
반응형
저작자표시 비영리 동일조건 (새창열림)

'프론트엔드✏️ > 개인공부' 카테고리의 다른 글

[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
    '프론트엔드✏️/개인공부' 카테고리의 다른 글
    • [react-query] QueryClient, - 작성 중
    • useEffect vs useLayoutEffect
    • [react-query, ] invalidateQueries, 에러 박스
    • [react-query] 검색 기능
    당근먹는하니
    당근먹는하니

    티스토리툴바

    단축키

    내 블로그

    내 블로그 - 관리자 홈 전환
    Q
    Q
    새 글 쓰기
    W
    W

    블로그 게시글

    글 수정 (권한 있는 경우)
    E
    E
    댓글 영역으로 이동
    C
    C

    모든 영역

    이 페이지의 URL 복사
    S
    S
    맨 위로 이동
    T
    T
    티스토리 홈 이동
    H
    H
    단축키 안내
    Shift + /
    ⇧ + /

    * 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.