Skip to main content Skip to footer

How to Load & View PDF Files in a Vue Application

  • 0 Comments
Quick Start Guide
Tutorial Concept

Vue PDF Viewer - Add the ability to view PDF files in Vue applications. The Documents Solutions PDF Viewer makes it possible to add this functionality and other document management options to web applications.

What You Will Need

NPM @mescius/dspdfviewer
Visual Studio Code
Vue3 or Earlier

Controls Referenced

Document Solutions PDF Viewer - Vue PDF Viewer Control
Online Demo Explore | Documentation

The Document Solutions PDF Viewer (DsPdfViewer) is a Vue PDF Viewer that enables users to view and edit PDF files directly in the browser— including interactive PDF forms. Compatible with all modern browsers, it also allows users to save their modified PDFs on the client side. In this article, we’ll show you how to integrate the Document Solutions PDF Viewer into a Vue application, giving users a seamless way to interact with PDF content in-browser.

Load and View PDF Files in a Vue PDF Control

Download a finished Vue3 sample app to follow along with the blog!

Steps for Loading & Viewing PDFs in Vue3 Apps: Viewer Integration and Loading Methods

  1. Integrate the Vue PDF Viewer Control into the Vue Project
  2. Load or Open a Default PDF Template
  3. Load or Open a PDF from a URL
  4. Load or Open a PDF from Another Domain URL using a CORS Proxy

Work on PDFs in Vue on your own by downloading a FREE trial of Document Solutions for PDF!


Integrate the Vue PDF Viewer Control into the Vue Project

Using the following command create a simple Vue project. This command will run create-vue, the Vue scaffolding tool, with optional prompts for features like TypeScript and testing support.

npm create vue@latest 

Note, you will be given several optional features such as TypeScript and Testing Support:

Creating a Vue Application

After creating the project, use the following commands to navigate to the project directory and install the Document Solutions PDF Viewer NPM package. Optionally, you can additionally install bootstrap for styling.

cd pdf-viewer-app
npm install @mescius/dspdfviewer
npm install bootstrap

After the installation is complete, all of the required files are installed in the node_modules → @mescius → dspdfviewer folder, as depicted below:

Node Modules Folder in the Vue PDF View Application | DsPdfViewer Install

Update the App.vue file by replacing the template with the following code to create a host element for the Vue PDF Viewer.

<template>
  <div id="viewer"></div>
</template>

Next, initialize the PDF Viewer inside the onMounted lifecycle hook by creating a new DsPdfViewer instance and passing in the ID of the host element. Then, call the addDefaultPanels method to display the viewer’s built-in toolbar and navigation panels.

<script setup>
import { onMounted } from 'vue'
import { DsPdfViewer } from '@mescius/dspdfviewer'
import 'bootstrap/dist/css/bootstrap.css'

onMounted(() => {
  const viewer = new DsPdfViewer(document.getElementById('viewer'), {
    workerSrc: "./node_modules/@mescius/dspdfviewer/dspdfviewer.worker.js"
  })
  viewer.addDefaultPanels()
})
</script>

Lastly, set the CSS styling for the PDF Viewer’s host element in the main.css class.

html, body, #app {
  height: 100%;
  margin: 0;
  padding: 0;
}
#viewer {
  height: 100%;
  width: 100%;
}

Run the Vue3 project and notice the PDF viewer control shows in the browser with the default side panels:

Vue PDF Viewer Example Application - Default Panels

Check out the online Vue PDF Viewer demo and documentation to learn more about this developer friendly PDF viewer control.


Load or Open a Default PDF Template

With the application configured and the Document Solutions PDF Viewer successfully rendered in the browser, we can now load and display a PDF file within the viewer. In this example, we'll load a local PDF file stored in the Vue project directory at public/pdfs/social_media_schedule.pdf.

To render the PDF, use the open method provided by DsPdfViewer, passing in the relative file path as an argument.

  viewer.open("./public/pdfs/social_media_schedule.pdf");

