Created
February 5, 2016 22:02
-
-
Save dcousineau/c92b01aa28f1845829e2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
{ | |
"devDependencies": { | |
"babel-cli": "^6.4.5", | |
"babel-core": "^6.4.5", | |
"babel-preset-es2015": "^6.3.13" | |
}, | |
"dependencies": { | |
"canvas": "^1.3.9" | |
} | |
} |
This file contains hidden or 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 Canvas = require('canvas'), | |
fs = require('fs'), | |
child_process = require('child_process'), | |
spawn = child_process.spawn | |
; | |
function fitText(text, {canvas, start, padding, style}) { | |
const ctx = canvas.getContext('2d'); | |
let iteration = start; | |
ctx.font = style(iteration); | |
while (ctx.measureText(text).width > (canvas.width - (padding * 2))) { | |
iteration -= 2; | |
ctx.font = style(iteration); | |
if (iteration <= 10) break; | |
} | |
return [ctx.measureText(text).width, style(iteration)]; | |
} | |
function renderBadge({firstName, lastName, ticketType, badge}) { | |
const canvas = new Canvas(); | |
canvas.width = badge.width; | |
canvas.height = badge.height; | |
//Print first name | |
(() => { | |
const ctx = canvas.getContext('2d'); | |
let width = 0; | |
let size = 120; | |
const padding = 5; | |
[width, ctx.font] = fitText(firstName, { | |
canvas, | |
padding, | |
start: size, | |
style: size => `bold ${size}px Helvetica Neue` | |
}); | |
ctx.fillText(firstName, ((canvas.width - width) / 2) - padding/2, (canvas.height/2 - size/2)); | |
})(); | |
//Print last name | |
(() => { | |
const ctx = canvas.getContext('2d'); | |
let width = 0; | |
let size = 60; | |
const padding = 5; | |
[width, ctx.font] = fitText(lastName, { | |
canvas, | |
padding, | |
start: size, | |
style: size => `${size}px Helvetica Neue` | |
}); | |
ctx.fillText(lastName, ((canvas.width - width) / 2) - padding/2, (canvas.height/2 + size/2)); | |
})(); | |
return canvas; | |
} | |
const badge = renderBadge({ | |
firstName: "Daniel", | |
lastName: "Cousineau", | |
type: "Organizer", | |
badge: { | |
width: 700, | |
height: 300 | |
} | |
}); | |
const out = fs.createWriteStream(__dirname + '/badge.png'); | |
const stream = badge.pngStream(); | |
stream.on('data', chunk => { | |
out.write(chunk); | |
}); | |
stream.on('end', () => { | |
child_process.exec('lp -d Brother_QL_700 -o media=Custom.2.4x1.5in ./badge.png', () => { | |
console.log('done'); | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment