Is it possible to utilize PDF.js once the PDF file has been downloaded?

My goal is to integrate PDF.js (or Viewer.js) with a Flask application, where I have already retrieved the file from a server.

Instead of using

PDFJS.getDocument('helloworld.pdf') 

I prefer to display the downloaded PDF in the browser through an Ajax call. This approach allows the server to have more control over providing access only to authorized users.

For example, in Flask:

@mayapp.route('/files/<int:file_id>', methods=['GET'])
def file_access(file_id: int=None):
    // Retrieve file path from the database based on user access
    return send_file(file_path)

On the client side:

fetchData: function () {
    axios({
      method: 'get',
      url: '/myapp/files/' + this.file_id,
      dataType: ...,
      headers: ...,
      data: {}
    })
    .then((response) => {
        this.file = response.data
      })
}

Next step is to use PDF.js to view the fetched file:

One way is to utilize a base64 encoded string like demonstrated in Flask / postgres - display pdf with PDFJS:

var doc = PDFJS.getDocument({data: pdfData})

However, I am facing challenges in rendering the document properly. Any suggestions?

Answer №1

To display a PDF on a webpage, you can loop through its pages and render each page onto a canvas element.

First, create an HTML container where the canvas elements will be added:

<body>
    <div id="pdf-container"></div>
</body>

Then, utilize the functionality of PDF.js by using the .numPages and .getPage() methods like this:

async function renderPDFPage(pdf, pageNumber) {
    const page = await pdf.getPage(pageNumber);
    const scale = 2;
    const viewport = page.getViewport({scale});
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;
    document.getElementById('pdf-container').appendChild(canvas);
    await page.render({canvasContext: context, viewport});
}

async function renderPDFContent(pdf) {
    for (let i = 1; i <= pdf.numPages; i++) {
        await renderPDFPage(pdf, i);
    }
}

const loadedPdf = PDFJS.getDocument({data: pdfData});
renderPDFContent(loadedPdf);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to check if something is "ready" by using a combination of setTimeout and recursive functions?

I am currently working on a solution to determine when an asynchronous call is "ready" or not. I have a function that uses $.ajax which, upon success, sets a boolean variable in the global scope and some other data. Prior to making the ajax call, the boole ...

Can you help me convert this Mongoose code to use promises?

Using Mongoose's built-in promise support, I aim to streamline the process of a user sending a friend request to another user. However, even with careful error handling and sequencing in place, I find myself grappling with a slightly condensed pyramid ...

Eliminate items/attributes that include a certain term

Is there a way in Node.js to remove all fields or objects from a JSON file that have a specific word (e.g. "test") as their name, and then return the modified JSON file? Take a look at an example of the JSON file: { "name": "name1", "version": "0 ...

Exploring the process of passing an array as a function argument from PHP to JavaScript

I am looking for assistance in passing an array as a function argument from PHP to JS. The values I need are retrieved from a database. while ($rows = pg_fetch_array($qry)) { ?> <option value="<?php echo $rows[&ap ...

Eliminate the CSS triggered by a mouse click

Having some difficulty toggling the switch to change the background color. Struggling with removing the applied CSS and getting it to toggle between two different colored backgrounds. Code Sample: <!Doctype html> <html lang="en"> <head> ...

Creating a window.variable in a jQuery ajax callback using CoffeeScript

This particular project is built using rails and backbone-on-rails framework. Despite my efforts, I have been facing an issue with setting a global variable in a response callback function. Here's what I have attempted so far: 1) Initialization of t ...

Utilizing reactjs (MERN stack) to dynamically update content on a single page based on both URL parameters and database queries

Hello everyone, please excuse my English Imagine I have page1 with content in a database, and page2 with different content in another database. Both page1 and page2 share the same template, but I want to dynamically change the content based on the URL or ...

Encountering a 500 (Internal Server Error) while trying to insert data into the database through ajax

In the HTML code, I have a basic AJAX function that is triggered by a button press. The goal is to have the PHP script being called insert the JavaScript variable sent into a database. var myval = 'testuser'; // generated by PHP $.a ...

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...

Struggling to properly line up the baselines of navigation list items that are styled as circular elements using CSS

I have transformed my navigation menu into a series of CSS circles with text inside. The issue I am facing is that the text spills out unevenly based on the amount of content in each circle. To address this, I used a JavaScript solution to center-align the ...

What is more effective: utilizing document fragments or string concatenation for adding HTML to the DOM?

My task involves adding a collection of cards to the DOM. html <div class="card"> <div class="card-title">Card 1</div> <div class="card-subtext">This is card 1</div> </div> js let ...

The backbone module is experiencing formatting issues

I'm new to learning backbone.js. I've created the example below, but unfortunately, it's not functioning properly. Can someone please help me understand why? The goal is to simply display the name within my div element. (function($) { ...

Clearing the filename in a file type input field using React

When using this input field, only video files are accepted. If any other types of files are uploaded by enabling the "all files" option, an alert will be displayed. While this functionality is working correctly, a problem arises if a non-video file is adde ...

The functionality of $(selector).css() seems to be malfunctioning

I currently have an html div element stored in a variable var rows = ""; rows += "<div>1111 : Hi there</div>"; Despite multiple attempts, I have failed to add a background color to this div using the following methods: 1. $(rows).css({&apos ...

Issue with API showing return value as a single value instead of an array

My database consists of collections for Teachers and Classes. In order to fully understand my issue, it's important to grasp the structure of my database: const TeacherSchema = new Schema( { name: { type: String, required: true } ...

Tips for using the deferred method in ajax to enhance the efficiency of data loading from a php script

I recently discovered this method of fetching data simultaneously using ajax. However, I'm struggling to grasp the concept. Can someone please explain how to retrieve this data from a PHP script and then add it to a div similar to the example provided ...

How to Retrieve the Value from Bulma Datepicker in Vue.js

Currently, I am facing an issue with the bulma vuejs datepicker where I am unable to fetch the value as it keeps returning null. Here is the link to the datepicker that I am using. Here is a snippet of my <date-picker> component: <template> ...

Exploring the Use of data- Attributes in SVG Circle Elements

Looking for a way to dynamically update the color of a Circle element in your SVG when it is clicked? You can achieve this by using jQuery's .css() method in conjunction with the data-* attribute. CHECK OUT AN EXAMPLE: STYLING IN CSS svg { height ...

Create an overlay effect when hovering in a Vue.js application

I am currently facing a challenge in implementing text display on image hover in vue.js. I have tried to replicate this functionality using an array with multiple images following this example: here. Although my vue file is quite extensive, the crucial pa ...