Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Cambie la entrada del archivo pdf para pasarme la ruta exacta

Encontré este código que selecciona un archivo pdf en una entrada y devuelve la cantidad de páginas que tiene. Resulta que con esta forma de leer pdfs es la única que he encontrado que lee absolutamente todos los pdfs correctamente.

Lo que estoy tratando de hacer es aislar el código que lee el archivo pdf, para poder pasarle la ruta al archivo en lugar de usar la entrada. Es para luego leer todos los archivos en una carpeta y mostrar el número total de páginas.

Pero no puedo averiguar dónde exactamente tendría que pasar la ruta al archivo pdf.

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PDF.js Example to Count Number of Pages inside PDF Document</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <h1 class="text-center">Count Pages inside PDF Document</h1> <div class="form-group container"> <input type="file" accept=".pdf" required id="files" class="form-control"> </div> <br><br> <h1 class="text-primary container" id="result"></h1> </div> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.12.313/pdf.min.js"></script> <script> let inputElement = document.getElementById('files') inputElement.onchange = function(event) { var file = event.target.files[0]; //Step 2: Read the file using file reader var fileReader = new FileReader(); fileReader.onload = function() { //Step 4:turn array buffer into typed array var typedarray = new Uint8Array(this.result); //Step 5:pdfjs should be able to read this const loadingTask = pdfjsLib.getDocument(typedarray); loadingTask.promise.then(pdf => { document.getElementById('result').innerHTML = "The number of Pages inside pdf document is " + pdf.numPages // The document is loaded here... }); }; //Step 3:Read the file as ArrayBuffer fileReader.readAsArrayBuffer(file); } </script> </html>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Necesitas 2 modificaciones para que funcione. Agregue el atributo "múltiple" a la entrada para permitir que el usuario seleccione múltiples archivos pdf.

 <input type="file" multiple accept=".pdf" required id="files" class="form-control">

Y luego recorra la matriz de archivos para calcular el número de páginas en cada uno:

 [].forEach.call(event.target.files, file => {

Actualización: se han agregado dos cambios adicionales.

1. Debemos restablecer la entrada del archivo al final del bucle. De lo contrario, solo funcionará una vez y luego se detendrá.

 // clear file selector to allow reuse event.target.value = "";

2. También debemos establecer el valor "workerSrc" para evitar un mensaje de advertencia de la consola. Más detalles sobre eso aquí .

 pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.worker.min.js';

Ejecute el fragmento de código para ver cómo funciona (mantenga presionada la tecla Mayús para seleccionar varios archivos pdf):

 let inputElement = document.getElementById('files') inputElement.onchange = function(event) { [].forEach.call(event.target.files, file => { //var file = event.target.files[i]; //Step 2: Read the file using file reader var fileReader = new FileReader(); fileReader.onload = function() { //Step 4:turn array buffer into typed array var typedarray = new Uint8Array(this.result); //Step 5:pdfjs should be able to read this const loadingTask = pdfjsLib.getDocument(typedarray); loadingTask.promise.then(pdf => { document.getElementById('result').innerHTML += "<li>" + file.name + " has " + pdf.numPages + "pages</li>"; // The document is loaded here... }); }; //Step 3:Read the file as ArrayBuffer fileReader.readAsArrayBuffer(file); }) // clear file selector to allow reuse event.target.value = ""; } // Must set worker to avoid error: Deprecated API usage: No "GlobalWorkerOptions.workerSrc" specified. pdfjsLib.GlobalWorkerOptions.workerSrc = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.worker.min.js';
 <div class="container"> <h4 class="text-center">Count Pages inside PDF Document</h4> <div class="form-group container"> <input type="file" multiple accept=".pdf" required id="files" class="form-control"> </div> <br><br> <ol class="text-primary container" id="result"></ol> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.7.570/pdf.min.js" integrity="sha512-g4FwCPWM/fZB1Eie86ZwKjOP+yBIxSBM/b2gQAiSVqCgkyvZ0XxYPDEcN2qqaKKEvK6a05+IPL1raO96RrhYDQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

about 4 years ago · Juan Pablo Isaza Report

0

no puedes

Los navegadores no le permiten acceder a rutas locales en la computadora de un usuario por razones de seguridad.

El navegador no llega a saber que el pdf está en /home/USERNAME/confidentialdocs/file.pdf , solo obtiene un blob de datos con un nombre de archivo dado.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!