Last active
November 28, 2017 07:23
-
-
Save roelvan/70c68a4a370fb101319237e4a3eb530b to your computer and use it in GitHub Desktop.
Generate PDF's and Barcodes with Feathers.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const errors = require('feathers-errors'); | |
const PDFDocument = require('pdfkit'); | |
const bwipjs = require('bwip-js'); | |
/* eslint-disable no-unused-vars */ | |
class Service { | |
constructor (options) { | |
this.options = options || {}; | |
} | |
_generateBarcode (text) { | |
return new Promise((resolve, reject) => { | |
bwipjs.toBuffer({ | |
bcid: 'code128', | |
text, | |
scale: 5, | |
height: 10, | |
includetext: true, | |
textxalign: 'center' | |
}, (err, png) => { | |
if (err) reject(err); | |
else resolve(png); | |
}); | |
}); | |
} | |
_generatePdf (booking) { | |
const doc = new PDFDocument(); | |
// Title and name of event | |
doc.fontSize(25).text(booking.firstName + ' ' + booking.lastName, 100, 100); | |
doc.fontSize(16) | |
.text(`${booking.numberOfSpots} toegangticket${booking.numberOfSpots > 1 ? 's' : ''} voor ${booking.eventName} - ${booking.price} EUR`); | |
// Add Bookfast website | |
doc.fontSize(16).text('Ticketing by', 100, 320); | |
doc.fontSize(25).text('www.example.com', 100, 345); | |
// Add a hr stroke | |
doc.moveTo(100, 160).lineTo(508, 160).lineTo(508, 161).lineTo(100, 161).fill('#DEDEDE'); | |
// Add the barcode | |
return this._generateBarcode(booking._id).then(barcode => { | |
doc.image(barcode, 100, 200, { width: 408 }); | |
return doc; | |
}); | |
} | |
async get (id, params) { | |
return this.app.service('bookings').get(id).then(booking => { | |
return this._generatePdf(booking); | |
}).catch(() => { | |
throw new errors.NotFound('Booking not found.'); | |
}); | |
} | |
setup(app) { | |
this.app = app; | |
} | |
} | |
module.exports = function (options) { | |
return new Service(options); | |
}; | |
module.exports.Service = Service; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment