custom-scripts/mccs-it/thermal/modules/Thermal.js

85 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-09-09 15:38:53 +00:00
const PDFDocument = require('pdfkit');
2024-09-09 17:33:26 +00:00
const fs = require('fs');
2024-09-09 15:38:53 +00:00
const { spawn } = require('child_process');
2024-09-09 17:33:26 +00:00
const path = require('path');
2024-09-09 15:38:53 +00:00
module.exports = {
2024-09-09 17:05:03 +00:00
generateFile(username, studentId, req, res) {
2024-09-09 17:03:23 +00:00
// Create the output text
const infoArray = [
'Username:',
`${username}`,
'',
'Email:',
`${username}@kvcc.me.edu`,
'',
'Student ID:',
`${studentId}`,
'',
'Note: When signing into the MyKV Portal, use your Username not your Email.',
2024-09-09 17:14:39 +00:00
'',
2024-09-09 17:03:23 +00:00
'For further assistance contact ithelp@mainecc.edu'
];
const infoString = infoArray.join('\n');
2024-09-09 17:33:26 +00:00
// Define the path for the PDF file
const pdfFilePath = path.join(__dirname, 'output.pdf');
// Create a new PDF document
2024-09-09 17:03:23 +00:00
const doc = new PDFDocument({
2024-09-09 17:41:14 +00:00
size: [204, 400],
2024-09-09 17:15:30 +00:00
margin: 5
2024-09-09 17:03:23 +00:00
});
2024-09-09 17:33:26 +00:00
// Create a writable stream to save the PDF to a file
const writeStream = fs.createWriteStream(pdfFilePath);
doc.pipe(writeStream);
2024-09-09 17:03:23 +00:00
// Add content (image, text) to the PDF
2024-09-09 20:17:52 +00:00
doc.image('./public/itslogo.jpg', {
fit: [196, 100],
align: 'center',
valign: 'top',
});
2024-09-09 17:03:23 +00:00
2024-09-09 20:17:52 +00:00
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.moveDown();
doc.moveDown();
2024-09-09 17:16:05 +00:00
doc.fontSize(12).text(infoString, {
2024-09-09 17:03:23 +00:00
align: 'left',
});
// Finalize the PDF
doc.end();
2024-09-09 17:33:26 +00:00
writeStream.on('finish', () => {
// PDF file has been saved, now print it using lp command
const printer = spawn('lp', ['-d', 'ITThermal', pdfFilePath]); // Replace 'ITThermal' with your actual printer name
// Handle error if the printing process fails
printer.on('error', (err) => {
console.error('Failed to start printing process:', err);
res.status(500).json({ message: 'Failed to start printing process', error: err.message });
});
// Handle the process exit event
printer.on('close', (code) => {
if (code === 0) {
2024-09-09 17:41:14 +00:00
res.send('PDF sent to printer successfully.');
2024-09-09 17:33:26 +00:00
} else {
res.status(500).json({ message: 'Failed to print PDF' });
}
});
});
// Handle any errors during file writing
writeStream.on('error', (err) => {
console.error('Error writing PDF file:', err);
res.status(500).json({ message: 'Error writing PDF file', error: err.message });
});
2024-09-09 17:03:23 +00:00
}
2024-09-09 15:38:53 +00:00
}