Interactive preview of PDFs with pdf.js adaptation

How can I update my PDF preview when resizing the window? Currently, the canvas resizes but the PDF preview remains the same size. I am struggling to find a solution for this.

    var myState = {
        pdf: null,
        currentPage: 1,
        zoom: 1
    }

function domLoad() {
    myState.pdf.getPage(myState.currentPage).then((page) => {
 
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');

        var viewport = page.getViewport(myState.zoom);

        var heightRatio = 842 / 595;
        canvas.width = ((((595/941.39)*100)*window.innerWidth)/100);
        canvas.height = ((((595/941.39)*100)*window.innerWidth)/100) * heightRatio;

        page.render({
            canvasContext: ctx,
            viewport: viewport
        });
        
    updateCanvas(canvas);
    });
}


document.addEventListener('DOMContentLoaded', function(event) {
     
        pdfjsLib.getDocument('https://www.ecam.fr/wp-content/uploads/sites/3/2016/06/Exemple-fichier-PDF-1.pdf').then((pdf) => {
     
            myState.pdf = pdf;
            render();

        });

        function render() {
            domLoad();
        }
  })


  addEventListener("resize", (event) => {

    domLoad();

  });

  function updateCanvas(canvas) {
    
    var canvasParent = document.getElementById("pdf_container");
    var previousCanvas = canvasParent.querySelector('canvas');
    if(previousCanvas !== null) {
        canvasParent.removeChild(previousCanvas);
    }
    canvasParent.appendChild(canvas);
  }
body { width: 100%; height: 100%; }
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.min.js"></script>
</head>

<body>
<a id="pdf_container" class="pdf_container" href="https://www.ecam.fr/wp-content/uploads/sites/3/2016/06/Exemple-fichier-PDF-1.pdf">
         </a>
</div>
</body>

I have attempted to resize the canvas and update it during window resizing by removing and re-adding it with a new size. However, the PDF preview inside does not adjust accordingly.

Answer №1

Reference : Here is the solution

Fortunately, I was able to resolve this issue by focusing on the viewport. The main problem lied in how getViewport method was being utilized:

var viewport = page.getViewport(canvas.width / page.getViewport(myState.zoom).width);

    var myState = {
        pdf: null,
        currentPage: 1,
        zoom: 1
    }

function loadDocument() {
    myState.pdf.getPage(myState.currentPage).then((page) => {
 
        var canvas = document.createElement('canvas');
        canvas.id = 'pdf_renderer';
        var ctx = canvas.getContext('2d');

        console.log(page);
        var heightRatio = 842 / 595;
        canvas.width = ((((595/941.39)*100)*window.innerWidth)/100);
        canvas.height = ((((595/941.39)*100)*window.innerWidth)/100) * heightRatio;
 
        var viewport = page.getViewport(canvas.width / page.getViewport(myState.zoom).width);
        page.render({
            canvasContext: ctx,
            viewport: viewport
        });
        
    updateCanvas(canvas);
    });
}


document.addEventListener('DOMContentLoaded', function(event) {
     
        pdfjsLib.getDocument('../documents/cv.pdf').then((pdf) => {
     
            myState.pdf = pdf;
            render();

        });

        function render() {
            loadDocument();
        }
  })


  addEventListener("resize", (event) => {

    loadDocument();

  });

  function updateCanvas(canvas) {
    
    var canvasParent = document.getElementById("pdf_container");
    var previousCanvas = canvasParent.querySelector('canvas');
    if(previousCanvas !== null) {
        canvasParent.removeChild(previousCanvas);
    }
    canvasParent.appendChild(canvas);
  }

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

Looking to dynamically adjust row color based on status using ANGULAR 4

