Buenos días. ¿Hay alguna forma de extraer la imagen del archivo pdf usando la biblioteca jspdf u otras bibliotecas npm? ¿Quizás hay algunas soluciones para reaccionar?
Estaré agradecido por la ayuda.
Obtuve todas las imágenes del archivo pdf usando las bibliotecas 'pdf-lib' y 'stream-mime-type'. Aquí está la función en sí, espero que sea útil.
const {PDFDocument} = require('pdf-lib'); const fs = require('fs') const {getMimeType} = require('stream-mime-type') const createJpgFile = require('./utils/createJpgFile.js') const path = require("path"); async function getImageFromPdf() { const existingPdfBytes = await new Promise((resolve, reject) => { fs.readFile(path.join(rootPath, 'test.pdf'), (err, result) => { if (err) { reject(err) } if (!err) { resolve(result) } }) }) const pdfDoc = await PDFDocument.load(existingPdfBytes) const pages = pdfDoc.getPages() const result = [] pages[0].doc.context.indirectObjects.forEach(el => { if (el.hasOwnProperty('contents')) result.push(el.contents) }) const mime = await Promise.all(result.map(async (el) => { return new Promise(async (resolve) => { const res = await getMimeType(el) if (res) { resolve(res) } }) })); await Promise.all(mime.map(async (el, i) => { if (el.mime === 'image/jpeg') { return new Promise(async (resolve) => { const res = await writeJpgFile(result[i], `image-${i}`, 'jpg') resolve(res) }) } }) ) }agregar: también escribí una función que analiza imágenes jpg de un archivo pdf sin usar bibliotecas de terceros. La función encuentra el comienzo de las imágenes jpg por firma. Para otros formatos, debe usar otras firmas.
const parserJpegFromPdf = async () => { const existingPdfBytes = await getArrayBufferFromPdf() const convertedBuffer = new Uint8Array(existingPdfBytes) const firstBeginSignatureSymbol = parseInt('ff', 16) const secondBeginSignatureSymbol = parseInt('d8', 16) const indexesStartSignatureImage = [] convertedBuffer.forEach((el, i) => { if (el === firstBeginSignatureSymbol && convertedBuffer[i + 1] === secondBeginSignatureSymbol && convertedBuffer[i + 2] === firstBeginSignatureSymbol && (convertedBuffer[i + 3] === parseInt('e0', 16) || convertedBuffer[i + 3] === parseInt('e1', 16) || convertedBuffer[i + 3] === parseInt('e2', 16) || convertedBuffer[i + 3] === parseInt('e3', 16) || convertedBuffer[i + 3] === parseInt('e8', 16))) { indexesStartSignatureImage.push(i) } }) const resultSlicedCodeImage = indexesStartSignatureImage.reduce((arr, el) => { arr.push(convertedBuffer.slice(el)); return arr }, []) await Promise.all(resultSlicedCodeImage.map(async (el, i) => { await createFile(el, `test_image_${i}`, 'jpeg') })) }