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).

Prerequisites

  • The latest stable version of Node.js(opens in a new tab).

  • 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 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.

  1. Run the following command to initialize a new npm workspace in an empty directory:

    Terminal window
    npm i init -y
  2. In 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

  1. Add the Nutrient Web SDK dependency:

    Terminal window
    npm i @nutrient-sdk/viewer
  2. Run the following commands to install the necessary dependencies for webpack, create a config directory, and place your webpack 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-plugin
    Terminal window
    mkdir config && touch config/webpack.js
  3. In the config folder, add the following code to the webpack.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

  1. Rename the PDF document you want to display in your application to document.pdf, and place it in an assets directory within your project. You can use this demo document as an example.

  2. Create a src folder in your project, and within it, create an index.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>
  3. In the src folder, create an index.css file with the following content. This declares the height of the viewer element:

    .container {
    height: 100vh;
    }
  4. In the src folder, create an index.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.
  5. 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

  1. Run the following command to install the serve package:

    Terminal window
    npm i -g serve
  2. Replace 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"
    },
  3. Run the following command to start the project:

    Terminal window
    npm i start
  4. Open your browser and navigate to http://localhost:8080(opens in a new tab). You’ll see the PDF document rendered in the viewer.

Troubleshooting