Matias Guzman
Matias Guzman

Reputation: 21

getDocument function on pdfjs-dist not working

hi I'm working on a site made with nodeJS, express (EJS), and PostgreSQL and I'm having trouble with the getDcoument function of pdfjs when I try to call it from my view.ejs. here is the code.

    <html lang="en">

<head>
  <meta charset="UTF-8">
  <title>PDF Viewer</title>
</head>

<body>
  <canvas id="pdf-canvas"></canvas>
  <script defer>
    window.onload = function () {
      const pdfjsLib = window.pdfjsLib;
      const loadingTask = pdfjsLib.getDocument('../textos/Padre-Rico-Padre-Pobre.pdf');
      loadingTask.promise.then(function (pdf) {
        // Obtén la primera página del PDF
        return pdf.getPage(1);
      }).then(function (page) {
        // Obtén el objeto canvas
        var canvas = document.getElementById("pdf-canvas");

        // Obtiene las dimensiones de la página
        var viewport = page.getViewport({ scale: 1 });

        // Establece las dimensiones del canvas
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        // Renderiza la página en el canvas
        page.render({
          canvasContext: canvas.getContext("2d"),
          viewport: viewport,
        });
      });
    };
  </script>
  </script>
</body>

</html>

is set the view like this in the index.js

const pdfjs = require('pdfjs-dist');
app.use(function (req, res, next) {
  const pdfjsLib = pdfjs;
  res.locals.pdfjsLib = pdfjsLib;
  next();
});
app.get('/lectura', function (req, res) {
  res.render('pdf_viewer');
});

the problem I'm having is that the getDcoument is not working for some reason, I work a loading task for the returning promise that the function is returning, but it just doesn't work. also, i checked with a console.log if the import was working and it seems that the view is correctly receiving the variable psdjsLib

if someone knows the reason for the error that getDocument doesn't exist tell me.

thank you so much for your help and support as always.

Upvotes: 0

Views: 1026

Answers (1)

Priestch
Priestch

Reputation: 109

Can you check where you set the window.pdfjsLib in your code?

const pdfjs = require('pdfjs-dist');
app.use(function (req, res, next) {
  const pdfjsLib = pdfjs;
  res.locals.pdfjsLib = pdfjsLib;
  next();
});
app.get('/lectura', function (req, res) {
  res.render('pdf_viewer');
});

I think the res.locals.pdfjsLib = pdfjsLib only set a variable in your node server, the browser can't see it, they are in different process.

Upvotes: 0

Related Questions