Notice, the specified PDF will now appear on load in the Vue PDF Viewer. 

Load a Local PDF in the Browser from a Vue Application

The PDF Viewer API also provides an openLocalFile method, which allows the user to choose the PDF that they want to load into the DsPdfViewer using the file open dialog.

Watch it in action: Here's a short video showing how to load a default PDF template into the JavaScript PDF Viewer control in a Vue application.


Load or Open a PDF from a URL

In addition to loading local files, you can also open PDFs hosted on the same domain as your Vue application. To do this, use the open method and pass the URL of the PDF as an argument:

viewer.open("/document-solutions/javascript-pdf-viewer/demos/product-bundles/assets/pdf/helloworld.pdf")

This method works for any PDF file that is accessible within your app’s domain. Once called, the viewer will fetch and render the specified PDF directly in the browser.

Load a PDF from a URL into a Vue PDF Viewer App

Test the above code here in the online PDF Viewer demo sample.


Load or Open a PDF from Another Domain URL using a CORS Proxy

To load a PDF from another domain, use the SupportApi configuration to avoid CORS issues. SupportApi is a lightweight ASP.NET Core service included with Document Solutions for PDF that acts as a proxy for loading and processing remote PDFs.

The supportApi object in the viewer config enables this, and you’ll also need to create a CorsProxyController on the server to download and stream remote files.

Start by adding the following controller to your SupportApi ASP.NET Core project:

[ApiController]
[Route("[controller]")]
public class CorsProxyController : ControllerBase
{
    private readonly IHttpClientFactory _httpClientFactory;
    public CorsProxyController(IHttpClientFactory httpClientFactory) => _httpClientFactory = httpClientFactory;

    [HttpGet]
    public async Task<IActionResult> Get(string url)
    {
        if (string.IsNullOrEmpty(url)) return BadRequest("Missing 'url' query parameter.");
        var client = _httpClientFactory.CreateClient();
        var response = await client.GetAsync(url);
        if (!response.IsSuccessStatusCode) return StatusCode((int)response.StatusCode);
        var stream = await response.Content.ReadAsStreamAsync();
        var contentType = response.Content.Headers.ContentType?.ToString() ?? "application/pdf";
        return File(stream, contentType);
    }
}

Make sure to register the HTTP client in Program.cs:

builder.Services.AddHttpClient();

In your Vue component, set up the viewer with the supportApi config pointing to your backend, and call the open method provided by DsPdfViewer, passing in the proxy endpoint:

onMounted(() => {
  const viewer = new DsPdfViewer("#viewer", {
    workerSrc: "https://cdn.mescius.com/ds-pdfviewer/latest/dspdfviewer.worker.js",
    restoreViewStateOnLoad: false,
    supportApi: {
      apiUrl: "https://localhost:7296",
      token: "support-api-demo-net-core-token-2021",
      webSocketUrl: false
    }
  });

  viewer.addDefaultPanels();
  viewer.open("https://localhost:7296/CorsProxy?url=https://www.africau.edu/images/default/sample.pdf");
});

Once configured, the Vue app will be able to open PDFs from external domains without hitting CORS issues, using an ASP.NET Core app as a secure proxy.

Load PDF Files in JavaScript PDF Viewer from a URL Avoiding CORS using a Proxy Server

Conclusion

This completes the basics of configuring the Document Solutions PDF Viewer in a Vue application. Download the Vue3 sample that we built throughout the article to check it out. Make sure to install the DsPdfViewer NPM package to get the sample working.

You can also refer to this online demo to observe the sample in action and go through the implementation details.

Work on PDFs in Vue on your own by downloading a FREE trial of Document Solutions for PDF!


Vue PDF Viewer Control

This article just scratches the surface of the full capabilities of the Vue PDF Viewer, Document Solutions PDF Viewer. Check out the online demo explorer and documentation to learn more about this powerful control.

Tags: