From 820ef74757b3eea95dc3e0366e9434b6a330c0ec Mon Sep 17 00:00:00 2001 From: Mykhailo Kravchenko Date: Tue, 5 Mar 2024 17:27:48 +0100 Subject: [PATCH 1/2] allow local file uploading for example --- example/src/App.tsx | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/example/src/App.tsx b/example/src/App.tsx index e5b7650..908e54e 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -53,6 +53,20 @@ function App() { > example_protected.pdf + + { + const uploadedFile = event?.target?.files?.[0]; + + if (!uploadedFile) { + return; + } + + setFile(URL.createObjectURL(uploadedFile)); + }} + /> )} From 6e3a2024395bd3c195ce38d5c1fa12a0c0ffc57a Mon Sep 17 00:00:00 2001 From: Mykhailo Kravchenko Date: Tue, 5 Mar 2024 17:28:23 +0100 Subject: [PATCH 2/2] fix pdf worker offline behaviour --- example/webpack.config.js | 7 +++++++ src/PDFPreviewer.tsx | 7 +++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/example/webpack.config.js b/example/webpack.config.js index cb5905d..d8e3af9 100644 --- a/example/webpack.config.js +++ b/example/webpack.config.js @@ -42,6 +42,13 @@ module.exports = { test: /\.css$/, use: ['style-loader', 'css-loader'], }, + // We are importing this worker as a string by using asset/source otherwise it will default to loading via an HTTPS request later. + // This causes issues if we have gone offline before the pdfjs web worker is set up as we won't be able to load it from the server. + { + // eslint-disable-next-line prefer-regex-literals + test: new RegExp('node_modules/pdfjs-dist/legacy/build/pdf.worker.js'), + type: 'asset/source', + }, ], }, plugins: [ diff --git a/src/PDFPreviewer.tsx b/src/PDFPreviewer.tsx index ebc8d0b..90618f1 100644 --- a/src/PDFPreviewer.tsx +++ b/src/PDFPreviewer.tsx @@ -1,3 +1,6 @@ +// @ts-expect-error - This line imports a module from 'pdfjs-dist' package which lacks TypeScript typings. +// eslint-disable-next-line import/no-extraneous-dependencies +import pdfWorkerSource from 'pdfjs-dist/legacy/build/pdf.worker'; import React, {memo, useCallback, useLayoutEffect, useRef, useState} from 'react'; import type {CSSProperties} from 'react'; import times from 'lodash/times'; @@ -91,8 +94,8 @@ const defaultProps = { containerStyle: {}, contentContainerStyle: {}, }; -// @ts-expect-error - It is a recommended step for import worker - https://github.com/wojtekmaj/react-pdf/blob/main/packages/react-pdf/README.md#import-worker-recommended -pdfjs.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.js', import.meta.url).toString(); + +pdfjs.GlobalWorkerOptions.workerSrc = URL.createObjectURL(new Blob([pdfWorkerSource], {type: 'text/javascript'})); function PDFPreviewer({pageMaxWidth, isSmallScreen, file, containerStyle, contentContainerStyle}: Props) { const [pageViewports, setPageViewports] = useState([]);