How to Build an Ionic PDF Viewer with PDF.js

24 Jun 2020

author
Dustin Riley

In this article (a four-minute read), you’ll learn how to quickly build a PDF viewer within an Ionic app with PDF.js, a popular open-source PDF viewer.

Here’s the app we are going to build:

The source code for this project is available in our Git repo.

Prerequisites

Step 1 - Create your Ionic app

Create an Ionic app by visiting the Ionic website and going through the steps to set up your project. It will ask you to choose a template and a framework. We will be using React for this tutorial with the TABS template.

Step 2 - Install the App

After going through all the set up steps, the Ionic website will give you two commands to run:

npm install -g @ionic/cli cordova-res
ionic start --start-id <Your-project-id>

The first command installs the Ionic command line interface and the next one installs your unique project.

Once your project has been installed you will need to navigate to the project directory to run it locally.

cd <your-project-name>
ionic serve  

Navigate to http://localhost:8100/ and you’ll see our default tab screen:

Step 3 - Implementing PDF.js

We will now integrate the open-source PDF.js library into our project to render a PDF inside our app. We will start by downloading the latest stable release from GitHub and then extracting the contents into a new public/lib folder.

We will also need a PDF file to view, which we will place in the web folder. You can use your own or download one from here.

The new file structure in our public folder will look like the following (it’s OK to have a different PDF.js version number):

public
├── lib
│   ├── pdfjs-2.3.200-dist
|       ├── build
|           ├── ...
|       ├── web
|           ├── my-pdf-file.pdf
|           ├── ...
|       ├── LICENSE
├── assets
├── index.html
└── manifest.json

Step 4 - Create a React Component

Next, let’s create a basic React component for our PDF viewer called PDFJSViewer.tsx, located under src/components. Here’s the code:

import React from 'react';

interface ContainerProps {
    height: string;
    width: string;
    url?: string
}
const path = 'lib/web/viewer.html'

const PdfJSViewer: React.FC<ContainerProps> = ({ height, width, url }) => {
    let pdfPath = url ? path + '?file=' + url : path;

    return (
        <div style={{ width, height }}>
            {
                <iframe
                    width='100%'
                    height='100%'
                    src={pdfPath}
                >
                </iframe>
            }
        </div>
    )
}

export default PdfJSViewer

The interface ContainerProps section of our component is where we will define the type of the props being passed to our component.

const path is the path to where the PDF.js viewer.html is located. You may have to change this path if you didn’t place your download of PDF.js into the public/lib folder.

const PdfJSViewer is what will return our instance of PDF.js within an iframe. It takes three props: width, height, and filename of a PDF you want to display.

Step 5 - Import the PDF Viewer Component

Now we will import the PDF viewer component and render it in our app.

If you are following along with the tab template, the files you will want to edit are all in the pages folder and are: tab1.tsx tab2.tsx and tab2.tsx. They are all currently identical besides their names/titles.

In each of the tab#.tsx replace the following line:

import ExploreContainer from '../components/ExploreContainer';

With:

import PdfJSViewer from '../components/PDFJSViewer';

And replace:

<ExploreContainer name="Tab # page" />

With:

<PdfJSViewer height="100%" width="100%"/>

This will display the default PDF.js PDF. If you want to display your own custom PDF, replace the above line with the line below instead. Replace demo.pdf with the name of your PDF located within the lib/web folder.

<PdfJSViewer height="100%" width="100%" url="demo.pdf" />

You can repeat this step for each tab that you want to display a PDF on.

Our http://localhost:8100/ will now display a different PDF on each tab rendered inside our PDF.js viewer.

Step 6 - Customizing the PDF.js Toolbar

As a final and optional step, we will reorganize the toolbar by moving elements around, removing buttons, and changing the icons.

Let’s open public/lib/pdfjs-2.3.200-dist/web/viewer.html and add the following to the <head> section:

<script src="customToolbar.js"></script>

Next, we’ll create customToolbar.js inside the public/lib/pdfjs-2.3.200-dist/web folder and add the following code:

