将PDF转换成PNG在谷歌云存储(Convert PDF to PNG on Google Clou

2019-09-26 16:19发布

我想创建从其中一个谷歌存储桶上传不同的文件中PNG缩略图。 就目前而言,我针对图像和PDF文件。 对于图像的功能工作正常,但对于PDF文件,我不能使它发挥作用。 这个想法是从桶下载文件,做的工作,然后上传新文件(PNG缩略图),以桶。

所以我做了检查,以查看上传的文件类型,如果该文件是一个图像我做与转换createImageFromImage功能,如果它是PDF,我使用createImageFromPDF

主功能:

const gm = require('gm').subClass({imageMagick: true});
const fs = require('fs');
const path = require('path');
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const im = require('imagemagick');

exports.generatePreviewImage = event => {
  const object = event.data || event; // Node 6: event.data === Node 8+: event

  const file = storage.bucket(object.bucket).file(object.name);
  const filePath = `gs://${object.bucket}/${object.name}`;

  // Ignore already-resized files (to prevent re-invoking this function)
  if (file.name.endsWith('-thumb.png')) {
    console.log(`The image ${file.name} is already resized.`);
    return;
  } else {
    console.log(`Analyzing ${file.name}.`);
    //  Check the file extension
    if(object.contentType.startsWith('image/')) {  //  It's an image
      console.log("This is an image!")
      return createImageFromImage(file);
    } else if (object.contentType === 'application/pdf') {  //  It's a PDF
      console.log("This is a PDF file!")
      return createImageFromPDF(file);
    } else {
      return;
    }
  }
};

createImageFromImage(文件) - 它的工作原理

function createImageFromImage(file) {
  const tempLocalPath = `/tmp/${path.parse(file.name).base}`;

  // Download file from bucket.
  return file
    .download({destination: tempLocalPath})
    .catch(err => {
      console.error('Failed to download file.', err);
      return Promise.reject(err);
    })
    .then(() => {
      console.log(
        `Image ${file.name} has been downloaded to ${tempLocalPath}.`
      );

      // Resize the image using ImageMagick.
      return new Promise((resolve, reject) => {
        gm(tempLocalPath)
          .resize(250)
          .setFormat('png')
          .write(tempLocalPath, (err, stdout) => {
            if (err) {
              console.error('Failed to resize the image.', err);
              reject(err);
            } else {
              resolve(stdout);
            }
          });
      });
    })
    .then(() => {
      console.log(`Image ${file.name} has been resized.`);

      //  Get the name of the file without the file extension and mark the result as resized, to avoid re-triggering this function.
      const newName = `${path.parse(file.name).name}-thumb.png`;

      // Upload the Blurred image back into the bucket.
      return file.bucket
        .upload(tempLocalPath, {destination: newName})
        .catch(err => {
          console.error('Failed to upload resized image.', err);
          return Promise.reject(err);
        });
    })
    .then(() => {
      console.log(`Resized image has been uploaded to ${file.name}.`);

      // Delete the temporary file.
      return new Promise((resolve, reject) => {
        fs.unlink(tempLocalPath, err => {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    });
}

createImageFromPDF(文件) - 不工作

function createImageFromPDF(file) {
  const tempLocalPath = `/tmp/${path.parse(file.name).base}`;

  return file
    .download({destination: tempLocalPath}) // Download file from bucket.
    .catch(err => {
      console.error('Failed to download file.', err);
      return Promise.reject(err);
    })
    .then(() => { // Convert the file to PDF.
      console.log(`File ${file.name} has been downloaded to ${tempLocalPath}.`);

      return new Promise((resolve, reject) => {

        im.convert([tempLocalPath, '-resize', '250x250', `${path.parse(file.name).name}-thumb.png`], 
          function(err, stdout) {
            if (err) {
              reject(err);
            } else {
              resolve(stdout);
            }
          });
      });
    })
    .then(() => { //  Upload the new image to the bucket
      console.log(`File ${file.name} has been resized.`);

      //  Get the name of the file without the file extension and mark the result as resized, to avoid re-triggering this function.
      const newName = `${path.parse(file.name).name}-thumb.png`;

      // Upload the Blurred image back into the bucket.
      return file.bucket
        .upload(tempLocalPath, {destination: newName})
        .catch(err => {
          console.error('Failed to upload resized image.', err);
          return Promise.reject(err);
        });
    })
    .then(() => { // Delete the temporary file.
      console.log(`Resized image has been uploaded to ${file.name}.`);

      return new Promise((resolve, reject) => {
        fs.unlink(tempLocalPath, err => {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    });
}

我得到一个错误im.convert它说: Command failed: convert: no images defined 'test1-thumb.png' @ error/convert.c/ConvertImageCommand/3210. 我不知道这是创建从PDF文件中的PNG缩略图以正确的方式,我想没有成功的其他解决方案。 请指教一下我做错了。 谢谢!

Answer 1:

我只是意识到gm可处理的ImageMagick,你已经做到这一点(使用.subClass({imageMagick: true})那么,为什么与其他包装费心呢?

反正,我只是尝试这样做:

const gm = require('gm').subClass({imageMagick: true});
const file = './test.pdf';
gm(file)
.resize(250, 250)
.setFormat('png')
.write(file, (err) => {
    if (err) console.log('FAILED', err);
    else console.log('SUCCESS');
});

它指出一些“未授权”错误,因为PDF处理最初禁用-看到这 -但我已经编辑后/etc/ImageMagick*/policy.xml的建议,它完美地工作。



文章来源: Convert PDF to PNG on Google Cloud Storage