由於存在Firebase函數(Firebase Introduction),因此可以使用NodeJS以pdfkit(PDFKit)爲例創建PDfs。以下示例描述了一種在AccountCreation(Event)上生成PDF的方法,將其保存到存儲並通過郵件發送給用戶。所有這些都發生在Firebase服務器上。對於所有使用的圖書館不要忘記npm安裝它們並將它們包含到package.json中。一個棘手的部分是add the Firebase Admin SDK to your Server。另外,this幫了很多。說實話,這花了我幾個小時。所以不要請求細節!
const functions = require('firebase-functions');
const admin = require("firebase-admin");
const nodemailer = require('nodemailer');
const pdfkit = require('pdfkit');
const gmailEmail = '[email protected]'
const gmailPassword = 'test123.ThisisNoTSave'
const mailTransport = nodemailer.createTransport(`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`);
const serviceAccount = require("./youradminsdk.json");
//Save this file to your functions Project
// Your company name to include in the emails
const APP_NAME = 'My App';
const PROJECT_ID = "google-testproject";
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: `https://${PROJECT_ID}.firebaseio.com`,
storageBucket: `${PROJECT_ID}.appspot.com`
});
var config = {
projectId: `${PROJECT_ID}`,
keyFilename: './youradminsdk.json'
};
const storage = require('@google-cloud/storage')(config);
const datastore= require('@google-cloud/datastore')(config);
// [START onCreateTrigger]
exports.sendPDFMail = functions.auth.user().onCreate(event => {
// [END onCreateTrigger]
// [START eventAttributes]
const doc = new pdfkit;
const user = event.data; // The Firebase user.
const email = user.email; // The email of the user.
const displayName = user.displayName; // The display name of the user.
// [END eventAttributes]
const bucket = storage.bucket(`${PROJECT_ID}.appspot.com`);
console.log(bucket);
const filename = Date.now() + 'output.pdf';
const file = bucket.file(filename);
const stream = file.createWriteStream({resumable: false});
// Pipe its output to the bucket
doc.pipe(stream);
doc.fontSize(25).text('Some text with an embedded font!', 100, 100);
doc.end();
stream.on('finish', function() {
return sendPDFMail(email, displayName, doc);
});
stream.on('error', function(err) {
console.log(err);
});
})
;
// [END sendPDFMail]
// Sends a welcome email to the given user.
function sendPDFMail(email, displayName, doc) {
const mailOptions = {
from: '"MyCompany" <[email protected]>',
to: email,
};
mailOptions.subject = `Welcome to ${APP_NAME}!`;
mailOptions.text = `Hey ${displayName}!, Welcome to ${APP_NAME}. I hope you will enjoy our service.`;
mailOptions.attachments = [{filename: 'meinPdf.pdf', content: doc, contentType: 'application/pdf' }];
return mailTransport.sendMail(mailOptions).then(() => {
console.log('New welcome email sent to:', email);
});
}
Firebase沒有任何內置功能來生成PDF,因此您必須在客戶端上生成它或爲其設置服務器。在堆棧溢出 –