I'm trying to create a PDF viewer on my nextjs static page but i dont know how. hope you guys can help me solving this error or showing one other way to do this. (I'm new to Next.js) I was following this working example here
index.js
import SiteLayout from "../../components/SiteLayout";
import React from 'react';
import ReactDOM from "react-dom";
import Viewer from "../resume/viewer.js";
export default function Resume({ resume }) {
return (
<div>
<Viewer />
</div>
);
}
viewer.js
import React, { useRef, useEffect } from "react";
import WebViewer from "@pdftron/webviewer";
const Viewer = (props) => {
const viewer = useRef(null);
useEffect(() => {
WebViewer({
path: "/lib",
initialDoc: "/pdf/GustavoMorilla.pdf"
}, viewer.current);
}, []);
return (
<div className="Viewer">
<div className="header">React sample</div>
<div className="webviewer" ref={viewer}></div>
</div>
);
};
export default Viewer;
WebViewer
needs the window
object to work. In nextjs
there is a prerender phase server side and on that side window
is not defined.
To solve your problem you can use next/dynamic in viewer.js
import dynamic from 'next/dynamic';
const WebViewer = dynamic(() => import('@pdftron/webviewer'), {ssr: false});
Alternatively you can import Viewer
in index.js
with dynamic import
import dynamic from 'next/dynamic';
const Viewer = dynamic(() => import('../resume/viewer.js'), {ssr: false});
When you import @pdftron/webviewer
some code is running even though you haven't called the WebViewer
function. The useEffect callback doesn't run in SSR. You can use Dynamic Imports there to import the module:
useEffect(() => {
import('@pdftron/webviewer')
.then(WebViewer) => {
WebViewer({
path: "/lib",
initialDoc: "/pdf/GustavoMorilla.pdf"
}, viewer.current);
})
}, []);
I kept getting 'window is not defined', the only solution that worked for me was following the NextJs way for importing external libraries dynamically:
useEffect(() => {
const loadWebViewer = async () => {
const WebViewer = (await import('@pdftron/webviewer')).default;
if (viewer.current) {
WebViewer(
{
path: '/lib',
initialDoc: `/api/getPdf/${encodeURIComponent(file)}/`,
disabledElements: [
'viewControlsButton',
'viewControlsOverlay',
'toolsOverlay',
'ribbonsDropdown',
'selectToolButton',
'panToolButton',
'leftPanelButton',
'toggleNotesButton',
'toolsHeader',
],
},
viewer.current
);
}
};
loadWebViewer();
}, []);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.