Add PDF functionality with TypeScript
Nutrient Web SDK is a PDF library for viewing, annotating, and editing PDFs directly in the browser. Use it to add PDF capabilities to any web application.
This guide walks you through the necessary steps to integrate Nutrient Web SDK into your TypeScript project. By the end, you’ll be able to render a PDF document in the user interface (UI).
You can test the SDK capabilities in our playground.
Prefer to jump straight to code? View the example repo on GitHub.
Prerequisites
A package manager compatible with npm(opens in a new tab). This guide contains usage examples for Yarn(opens in a new tab), pnpm(opens in a new tab), and the npm client(opens in a new tab). The npm client is installed with Node.js by default.
Node.js is required to complete this guide, but it’s not a general requirement for using Nutrient Web SDK.
Run the following command to install TypeScript globally:
Terminal window npm i -g typescriptTerminal window pnpm add -g typescriptTerminal window yarn global add typescript
Creating a new project
If you don’t have a project set up yet, you can create a new one using the following commands.
Run the following command to initialize a new npm workspace in an empty directory:
Terminal window npm i init -yTerminal window pnpm add init -yTerminal window yarn add init -yIn the root folder of your project, create a
tsconfig.json
file with the following content:{"compilerOptions": {"removeComments": true,"preserveConstEnums": true,"module": "commonjs","target": "es5","sourceMap": true,"noImplicitAny": true,"esModuleInterop": true},"include": ["src/**/*"]}
Adding Nutrient Web SDK dependency
Add the Nutrient Web SDK dependency:
Terminal window npm i @nutrient-sdk/viewerTerminal window pnpm add @nutrient-sdk/viewerTerminal window yarn add @nutrient-sdk/viewerRun the following commands to install the necessary dependencies for
webpack
, create aconfig
directory, and place yourwebpack
configuration file inside it:Terminal window npm i -D webpack webpack-cli webpack-dev-server ts-loader typescript html-webpack-plugin cross-env copy-webpack-plugin clean-webpack-pluginTerminal window pnpm add -D webpack webpack-cli webpack-dev-server ts-loader typescript html-webpack-plugin cross-env copy-webpack-plugin clean-webpack-pluginTerminal window yarn add -D webpack webpack-cli webpack-dev-server ts-loader typescript html-webpack-plugin cross-env copy-webpack-plugin clean-webpack-pluginTerminal window mkdir config && touch config/webpack.jsIn the
config
folder, add the following code to thewebpack.js
file:const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');const CopyWebpackPlugin = require('copy-webpack-plugin');const filesToCopy = [// Nutrient files.{from: './node_modules/nutrient-sdk/viewer/dist',to: './nutrient-lib',},// Application CSS.{from: './src/index.css',to: './index.css',},// Example PDF.{from: './assets/document.pdf',to: './document.pdf',},];/*** webpack main configuration object.*/const config = {entry: path.resolve(__dirname, '../src/index.ts'),mode: 'development',devtool: 'inline-source-map',output: {path: path.resolve(__dirname, '../dist'),filename: '[name].js',},resolve: {extensions: ['.ts', '.tsx', '.js'],},module: {rules: [// All files with a `.ts` or `.tsx` extension will be handled by `ts-loader`.{test: /\.tsx?$/,loader: 'ts-loader',exclude: /node_modules/,},],},plugins: [new HtmlWebpackPlugin({template: './src/index.html',}),// Copy the WASM/ASM and CSS files to the `output.path`.new CopyWebpackPlugin({ patterns: filesToCopy }),],optimization: {splitChunks: {cacheGroups: {// Creates a `vendor.js` bundle that contains external libraries (including `pspdfkit.js`).vendor: {test: /node_modules/,chunks: 'initial',name: 'vendor',priority: 10,enforce: true,},},},},};module.exports = config;
Rendering a PDF
Rename the PDF document you want to display in your application to
document.pdf
, and place it in anassets
directory within your project. You can use this demo document as an example.Create a
src
folder in your project, and within it, create anindex.html
file with the following content. This adds an empty<div>
element where Nutrient Web SDK viewer is loaded:<!DOCTYPE html><html><head><title>Nutrient Web SDK viewer — TypeScript example</title><link rel="stylesheet" href="index.css" /></head><body><div class="container"></div></body></html>In the
src
folder, create anindex.css
file with the following content. This declares the height of the viewer element:.container {height: 100vh;}In the
src
folder, create anindex.ts
file with the following content:import NutrientViewer from '@nutrient-sdk/viewer';function load(document: string) {console.log(`Loading ${document}...`);NutrientViewer.load({document,container: '.container',}).then((instance) => {console.log('Nutrient loaded', instance);}).catch(console.error);}load('document.pdf'); // Pass your PDF file.Your project structure will look as follows:
nutrient-typescript-example├── assets│ └── document.pdf├── config│ └── webpack.js├── src│ ├── index.css│ ├── index.html│ └── index.ts├── node_modules├── dist├── package-lock.json├── package.json└── tsconfig.json
Running the project
Run the following command to install the serve package:
Terminal window npm i -g serveTerminal window pnpm add -g serveTerminal window yarn global add serveReplace the scripts section of the
package.json
file in your project with the following content:"scripts": {"build": "cross-env NODE_ENV=production webpack --config config/webpack.js","prestart": "npm run build","dev": "tsc","start": "serve -l 8080 ./dist"},Run the following command to start the project:
Terminal window npm i startTerminal window pnpm add startTerminal window yarn add startOpen your browser and navigate to http://localhost:8080(opens in a new tab). You’ll see the PDF document rendered in the viewer.