将PDF上载到Amazon S3并在浏览器中显示

时间:2018-06-21 14:42:27

标签: node.js amazon-s3

const fs = require('fs');

const pdf = require('html-pdf');

const AWS = require("aws-sdk");

//Read html file
function readHTMLfile(path, callback) {

    fs.readFile(path, {encoding: 'utf-8'}, function(err, html) {

        if(err) {

            callback(err);
        }

        else {

            callback(null, html)

        }

    })

}

//importing HTML file
readHTMLfile(__dirname + '/Nda.html', function(err, html) {

    if(err) {
        console.log('Error: ',err)
    }

    else {
        var handlebars = require("handlebars");
        var template = handlebars.compile(html);
        var replacables = {
            url: 'http://politicalmemorabilia.com/wp-content/uploads/2014/10/2000px-Aaron_Burr_signature.png'
        } 
        var HtmlToSend = template(replacables);
        //pdf.create(HtmlToSend).toStream(function(err, stream){
        pdf.create(HtmlToSend).toBuffer(function(err, buf){
            if(err){
                return console.log(err);    
            } 
            else {
                console.log('This is a buffer:', buf);
                //stream.pipe(fs.createWriteStream('./Nda2.pdf'));
              //var readableStream = fs.readFileSync('./Nda2.pdf', 'base64')
              // console.log('Readable Stream: ',readableStream)
              // var buf = new Buffer('readableStream', 'base64')
              // console.log('Buffer String ',buf.toString())
              //console.log('Readable Stream ',readableStream)
              //console.log('Pdf Content', ./Nda2.pdf);

                AWS.config.update({
                    accessKeyId: "AKIAIRJAKT756L72NPBA",
                    secretAccessKey: "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"
              });

            var s3Bucket = new AWS.S3({ params: { Bucket: "vizitor-profilepicture" } });

                var options = {
                Key: `nda/Nda`,
                Body: 'buf',
                ContentEncoding: "buffer",
                //ContentDisposition: "inline",
                ContentType: "application/pdf"
                };
                s3Bucket.upload(options, function(err, data) {
                  if (err) {
                    console.log(err);
                    console.log("Error uploading data: ", data);
                  } else {
                    console.log('Data: ',data)
                    console.log("data: ", data.Location);
                    console.log("succesfully uploaded pdf!");
                  }
                });     
            }
        });
    }
})

我正在导入HTML文件,并使用“ html-pdf”模块将其转换为pdf,并使用把手将动态URL嵌入HTML文件中。然后,我将HTML文件转换为缓冲区,并希望以pdf格式上传到Amazon s3。为此,我在主体选项中使用了缓冲区。我得到了正确的缓冲区,但是当我将pdf文件上传到amazon s3时,生成了一个链接,但是在浏览器中打开链接时出现错误“无法加载pdf”

我已经制作了s3桶以供公众查看,所以这里不是问题。

0 个答案:

没有答案