//create a new style sheet
let sheet = (function() {
  let style = document.createElement("style");
  style.appendChild(document.createTextNode(""));
  document.head.appendChild(style);
  return style.sheet;
 })();
 function editToolBar(){
  //when the page is resized, the viewer hides and move some buttons around.
  //this function forcibly show all buttons so none of them disappear or re-appear on page resize
  removeGrowRules();

  /* Reorganizing the UI */
  // the 'addElemFromSecondaryToPrimary' function moves items from the secondary nav into the primary nav
  // there are 3 primary nav regions (toolbarViewerLeft, toolbarViewerMiddle, toolbarViewerRight)

  //adding elements to left part of toolbar
  addElemFromSecondaryToPrimary('pageRotateCcw', 'toolbarViewerLeft')
  addElemFromSecondaryToPrimary('pageRotateCw', 'toolbarViewerLeft')
  addElemFromSecondaryToPrimary('zoomIn', 'toolbarViewerLeft')
  addElemFromSecondaryToPrimary('zoomOut', 'toolbarViewerLeft')

  //adding elements to middle part of toolbar
  addElemFromSecondaryToPrimary('previous', 'toolbarViewerMiddle')
  addElemFromSecondaryToPrimary('pageNumber', 'toolbarViewerMiddle')
  addElemFromSecondaryToPrimary('numPages', 'toolbarViewerMiddle')
  addElemFromSecondaryToPrimary('next', 'toolbarViewerMiddle')

  //adding elements to right part of toolbar
  addElemFromSecondaryToPrimary('secondaryOpenFile', 'toolbarViewerRight')

  /* Changing icons */
  changeIcon('previous', 'icons/baseline-navigate_before-24px.svg')
  changeIcon('next', 'icons/baseline-navigate_next-24px.svg')
  changeIcon('pageRotateCcw', 'icons/baseline-rotate_left-24px.svg')
  changeIcon('pageRotateCw', 'icons/baseline-rotate_right-24px.svg')
  changeIcon('viewFind', 'icons/baseline-search-24px.svg');
  changeIcon('zoomOut', 'icons/baseline-zoom_out-24px.svg')
  changeIcon('zoomIn', 'icons/baseline-zoom_in-24px.svg')
  changeIcon('sidebarToggle', 'icons/baseline-toc-24px.svg')
  changeIcon('secondaryOpenFile', './icons/baseline-open_in_browser-24px.svg')

  /* Hiding elements */
  removeElement('secondaryToolbarToggle')
  removeElement('scaleSelectContainer')
  removeElement('presentationMode')
  removeElement('openFile')
  removeElement('print')
  removeElement('download')
  removeElement('viewBookmark')
 }
 function changeIcon(elemID, iconUrl){
  let element = document.getElementById(elemID);
  let classNames = element.className;
  classNames = elemID.includes('Toggle')? 'toolbarButton#'+elemID :
 classNames.split(' ').join('.');
  classNames = elemID.includes('view')? '#'+elemID+'.toolbarButton' : '.'+classNames
  classNames+= "::before";
  addCSSRule(sheet, classNames, `content: url(${iconUrl}) !important`, 0)
 }
 function addElemFromSecondaryToPrimary(elemID, parentID){
  let element = document.getElementById(elemID);
  let parent = document.getElementById(parentID);
  element.style.minWidth = "0px";
  element.innerHTML =''
  parent.append(element);
 }
 function removeElement(elemID){
  let element = document.getElementById(elemID);
  element.parentNode.removeChild(element);
 }
 function removeGrowRules(){
  addCSSRule(sheet, '.hiddenSmallView *', 'display:block !important');
  addCSSRule(sheet, '.hiddenMediumView', 'display:block !important');
  addCSSRule(sheet, '.hiddenLargeView', 'display:block !important');
  addCSSRule(sheet, '.visibleSmallView', 'display:block !important');
  addCSSRule(sheet, '.visibleMediumView', 'display:block !important');
  addCSSRule(sheet, '.visibleLargeView', 'display:block !important');
 }
 function addCSSRule(sheet, selector, rules, index) {
  if("insertRule" in sheet) {
  sheet.insertRule(selector + "{" + rules + "}", index);
  }
  else if("addRule" in sheet) {
  sheet.addRule(selector, rules, index);
  }
 }
 window.onload = editToolBar

The PDF.js primary toolbar is broken down into 3 regions:

Screenshot: PDF.js Viewer Primary Toolbar Regions

The secondary toolbar is accessed via the chevron icon in the right region:

Screenshot: PDF.js Viewer Secondary Toolbar

