如何使用Node.js读取.pdf文件的内容?

5

我有一个自动化PDF内容的场景。如何在nodejs中检索PDF文件的内容。

我完全被卡住了。虽然有一些关于pdf2jsonajsonreader的帖子,但它们对我不起作用。任何帮助都将不胜感激。

var pdfParser = new PDFParser();
fs.readFile(pdfFilePath, function(err, pdfBuffer) {
    pdfParser.parseBuffer(pdfBuffer);
}, function(pdfBuffer){
    pdfParser.parseBuffer(pdfBuffer);
})

错误:无效的参数数组,需要 .data 或 .url 在 FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:445:3)


你好。你是否发现这两个库存在特定的问题? - Sebas
嗨Sebas,我已经将代码片段和错误添加到了问题本身。请看一下并告诉我是否有任何遗漏,因为我是nodejs的新手。 - mfsi_sudhansu
我不确定错误是来自于pdfParser还是fs对象。 - Sebas
2个回答

2
 const fs = require("fs");
 const PdfReader = require('pdfreader').PdfReader;
  fs.readFile("E://file streaming in node js//demo//read.pdf", (err, pdfBuffer) => {
    // pdfBuffer contains the file content
    new PdfReader().parseBuffer(pdfBuffer, function(err, item){
       if (err)
           callback(err);
        else if (!item)
            callback();
         else if (item.text)
            console.log(item.text);
          });
       });

1
我找到了答案,而且它完美地运行。通过运行以下命令安装fs和pdf2json。 npm install pdf2jsonnpm install fs
var fs = require('fs');
var PDFParser = require('pdf2json');
var path = osHomedir();
var homepath = path.replace(new RegExp('\\' + path.sep, 'g'), '/');
var pdfFilePath = homepath + '/Downloads/' + 'filename.pdf';

if (fs.existsSync(pdfFilePath)) {
  //Read the content of the pdf from the downloaded path
  var pdfParser = new PDFParser(browser, 1);
  pdfParser.on("pdfParser_dataError", function (errData) {
     console.error(errData.parserError)
  });
  pdfParser.on("pdfParser_dataReady", function (pdfData) {
  //console.log('here is the content: '+pdfParser.getRawTextContent());
  browser.assert.ok(pdfParser.getRawTextContent().indexOf(textToVerify) > -1);
  });

  pdfParser.loadPDF(pdfFilePath);
} else {
    console.log('OOPs file not present in the downloaded folder');
    //Throw an error if the file is not found in the path mentioned
    browser.assert.ok(fs.existsSync(pdfFilePath));
}

3
请问您这里的"browser"是指什么?我也在使用同样的东西,但是遇到了这个错误:ReferenceError: browser is not defined。 - Vishnu Chauhan
你需要解释一下 browser 变量是什么。 - Wayne Smallman
https://www.npmjs.com/package/pdf2json 的文档是使用 pdf2json 的不错起点。 - therightstuff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接