【问题标题】:pdf2json fail on passing a pdf from http requestpdf2json 无法从 http 请求传递 pdf
【发布时间】:2015-08-11 21:58:48
【问题描述】:

我正在尝试从 nodejs 脚本上的 PDF 文件中获取信息。

执行程序时出现此错误。

Error: stream must have data
at error (eval at <anonymous> (/Users/.../node_modules/pdf2json/lib/pdf.js:60:6), <anonymous>:193:7)
....

代码如下:

http.get(url_Of_Pdf_File, function(res) {
    var body = '';
    res.on('data', function (chunk) {
        body += chunk;
    });
    res.on('end', function() {
        // Here body have the pdf content
        pdf2table.parse(body, function (err, rows, rowsdebug) { // <-- Conflict
            // Code fail executing the previous line
            if(err) return console.log(err);
            toMyFormat(rows, function(data){
                console.log(JSON.stringify(data,null," "));
            });
        });
    });
});

我不确定为什么代码不起作用,因为如果我下载 PDF 文件,然后不是使用“http.request”方法获取文件,而是使用“fs.readFile”方法获取文件之前的代码有效。

fs.readFile(pdf_file_path, function (err, buffer) {
    if (err) return console.log(err);
    pdf2table.parse(buffer, function (err, rows, rowsdebug) {
        if(err) return console.log(err);
        console.timeEnd("Processing time");
        toMyFormat(rows, function(data){
            output(JSON.stringify(rows, null, " "));
        });
    });
});

我的问题是:

两个例子中'body'和'buffer'的内容有什么区别?

【问题讨论】:

    标签: javascript node.js pdf


    【解决方案1】:

    在第一个示例中,chunk 是缓冲区,您通过添加空正文 '' 将其转换为 utf8 字符串。当您使用字符串添加缓冲区时,它会转换为 utf8 并且您的原始数据会丢失。

    试试这个:

    var chunks = [];
    res.on('data', function (chunk) {
        chunks.push(chunk)
    });
    res.on('end', function() {
        // Here body have the pdf content
        pdf2table.parse(Buffer.concat(chunks), function (err, rows, rowsdebug) {
           //...
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-04
      • 2018-03-09
      • 2020-09-16
      • 2020-05-08
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多