0

我想使用用于 nodejs 的 SendGrid 将受密码保护的 pdf 作为电子邮件附件发送。

我尝试使用密码保护我的 pdf qpdf。这将输出一个在本地受密码保护的新 pdf 文件。然后,我尝试从此文件中读取数据,并将其作为 SendGrid 文档的附件内容发送。

const fs = require('fs');
const qpdf = require('node-qpdf');

const options = {
  keyLength: 128,
  password: 'FAKE_PASSWORD',
  outputFile: filename
}
const attachments = []

await new Promise(res => {
  const writeStream = fs.createWriteStream('/tmp/temp.pdf');
  writeStream.write(buffer, 'base64');
  writeStream.on('finish', () => {
      writeStream.end()
  });
  res();
})
await qpdf.encrypt('/tmp/temp.pdf', options);
const encryptedData = await new Promise(res => {
  const buffers = []
  const readStream = fs.createReadStream('/tmp/temp.pdf');
  readStream.on('data', (data) => buffers.push(data))
  readStream.on('end', async () => {
    const buffer = Buffer.concat(buffers)
    const encryptedBuffer = buffer.toString('base64')
    res(encryptedBuffer)
  })
})
attachments.push({
  filename,
  content: encryptedData,
  type: 'application/pdf',
  disposition: 'attachment'
})

我收到带有 pdf 作为附件的电子邮件,但它没有密码保护。这可能与这两个库有关吗?

4

1 回答 1

1

看起来您发送的是未加密的文件。也许这会起作用?

const fs = require('fs');
const qpdf = require('node-qpdf');

const options = {
  keyLength: 128,
  password: 'FAKE_PASSWORD'
}
const attachments = []

await new Promise(res => {
  const writeStream = fs.createWriteStream('/tmp/temp.pdf');
  writeStream.write(buffer, 'base64');
  writeStream.on('finish', () => {
      writeStream.end()
      res(); // CHANGED
  });
})
await qpdf.encrypt('/tmp/temp.pdf', options, filename); // CHANGED
const encryptedData = await new Promise(res => {
  const buffers = []
  const readStream = fs.createReadStream(filename); // CHANGED
  readStream.on('data', (data) => buffers.push(data))
  readStream.on('end', async () => {
    const buffer = Buffer.concat(buffers)
    const encryptedBuffer = buffer.toString('base64')
    res(encryptedBuffer)
  })
})
attachments.push({
  filename,
  content: encryptedData,
  type: 'application/pdf',
  disposition: 'attachment'
})

于 2019-09-28T12:04:42.097 回答