2017-07-26 157 views
3

我是JavaScript新手,我试图使用pdfkit从firebase函数创建PDF文件。以下是我的功能代码。在Firebase云端函数中创建PDF

const pdfkit = require('pdfkit'); 
const fs = require('fs'); 

exports.PDFTest = functions.https.onRequest((req, res) => { 

var doc = new pdfkit(); 

var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in...'; 

doc.y = 320; 
doc.fillColor('black') 
doc.text(loremIpsum, { 
paragraphGap: 10, 
indent: 20, 
align: 'justify', 
columns: 2 
}); 

doc.pipe(res.status(200)) 

}); 

该函数启动但发生超时错误。 这是在Firebase中创建PDF文件的最佳方式吗? 我有一些我想要制作成pdf文件的html。

回答

1

只是工作这也为保存PDF在它的工作原理是这样

const myPdfFile = admin.storage().bucket().file('/test/Arbeitsvertrag.pdf'); 
const doc = new pdfkit(); 
const stream = doc.pipe(myPdfFile.createWriteStream()); 
doc.fontSize(25).text('Test 4 PDF!', 100, 100); 
doc.end(); 

return res.status(200).send(); 

猜你应该等待,直到流被关闭,并听取了错误和事物的存储,但是这是第一个工作我能够做的例子,现在正在研究如何从存储中获取图像到PDF中。

+0

我结束了使用HTML,PDF,对我来说真是棒极了。我会接受你的回答。 – user1184205

1

我也在此工作,下面您可以找到一个云功能示例,该示例从托管在Firebase存储上的模板HTML创建PDF文件。 它使用Hanldebars将一些数据应用到模板,然后在Firebase存储上再次上传。 我在这里使用了node-html-pdf。

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
const pdf = require('html-pdf'); 
const gcs = require('@google-cloud/storage')({ 
    projectId: '[YOUR PROJECT ID]', 
    //key generated from here https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk?authuser=1 
    keyFilename: '[YOUR KEY]' 
}); 
const handlebars = require('handlebars'); 
const path = require('path'); 
const os = require('os'); 
const fs = require('fs'); 
const bucket = gcs.bucket('[YOUR PROJECT ID].appspot.com'); 

admin.initializeApp(functions.config().firebase); 

exports.helloWorld = functions.https.onRequest((request, response) => { 
    // data to apply to template file 
    const user = { 
    "date": new Date().toISOString(), 
    "firstname" : "Guillaume", 
    }; 
    const options = { 
    "format": 'A4', 
    "orientation": "portrait" 
    }; 
    const localTemplate = path.join(os.tmpdir(), 'localTemplate.html'); 
    const localPDFFile = path.join(os.tmpdir(), 'localPDFFile.pdf'); 

    bucket.file('template.html').download({ destination: localTemplate }).then(() => { 
    console.log("template downloaded locally"); 
    const source = fs.readFileSync(localTemplate, 'utf8'); 
    const html = handlebars.compile(source)(user); 
    console.log("template compiled with user data", html); 

    pdf.create(html, options).toFile(localPDFFile, function(err, res) { 
     if (err){ 
     console.log(err); 
     return response.send("PDF creation error"); 
     } 
     console.log("pdf created locally"); 

     return bucket.upload(localPDFFile, { destination: user.name + '.pdf', metadata: { contentType: 'application/pdf'}}).then(() => { 
     response.send("PDF created and uploaded!"); 
     }).catch(error => { 
     console.error(error); 
     response.send("PDF created and uploaded!"); 
     }); 
    }); 
    }); 
}); 

希望这将有助于下一个这样:)

+0

嗨Guillaume!什么包含在template.html里面? – Mario

+0

@Mario根据http://handlebarsjs.com/文档,您必须使用html模板。在这种情况下类似的东西是确定: <元的charset = “utf-8”> <表边界=“1”> ​​ {{日期}} ​​ { {姓名}} 然而,AF ter模板已经明显正确编译,我得到以下错误...错误:html-pdf:PDF生成超时。 Phantom.js脚本没有退出。 –

0

我试图Guillaume的建议,它几乎让我在那里。不幸的是,Phantomjs正在退出,没有完成。

我最终通过结合纪尧姆的解决方案和https://phantomjscloud.com(和他们的图书馆)解决了这个问题。现在,它的工作就像一个魅力。

后“用户数据编译模板”,取代了以下内容:

const phantomJsCloud = require("phantomjscloud"); 
const browser = new phantomJsCloud.BrowserApi([YOURPHANTOMJSCLOUDAPIKEY]); 

var pageRequest = { content: html, renderType: "pdf" }; 

// Send our HTML to PhantomJS to convert to PDF 

return browser.requestSingle(pageRequest) 
     .then(function (userResponse) { 
      if (userResponse.statusCode != 200) { 
       console.log("invalid status code" + userResponse.statusCode); 
      } else { 
       console.log('Successfully generated PDF'); 

       // Save the PDF locally 
       fs.writeFile(localPDFFile, userResponse.content.data, { 
          encoding: userResponse.content.encoding, 
         }, function (err) {        
          // Upload the file to our cloud bucket 
          return pdfBucket.upload(localPDFFile, { destination: 'desired-filename.pdf', metadata: { contentType: 'application/pdf'}}).then(() => { 
          console.log('bucket upload complete: '+ localPDFFile); 
          }).catch(error => { 
          console.error('bucket upload error:', error); 
          }); 
         }); 

        } 

        }); 
相关问题