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, 1000], 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) { // Delete the file after printing to clean up fs.unlink(pdfFilePath, (err) => { if (err) { console.error('Error deleting file:', err); res.status(500).json({ message: 'Failed to clean up after printing', error: err.message }); return; } 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 }); }); } }