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

85 lines
2.2 KiB
JavaScript

const PDFDocument = require('pdfkit');
const fs = require('fs');
const { spawn } = require('child_process');
const path = require('path');
module.exports = {
generateFile(username, studentId, req, res) {
// 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.',
'',
'For further assistance contact ithelp@mainecc.edu'
];
const infoString = infoArray.join('\n');
// Define the path for the PDF file
const pdfFilePath = path.join(__dirname, 'output.pdf');
// Create a new PDF document
const doc = new PDFDocument({
size: [204, 400],
margin: 5
});
// Create a writable stream to save the PDF to a file
const writeStream = fs.createWriteStream(pdfFilePath);
doc.pipe(writeStream);
// Add content (image, text) to the PDF
// doc.image('./public/itslogo.jpg', {
// fit: [196, 100],
// align: 'center',
// valign: 'top',
// });
// doc.moveDown();
// doc.moveDown();
// doc.moveDown();
// doc.moveDown();
// doc.moveDown();
// doc.moveDown();
// doc.moveDown();
doc.fontSize(12).text(infoString, {
align: 'left',
});
// Finalize the PDF
doc.end();
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) {
res.send('PDF sent to printer successfully.');
} 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 });
});
}
}