首页 > 解决方案 > 解决方案使用 Node JS 将 PDF 转换为图像 Centos Stream 8

问题描述

为了实现将 PDF 转换为图像的过程自动化的目标,我遇到了许多障碍,例如“不支持 Linux”、“pdfToCairo 不是函数” 一些库使用 poppler 但 Centos 不会自动安装必要的依赖项。

下面是使用的库和脚本,感谢 pdf2img-promises 及其创建者。

标签: node.jscentos

解决方案


解决方案:

依赖项 这些依赖项必须安装在您的服务器上,因为 gm 包使用它们:

GraphicsMagick GhostScript

 $ yum  install GraphicsMagick ghostscript

安装

 $ npm install pdf2img-promises

用法

 const fs      = require('fs');
    const path    = require('path');
    const Pdf2Img = require('pdf2img-promises');
    
    let input   = __dirname + '/test.pdf';
    let fileName = 'test';
    
    let converter = new Pdf2Img();
    
    // The event emitter is emitting to the file name
    converter.on(fileName, (msg) => {
        console.log('Received: ', msg);
    });

converter.setOptions({
  type: 'png',                                // png or jpg, default jpg
  size: 1024,                                 // default 1024
  density: 600,                               // default 600
  quality: 100,                               // default 100
  outputdir: __dirname + path.sep + 'output', // output folder, default null (if null given, then it will create folder name same as file name)
  outputname: fileName,                       // output file name, dafault null (if null given, then it will create image name same as input name)
  page: null                                  // convert selected page, default null (if null given, then it will convert all pages)
});

converter.convert(input)
  .then(info => {
    console.log(info);
  })
  .catch(err => {
    console.error(err);
  })

它将返回拆分和转换的图像文件数组。

{ result: 'success',
  message: 
   [ { page: 1,
       name: 'test_1.jpg',
       size: 17.275,
       path: '/output/test_1.jpg' },
     { page: 2,
       name: 'test_2.jpg',
       size: 24.518,
       path: '/output/test_2.jpg' },
     { page: 3,
       name: 'test_3.jpg',
       size: 24.055,
       path: '/output/test_3.jpg' } ] }

https://npm.io/package/pdf2img-promises


推荐阅读