How to Make a Next.js App With ComPDFKit for Web
Prerequisites
To get started, you'll need:
- The latest stable version of Node.js.
- A package manager compatible with npm.
- Apply the License Key: Contact ComPDFKit's sales team to get a free 30-day license to test the project.
Create a New Project
- Create a new Next.js project:
npx create-next-app@latest
During the setup process, Next.js will prompt you with a series of questions, allowing you to customize your project. For this example, we usually use the defaults.
Change your directory to compdfkit-app:
cd compdfkit-app
Add ComPDFKit for Web
- Install webviewer as a dependency with npm:
npm i @compdfkit_pdf_sdk/webviewer --save
- Add the "webviewer" folder that contains the required static resource files to run the ComPDFKit Web demo, to your project’s public resource folder.The folder you need to copy is
node_modules/@compdfkit_pdf_sdk/webviewer/dist
.
cp -r ./node_modules/@compdfkit_pdf_sdk/webviewer/dist ./public/webviewer
Display a PDF
Add the PDF document you want to display to the
public/webviewer/example
directory. You can use our demo document as an example.When using the Web SDK, you need to use the
path
parameter to tell it where the copied static resources are located, if not, they will be relative to the current path.
If you chose JavaScript during the setup of your project, add the following code to your app/page.js
file:
'use client';
import React, { useRef, useEffect } from 'react';
import Head from 'next/head'
import Webviewer from '@compdfkit_pdf_sdk/webviewer';
export default function Home() {
const viewer = useRef(null);
let docViewer = null;
useEffect(() => {
Webviewer.init({
path: '/',
pdfUrl: './example/developer_guide_web.pdf',
license: '<Input your license here>',
}, viewer.current).then((instance) => {
docViewer = instance.docViewer;
docViewer.addEvent('documentloaded', async () => {
console.log('ComPDFKit Web Demo loaded');
})
})
});
return (
<>
<Head>
<title>ComPDFKit Web Viewer</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<div id="webviewer" ref={viewer} style={{ height: '100vh', overflow: 'hidden' }}></div>
</>
)
}
When WebViewer is initialized, it returns an instance of WebViewer that can be used to call a number of useful APIs for document creation, manipulation, annotation, collaboration, and more.
Learn more about WebViewer’s comprehensive functionality by diving into the documentation.
Lastly, the style option helps us apply custom CSS like width and height on the viewer’s div element which WebViewer gets mounted on.
- Start the app and open it in your default browser:
npm run dev