Injecting PDF into an HTML

PDF is one of the most widely used format for the web today. Every day people all around the world download PDF files from internet, send PDF documents via email and just read PDF books on their devices. However, it’s not so easy if you want to display some PDF file on your site as a part of the web page. In this article we’re going to have a look at the possible ways for injecting PDF into an HTML page, covering the pros and cons of each method.

There’re three main options for injecting a PDF into an HTML page:

  • Using HTML tags iframe, embed and object
  • Using external services, like Slideshare
  • Using JS libraries, like pdf.js by Mozilla

Using <iframe>, <embed> and <object> tags

All these tags are inline elements those content may be taken from an external file, including PDF. This is the most easy and basic option for injecting a PDF into an HTML page. What’s needed is just to add a correspondent tag into the page markup setting the src attribute with a valid link to the document we want to display. We can also adjust width and height of the element by either specifying corresponding HTML attributes or with custom CSS styles.

<iframe src="https://scalified.com/valid-document-url.pdf" width="100%" height="100%"></iframe>
<embed src="https://scalified.com/valid-document-url.pdf" width="100%" height="100%"></embed>
<object src="https://scalified.com/valid-document-url.pdf" width="100%" height="100%"></object>

These tags are quite well supported for all the modern browsers, however there’s an important detail to consider when using them for displaying PDF files – they all assume that the browser knows how to render PDF format, e.g. some plugin is installed. For example, Chrome has the needed plugin installed out of the box. In case of other browsers/plugins the result is directly dependent on the particular plugin.

Injecting PDF via iframe

Injecting PDF via iframe

Using external services for documents hosting

There’re various online services that allow to host documents and share them over the internet. Some of them are using iframe for embedding documents into web-pages. For example, one of those services, Slideshare, generates code like this:

<iframe src="http://www.slideshare.net/slideshow/embed_code/key/fZHbg6xSXHL9Ua?startSlide=32" width="595" height="485" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;" allowfullscreen> </iframe>

As result, it will display the document in the iframe:
Injecting PDF Slideshare

The advantage of this method is simplicity, however the limitation is that your PDF files have to be uploaded to Slideshare and you’re limited by it’s functionality. For example, if you need to display dynamic PDF files depending on some condition, you might find it quite challenging to implement this using any of the third-party services.

Injecting PDF using js-libraries (e.g. pdf.js)

The last option we’re going to have a look at is using special js-libraries for PDF rendering. One of the most famous is pdf.js by Mozilla. Here’s an example taken from the official docs:

<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>

<h1>PDF.js 'Hello, base64!' example</h1>

<canvas id="the-canvas"></canvas>

In this simple HTML markup we’ve included pdf.js library itself and created a <canvas> element where PDF will be rendered. To do the rendering we’re going to use pdf.js in the following script:

// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
var url = '//cdn.mozilla.net/pdfjs/helloworld.pdf';

// Disable workers to avoid yet another cross-origin issue (workers need
// the URL of the script to be loaded, and dynamically loading a cross-origin
// script does not work).
// PDFJS.disableWorker = true;

// The workerSrc property shall be specified.
PDFJS.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

// Asynchronous download of PDF
var loadingTask = PDFJS.getDocument(url);
loadingTask.promise.then(function(pdf) {
  console.log('PDF loaded');

  // Fetch the first page
  var pageNumber = 1;
  pdf.getPage(pageNumber).then(function(page) {
    console.log('Page loaded');

    var scale = 1.5;
    var viewport = page.getViewport(scale);

    // Prepare canvas using PDF page dimensions
    var canvas = document.getElementById('the-canvas');
    var context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    // Render PDF page into canvas context
    var renderContext = {
      canvasContext: context,
      viewport: viewport
    };
    var renderTask = page.render(renderContext);
    renderTask.then(function () {
        console.log('Page rendered');
      });
  });
}, function (reason) {
  // PDF loading error
  console.error(reason);
});

It will display your PDF file on the page.
Injecting PDF with javascript pdf.js

In this example <canvas> is used for rendering, however there’s a possibility to render documents into regular html markup, so that it would look like a part of the original page markup.

Obviously, this method is very flexible and makes it possible to do quite fancy stuff. For example, we’re using it in one of our software products to display corporate documents, depending on various business conditions. Besides, there’re plenty of wrapper-libraries for most popular frontend frameworks like Angular, Vue.js, React etc, which is a good starting point for using this method.

On the other hand, there’s a disadvantage that might be significant – browser support. For example, IE9 partially supports pdf.js functionality, IE8 and lower don’t support it at all. For full browsers-support list see FAQ on the vendor’s Github page.

We hope you’ll find this article useful. Have a great day and follow Scalified to read more frontend development articles!

Denys Koval - Frontend Engineer at Scalified

Denys Koval

Frontend Engineer at Scalified