Cloudinary Blog

How to Build a Simple Multipage PDF Viewer with Vue and Cloudinary

By Christian Nwamba
Build a PDF Viewer with Vue.js and Cloudinary

Cloudinary offers an interesting feature: The ability to generate images from the PDF files and pages. With Cloudinary, you can create thumbnail images of your documents for previewing purposes. It's useful when you don't want to grant user access to the content, but need to give them a sneak peek of what they're missing if they haven’t downloaded the PDF yet.

In this blog, we will share a hands-on example for building such solutions using Cloudinary. Here are the tools you’ll need:

  • Cloudinary: End to end image and video management service
  • Vue: Progressive JavaScript framework

Create a Vue Project

The best and easiest way to get started on a Vue project is via the command line tool. You can install it with npm using the following command:

Copy to clipboard
npm install -g vue-cli

This installation exposes Vue commands to the CLI, which you could use to perform various tasks including creating a new Vue project. Here is the command that creates a new project:

Copy to clipboard
vue init simple pdf-viewer

simple is the project template we prefer to use as our very simple example, while pdf-viewer is the name of the project we are creating.

This command creates a file, index.html with some simple markup. Feel free to empty this file and replace with the following:

Copy to clipboard
<html>
<head>
  <title>Welcome to Vue</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="/style.css">
  <script src="https://unpkg.com/vue"></script>
</head>
<body>
  <div id="app">
    <div class="container">
      <h3 class="text-center" style="color:#fff">PDF Viewer</h3>
      <div class="row">
        <div class="col-md-6 col-md-offset-3" v-if="file">
          <img :src="preview" alt="" class="preview">
        </div>
      </div>
      <div class="row pages">
        <div class="col-md-4" v-for="page in pages">
          <img :src="page.url" alt="" class="img-responsive" @click="selectImage(page.page)">
        </div>
      </div>
      <div class="row upload" v-if="!file">
        <div class="col-md-offset-4 col-md-4">
          <button @click="openWidget()">Upload PDF</button>
        </div>
      </div>
    </div>
  </div>
  <script src="//widget.cloudinary.com/global/all.js" type="text/javascript"></script>
  <script src="/script.js"></script>
</body>
</html>
  • Most of our dependencies are included via content delivery networks (CDNs) including Bootstrap, Vue and Cloudinary JavaScript SDK. We also include a style.css and script.js files, which we will need to create.

  • There are three bootstrap-generated rows:

    • The first shows a large preview of the PDF pages and is only active when the file property on the Vue instance is not null. It has an image whose src attribute is bound to a preview property.
    • The second row displays a thumbnail of the PDF as images using a pages array on the Vue instance. When each of the images are clicked, the selectImage method is called to update the larger viewer.
    • Finally, the third contains a button to open the Cloudinary upload widget.

Before we start seeing the logic in action, create a ./style.css and update with the following basic CSS:

Copy to clipboard
html, body, #app, .container {
  height: 100%;
}

.preview {
  margin-top: 40px;
}
img {
  display: block;
  margin: auto;
  border: #E1E1E1;
  box-shadow: 0px 3px 6px 0px rgba(0,0,0,0.3);
}

.upload {
  margin-top: 30%;
  margin-left: 14%;
}

button {
  color: #687DDB;
  padding: 10px 15px;
  border: #e1e1e1;
  background: #fff;
  border-radius: 4px;
}

#app {
  background: #687DDB;
}

.pages {
  margin-top: 20px
}

Image Uploads with Cloudinary Widget

Now that we have a platform, let's start uploading PDF files. First create the JavaScript file we included earlier. Next create a Vue instance and add a method for uploading images:

Copy to clipboard
new Vue({
  el: '#app',
  methods: {
    openWidget(url) {
      window.cloudinary.openUploadWidget(
        {
          cloud_name: 'CLOUD_NAME',
          upload_preset: 'UPLOAD_PRESET',
          tags: ['pdf'],
          sources: [
            'local',
            'url',
          ]
        },
        (error, result) => {
          console.log(error, result);
        }
      );
    }
  }
});

When the button is clicked, the upload widget pops up and should look like this:

Upload button

UPLOAD WIDGET

The openUploadWidget method on the Cloudinary object takes a config and a callback method. The config must have at least a cloud name that is assigned on creating an account and an unsigned upload preset that can be generated from the settings dashboard.

The callback function gets triggered once the upload is successful and is passed a payload of the upload information.

Showing Preview & Thumbnails

Uploading a PDF file logs the result to the console. Hence, we need to start showing the PDF pages as image thumbnails on the view.

Copy to clipboard
new Vue({
  el: '#app',
  data: {
    file: null,
    preview: null,
    pages: []
  },
  methods: {
    openWidget(url) {
      window.cloudinary.openUploadWidget(
        {
          cloud_name: 'christekh',
          upload_preset: 'qbojwl6e',
          tags: ['pdf'],
          sources: [
            'local',
            'url',
          ]
        },
        (error, result) => {
          console.log(error, result);
          this.file = result[0];
          this.preview = `https://res.cloudinary.com/christekh/image/upload/w_350,h_400,c_fill,pg_1/${this.file.public_id}.jpg`;
          for (let i = 1; i <= this.file.pages; i++) {
            this.pages.push(
              {
                url: `https://res.cloudinary.com/christekh/image/upload/w_200,h_250,c_fill,pg_${i}/${this.file.public_id}.jpg`,
                page: i
              }
            )
          }
        }
      );
    }
  }
});

Back to the callback function for the upload widget -- when an image is uploaded, we attempt to do two things:

  1. Set a property preview with a large preview of the image using Cloudinary's URL transformation feature. We set the width to 350, height to 400 and page to 1. To convert the PDF page to an image, we just add an image extension at the end of the URL (.jpg).
  2. Secondly, we create smaller images (200 x 250) of all the pages in the PDF and store all the image URLs in a pages array. This array is iterated over and displayed on the view.

Image of Preview and Pages

Lastly, we want to update the image preview when the thumbnails are clicked. We already have a bound selectImage method. Let's implement this method now:

Copy to clipboard
selectImage(page) {
      this.preview = `https://res.cloudinary.com/christekh/image/upload/w_350,h_400,c_fill,pg_${page}/${this.file.public_id}.jpg`
    }

All it does is update the preview property by setting the page URL to the selected page. Of course the width and height will be 300 X 400 to match the dimensions of the previously previewed image.

Another good point to be aware of is you could improve the quality of the image using the dn transformation parameter:

Copy to clipboard
https://res.cloudinary.com/christekh/image/upload/dn_50,w_350,h_400,c_fill,pg_${page}/${this.file.public_id}.jpg

To even get more strict with the PDF contents, you can use Cloudinary’s overlay feature to add watermarks to the images and protect the content. You can learn more about this feature from the docs provided by Cloudinary.

Conclusion

Cloudinary offers a lot more functionality for generating image previews and thumbnails from a PDF. Learn more about more about Cloudinary’s image manipulation capabilities, sign up for free to start using these features.

This was originally posted on VueJS Developers

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more