In my table, I have 6 columns: name, email, phone, company, status_1, and status_2. Both status_1 and status_2 can have two options: "1" or "0." My Requirement: I want to change the color of the row based on the following logic: if(status_1 is "1" ...

A webpage styled with w3.css featuring text without any underline

I am currently using w3.css but I'm facing an issue where some of my hyperlinks have underlines while others do not. My goal is to remove all underlines from the hyperlinks in the content below: <ul class="w3-ul w3-white"> <a class="" href=" ...

working with html data in a bootstrap modal using javascript

Utilizing an id, I pass data to a bootstrap modal and link that id with stored data. $("#fruit").html($(this).data("fruit")); In addition, I am appending data to the bootstrap modal $('#mymodal').find('.modal-body').append('< ...

What is the best way to set a parent element's width to be the same as one of

Is it possible to make the width of div.main match that of table.tbl2? In this scenario, I want inline4 to be on the second line and for the width of div.main to be identical to the width of table.tbl2. .container { text-align: center; } .main { di ...

What could be causing the malfunction of the map function, despite the code appearing to be correct?

I have encountered an issue in my React functional component where I am trying to display a list of notifications. The useEffect() function is being called to generate the "data" which should then be displayed on the page. The code seems to be running fine ...

Generate a customizable URL for my search bar

I have developed a single HTML page with full AJAX functionality, displaying all content including form submits, main page, form results, and more through various DOM manipulations. The issue I am currently encountering is related to a search box where use ...

Is there a way to verify if an HTML popover is currently displayed?

Is there a method using JavaScript to determine if the popover is open when utilizing the new popover API? <button popovertarget="pop">Trigger the popover</button> <div popover id="pop">This is the content of the popover!</div> ...

I am consistently encountering the error message: "Error: Unable to locate module './framer'"

I've been running into the same issue repeatedly. I'm in the process of creating a website for a barbershop and I'm attempting to integrate events into a Google calendar using the Google API. I've installed googleapis and framer, but I ...

Is there a way to maintain the second form's state when the page is refreshed using Vue.js?

I have a challenge in creating a web-app with only 2 pages. The first page requires filling out forms across two stages, but I am unable to create separate pages for this purpose. Is there a way to display two forms on one page and remain on the second for ...

Implementing Material UI datetime-local feature with no minute selection

Is there a way to hide minutes in a TextField with type = datetime-local? <TextField label="From" type="datetime-local" InputLabelProps={{ shrink: true, }} /> This is how it appears on my end: screenshot ...

Something is overriding the style created by makestyle material UI that I had implemented

How can I increase the importance of my makeStyles classes over default Material UI styles? Here is my code: import { createTheme, ThemeProvider } from '@mui/material/styles'; import { makeStyles, createStyles } from '@mui/styles'; co ...

JavaScript can be used to extract a specific value from a SOAP response

In order to extract the Patient ID (PATAA000000040) from the SOAP response below using JavaScript and insert it into a Mirth destination, we need to target the value under the livingSubjectId tag. It's important to note that this tag may repeat, but w ...

how to load CSS and JS files on certain views in Laravel 5.2

Currently, I am facing a situation where I need to ensure that the CSS and JS files are loaded only on specific views in Laravel 5.2. Due to my boss's decision to eliminate RequireJS for loading JS files on our blade templates, we are now exploring a ...

Making <div> elements responsive by rearranging their display order using CSS in media queries, troubleshooting issues with floats, and adjusting font sizes

I'm currently working on a webpage located at: On this page, there is a containing division with 5 elements inside. They are floated left in order to align vertically, but I am facing some challenges when it comes to adjusting my CSS for media querie ...

Design a basic button that does not adopt any of the CSS attributes from Bootstrap

Currently, my styling is done using Bootstrap.css. However, I am interested in creating a straightforward <button> without incorporating any of the CSS properties from Bootstrap. Specifically for this <button>, I do not want it to inherit any ...

How to refresh component after clearing dates in Vuetify datepicker

Currently, I am working with a datepicker in Vuetify JS and I need to find a way to clear the dates and refresh the component. In addition, there is a v-data table that is filtered based on the dates range array. I am exploring options to either add a &ap ...

Can one open a unique custom pop-up before the window is about to close?

Seeking a way to create a pop-up confirmation dialog for users when they try to log out or stay on the page while logged in. I attempted using the code below, but haven't been able to find the correct solution: window.onbeforeunload = function (e) { ...

Pick the final offspring of the HTML element that is not assigned to a specific class

Currently, I am attempting to target the final element of a child that lacks a specific class. You can view my progress on this JSFiddle. <aside class="col2"> <div class="infobox teal"></div> <div class="infobox mediumbrown"&g ...

I encountered an issue while trying to use jshint with a simple hello world script, receiving the error message: "line 0, col 0, Bad option: 'script'."

This is a basic introduction to my coding journey. function greet() { return 'Hello world'; } Here is the jshint setup I am using: { "browser": true, "browserify": true, "devel": true, "script" ...

Email confirmation based on checkbox status in PHP contact form

My goal is to make my file called send_form_email.php work by sending an email with a way to indicate which checkboxes are checked. Right now, it sends the form successfully, but doesn't include any information about the checked items. The following ...