
관련 깃허브 링크는 다음과 같다.
https://github.com/wojtekmaj/react-pdf
GitHub - wojtekmaj/react-pdf: Display PDFs in your React app as easily as if they were images.
Display PDFs in your React app as easily as if they were images. - wojtekmaj/react-pdf
github.com
설치 방법 >
npm install react-pdf
or
yarn add react-pdf
이후
react-pdf를 설치하고 withResolver가 없다는 에러를 막기 위해 core-js도 설치해 준다
npm install core-js
import
import { Document, Page, pdfjs } from "react-pdf";
import "core-js/full/promise/with-resolvers.js";
import "pdfjs-dist/webpack";
// Polyfill for environments where window is not available (e.g., server-side rendering)
// @ts-expect-error This does not exist outside of polyfill which this is doing
if (typeof Promise.withResolvers === "undefined") {
if (typeof window !== "undefined") {
// @ts-expect-error This does not exist outside of polyfill which this is doing
window.Promise.withResolvers = function () {
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};
} else {
// @ts-expect-error This does not exist outside of polyfill which this is doing
global.Promise.withResolvers = function () {
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};
}
}
// ❌❌❌❌ 아래 코드를 사용하게 되면 build 에러 발생
// import "pdfjs-dist/webpack"; 해주고
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
"pdfjs-dist/legacy/build/pdf.worker.min.mjs",
import.meta.url,
).toString();
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
// 위 코드로 대신 사용!
pdf를 보여주는 컴포넌트 상단에 위의 코드를 import 한다.
Document: prop를 사용하여 전달된 문서를 로드한다.
Page: 페이지를 표시하며 내부에 배치해야 한다.
Document에서 파일을 로드 👉 Page에서 어떻게 보여줄지 커스텀 가능하다.
component
import { useState } from 'react';
import { Document, Page } from 'react-pdf';
function MyApp() {
const [numPages, setNumPages] = useState<number>();
const [pageNumber, setPageNumber] = useState<number>(1);
function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {
setNumPages(numPages);
}
return (
<div>
<Document file="somefile.pdf" onLoadSuccess={onDocumentLoadSuccess}>
<Page pageNumber={pageNumber} />
</Document>
<p>
Page {pageNumber} of {numPages}
</p>
</div>
);
}
공식에서 소개하고 있는 기본 사용법이다
numPages는 전체 페이지 수이고 pageNumber는 현재 페이지를 나타낸다
onLoadSuccess 이벤트를 사용해서 로드가 되면 페이지를 할당해 주는 함수를 만들어 사용한다
⭐️ Document 컴포넌트의 file에는 띄워줄 pdf의 url을 넘겨줘야 한다.
참고 블로그
https://velog.io/@saemmmm/react-pdf-%EC%82%AC%EC%9A%A9%EB%B2%95
react-pdf 사용법
pdf 뷰어인 react-pdf 사용법react-pdf 깃허브pnpm add react-pdfpnpm add core-jsreact-pdf를 설치하고 withResolver가 없다는 에러를 막기 위해 core-js도 설치해준다pdf를 보여주는 컴포넌트 상단에 위의 코
velog.io
(위 블로그를 참고하였다.)
https://www.youtube.com/watch?v=ajgawvxCdDo
(관련 영상) - kakao
'프론트 엔드 > React' 카테고리의 다른 글
Vite로 리액트 프로젝트 시작하기 (0) | 2025.03.08 |
---|---|
create react app 지원 중단 (2) | 2025.03.07 |
리액트 로딩창 구현 (0) | 2025.02.25 |
리액트 emotion 사용법 (2) | 2025.02.23 |
리액트 zustand란? (0) | 2025.02.21 |