Custom PDF Viewer using PDF.js

Custom PDF Viewer using PDF.js

Hey guys, I spent a lot of time trying to figure out how to embed a custom pdf viewer in anvil. So I built a custom pdf viewer using PDF.js and feel free to use it.

This is a custom PDF viewer built using the PDF.js library. As of the latest update, the project works with version 3.7.107 of PDF.js. Future changes might break the current code.

Live demo app: Link
Here is a clonable: link

You can view a functional HTML version of the project hosted on jsfiddle.

Features

The viewer includes several UI elements to facilitate interaction with the loaded PDF:

  • Navigational buttons for page progression.
  • Scroll-enabled page changes.
  • Text selection capabilities.

Getting Started

You can clone the app and use the component in your app using dependencies. Here is a clonable link


Or if you want to start from scratch, follow these instructions below and reference the codes from the clonable app.

Note: Ensure that the library version in your project matches that of PDF.js (v3.7.107) as this is critical to the viewer’s performance.

  1. Import the PDF.js library using a CDN in the Native Libraries section. This process imports the library into your app’s header.
  2. Verify that the version numbers in the custom_pdfviewer.html file match your PDF.js version. The relevant codes are pdfjsLib.GlobalWorkerOptions.workerSrc and SANDBOX_BUNDLE_SRC.
  3. The logic and bindings for the UI elements, including buttons for navigating to the previous/next pages, zooming in/out, and downloading the PDF, are located within the client-side JavaScript of the PDFViewer component.
  4. To display a PDF file from your app, locate the load_document function within the ServerModule1 file. This function retrieves the permanent URL of your file from your datatable. Use this URL to call the JavaScript display_pdf function.

Remember, managing the version number is essential due to significant changes that can occur between library versions. Always ensure your code reflects the correct version number.

10 Likes

This works really well. I had a problem changing pages on PDFs without reloading the PDF and this did the trick.

Thanks!

Thanks for this. I needed this exact solution for my project.

Very useful, thank you!

Thanks it’s really live saving!
One question, how you can pass custom doc_name to it? For some reason I can’t pass anything to it when it loads.

I’ve tried to use module variable to pass it to the query and self.item method but nothing seems to work. Always getting the same error message. How do you pass the custom doc_name to the component?

I suggest you to read this documentation: Anvil Docs | Custom Components.
Example would be: the doc_name as a string in your custom component. And once you add your custom component in your form, you can set the doc_name.