【问题标题】:Check if base64 string contains a valid PDF - and nothing else检查 base64 字符串是否包含有效的 PDF - 仅此而已
【发布时间】:2018-02-26 07:55:28
【问题描述】:

在我的网络应用程序中,用户只能上传图片和 PDF。这些来自前端到后端的 base64 字符串。在那里,在 Node.js 8.9 服务器上,我想做一些完整性检查,即测试我得到的 base64 字符串是否实际上只是图像和 PDF - 没有别的。

对于图像,这很容易。使用带有failOnError true 的sharp npm-module,正是我想要的:base64 字符串中的一个错误字符会导致失败并且输入将被拒绝。

但是,对于 PDF,我找不到类似的解决方案。我已经尝试过 pdf2json(无论如何,它似乎对我的要求过于强大),但无法通过转换为缓冲区来传递 base64 字符串。

【问题讨论】:

  • 您认为什么是“有效”的 PDF?任何以%PDF 开头的文件(因为如果不是,它根本就不是 PDF),或者只有那些不仅 do 以魔术字节开头,而且所有它的页面和内容可以在 JavaScript 中以少量处理器能力呈现而不会出现任何错误?

标签: node.js pdf base64


【解决方案1】:

我终于找到了一个完全符合我期望的 NPM 模块:hummusJS。 就我的测试而言,下面的代码有效:接受有效的 PDF,而拒绝无效的字符串。到目前为止没有发现任何性能影响。

var hummus = require('hummus');

let pdfBase64String = '<<base64 string here>>';
let bufferPdf;
try {
  bufferPdf = Buffer.from(pdfBase64String, 'base64');
  const pdfReader = hummus.createReader(new hummus.PDFRStreamForBuffer(bufferPdf));
  var pages = pdfReader.getPagesCount();
  if(pages > 0) {
      console.log("Parsable with Hummus and more than 0 pages. Seems to be a valid PDF!");
  }
  else {
      console.log("Unexpected outcome for number o pages: '" + pages + "'");
  }
}
catch(err) {
   console.log("ERROR while handling buffer of pdfBase64 and/or trying to parse PDF: " + err);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-26
    • 2017-01-20
    • 2010-12-19
    • 1970-01-01
    • 2020-07-16
    • 2014-03-02
    • 2011-01-25
    相关资源
    最近更新 更多