首页 > 解决方案 > Hummus-recipe NPM:TypeError:无法开始解析 PDF 文件

问题描述

const HummusRecipe = require('hummus-recipe');
const pdfDoc = new HummusRecipe(inputFilePath, outputFilePath);

上面的代码将引发错误TypeError: Unable to start parsing PDF file in hummus-recipe library if the input PDF is invalid standard PDF Format。

标签: javascriptnode.jshummus.js

解决方案


最后,我创建了一个解决方案来处理hummus-recipe 中的此错误, 是由于hummus-recipe不接受的无效PDF 格式引起的。

exports.PDFConversionToHummusFormat = async (inputPath, outputPath) => {
const { PDFDocument } = require('pdf-lib');
const HummusRecipe = require('hummus-recipe');
const fileBytes = fs.readFileSync(inputPath);
const convertedPdf = await PDFDocument.load(fileBytes);
const pdfBytes = await convertedPdf.save();
fs.writeFileSync(inputPath, pdfBytes);
const pdfDoc = new HummusRecipe(inputPath, outputPath);
return pdfDoc;
};


const HummusRecipe = require('hummus-recipe');
let pdfDoc;
try {
        pdfDoc = new HummusRecipe(inputPath, outputPath);
} catch (error) {
  if (error.message === 'TypeError: Unable to start parsing PDF file') {
        pdfDoc = await PDFConversionToHummusFormat(inputPath, outputPath);
  } else {
      console.error('Error in Hummus Recipe Library ->', error);
  }
}

注意:您可以在https://www.pdfen.com/pdf-a-validator检查您的 PDF 是否有效,或者您可以在https://docupub.com/pdfconvert/将您的 PDF 转换为有效版本


推荐阅读