【问题标题】:Node.js imagemagick Error: Too many pages in Page tree. while converting pdf to pngNode.js imagemagick 错误:页面树中的页面太多。在将pdf转换为png时
【发布时间】:2020-08-21 15:06:15
【问题描述】:

在将一些 pdf 转换为 png 缩略图时遇到了一些问题。

const outputStream = gm(Buffer.from(path, 'base64'))
        .selectFrame(0)
        .noProfile()
        .quality(60)
        .density(200)
        .background('white')
        .resize(600, 600)
        .setFormat('png');

Then I just got this error

Here you can see those pdfs

有什么方法可以修复这个错误或其他获取pdf缩略图的方法吗?

【问题讨论】:

  • 这些 pdf 包含表格,也许删除表格后它会起作用...

标签: javascript pdf imagemagick ghostscript imagemagick-convert


【解决方案1】:

Flag -flatten 解决了我的问题 :)

在某些文件格式(例如 Photoshop 的 PSD)中,复杂图像可能由“层”(独立图像)表示,必须将其合成才能获得最终再现。 -flatten 选项完成了这种组合。图像序列被替换为通过依次合成每个图像创建的单个图像,同时尊重合成运算符和页面偏移量。虽然 -flatten 可立即用于消除层,但它也可用作通用合成工具。

所以我只是生成flatten pdf,然后将其转换为图像

希望对大家有所帮助

const flattenPDFStream = gm(Buffer.from(path, 'base64'))
  .define('pdf:use-cropbox=true')
  .selectFrame(0)
  .flatten();

const flattenPDF = await gmToBuffer(flattenPDFStream);
const outputStream = gm(flattenPDF)
  .selectFrame(0)
  .noProfile()
  .quality(90)
  .background('white')
  .resize(400, 400)
  .setFormat('png');

GM转缓冲功能:

function gmToBuffer(data) {
  return new Promise((resolve, reject) => {
    data.stream((err, stdout, stderr) => {
      if (err) { return reject(err); }
      const chunks = [];
      stdout.on('data', chunk => {
        // Not best solution, but i need to control error message will not appear in pdf
        if (!chunk.includes('Error')) {
          chunks.push(chunk);
        } else {
          console.log(chunk.toString());
        }
      });
      // these are 'once' because they can and do fire multiple times for multiple errors,
      // but this is a promise so you'll have to deal with them one at a time
      stdout.once('end', () => { resolve(Buffer.concat(chunks)); });
      stderr.once('data', data => { reject(String(data)); });
    });
  });
}

【讨论】:

  • 也许没有必要创建 pdf,但至少它可以工作
猜你喜欢
  • 2011-07-06
  • 2022-01-22
  • 2011-08-03
  • 2014-06-19
  • 2022-10-20
  • 1970-01-01
  • 2016-10-26
  • 2011-06-10
  • 2014-06-06
相关资源
最近更新 更多