We can move elements from the secondary toolbar into the left, middle, or right regions of the primary toolbar with the addElemFromSecondaryToPrimary function in customToolbar.js. For example, uncommenting this line will move the counter-clockwise rotation tool to the left region of the primary toolbar:

  addElemFromSecondaryToPrimary('pageRotateCcw', 'toolbarViewerLeft')

If you wanted to move pageRotateCcw to the middle region instead, you’d replace toolbarViewerLeft with toolbarViewerMiddle, or toolbarViewerRight for the right region. To move a different tool, replace the pageRotateCcw ID with the element ID you want to move. (See below for a full list of element IDs.)

We can also hide elements like this:

  removeElement('print')
  removeElement('download')

To hide different elements, replace print or download with the element ID.

NOTE: Hiding the download and print buttons is not a bulletproof way to protect our PDF, because it’s still possible to look at the source code to find the file. It just makes it a bit harder.

We can also customize the icons for various tools by swapping out the SVG file, like this:

changeIcon('previous', 'icons/baseline-navigate_before-24px.svg')

In the above example, previous is the element ID, while icons/baseline-navigate_before-24px.svg is the path to the tool icon.

And that’s it!

Element ID Reference for PDF.js User Interface Customization

Here’s handy reference with the IDs of the various toolbar icons:

Toolbar Icon ID
PDF Viewer UI Icon: sidebarToggle sidebarToggle
PDF Viewer UI Icon: viewFind viewFind
PDF Viewer UI Icon: pageNumber pageNumber
PDF Viewer UI Icon: numPages numPages
PDF Viewer UI Icon: zoomOut zoomOut
PDF Viewer UI Icon: zoomIn zoomIn
PDF Viewer UI Icon: next page next
PDF Viewer UI Icon: previous page previous
PDF Viewer UI Icon: presentationMode presentationMode
PDF Viewer UI Icon: openFile openFile
PDF Viewer UI Icon: print print
PDF Viewer UI Icon: download download
PDF Viewer UI Icon: viewBookmark viewBookmark
PDF Viewer UI Icon: secondaryToolbarToggle secondaryToolbarToggle
PDF Viewer UI Icon: scaleSelectContainer scaleSelectContainer
PDF Viewer UI Icon: secondaryPresentationMode secondaryPresentationMode
PDF Viewer UI Icon: secondaryOpenFile secondaryOpenFile
PDF Viewer UI Icon: secondaryPrint secondaryPrint
PDF Viewer UI Icon: secondaryDownload secondaryDownload
PDF Viewer UI Icon: secondaryViewBookmark secondaryViewBookmark
PDF Viewer UI Icon: firstPage firstPage
PDF Viewer UI Icon: lastPage lastPage
PDF Viewer UI Icon: pageRotateCw pageRotateCw
PDF Viewer UI Icon: pageRotateCcw pageRotateCcw
PDF Viewer UI Icon: cursorSelectTool cursorSelectTool
PDF Viewer UI Icon: cursorHandTool cursorHandTool
PDF Viewer UI Icon: scrollVertical scrollVertical
PDF Viewer UI Icon: scrollHorizontal scrollHorizontal
PDF Viewer UI Icon: scrollWrapped scrollWrapped
PDF Viewer UI Icon: spreadNone spreadNone
PDF Viewer UI Icon: spreadOdd spreadOdd
PDF Viewer UI Icon: spreadEven spreadEven
PDF Viewer UI Icon: documentProperties documentProperties

Conclusion

As you can see, rendering a PDF inside an Ionic app isn't difficult using open-source libraries.

Building a PDF Viewer with Ionic is relatively straightforward, but once you want to start annotating, signing, or filling forms, you would have to implement these things yourself. See our PDF.js Build vs Buy and Guide to Evaluating PDF.js to learn more.

That’s where PDF.js Express comes in. It’s a commercial PDF.js viewer that wraps a React-based UI around the open-source PDF.js rendering engine and offers out-of-the-box features like annotations, form filling and e-signatures. It’s fully compatible with many frameworks -- check out the demo, and let us know what you think!

If you need high-fidelity rendering, increased reliability, and faster performance, you could consider PDFTron WebViewer. It’s a JavaScript PDF library that integrates with Ionic/Cordova, and offers hundreds of features, like redaction, editing, page manipulation, real-time document collaboration, digital signatures, and much more. Check out the WebViewer demo.

If you have any questions about implementing PDF.js Express in your project, please contact us and we will be happy to help!