import mammoth from 'mammoth'; import ExcelJS from 'exceljs'; import puppeteer from 'puppeteer'; const HTML_TEMPLATE = ` {{CONTENT}} `; export async function convertToPdf(fileBuffer, mimeType, originalName) { let htmlContent = ''; if (mimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || originalName.endsWith('.docx')) { const result = await mammoth.convertToHtml({ buffer: fileBuffer }); htmlContent = result.value; } else if (mimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || originalName.endsWith('.xlsx')) { const workbook = new ExcelJS.Workbook(); await workbook.xlsx.load(fileBuffer); let htmlBuilder = ''; workbook.eachSheet((worksheet, sheetId) => { htmlBuilder += `

${worksheet.name}

`; worksheet.eachRow((row, rowNumber) => { htmlBuilder += ''; row.eachCell({ includeEmpty: true }, (cell, colNumber) => { const tag = rowNumber === 1 ? 'th' : 'td'; let cellValue = ''; try { if (cell.type === 6) { cellValue = ''; } else { cellValue = cell.text || (cell.value != null ? cell.value.toString() : ''); } } catch (e) { cellValue = ''; } htmlBuilder += `<${tag}>${cellValue}`; }); htmlBuilder += ''; }); htmlBuilder += '

'; }); htmlContent = htmlBuilder; } else { throw new Error(`Unsupported document type for conversion: ${mimeType}`); } const fullHtml = HTML_TEMPLATE.replace('{{CONTENT}}', htmlContent || '

Empty Document

'); const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] }); const page = await browser.newPage(); await page.setContent(fullHtml, { waitUntil: 'networkidle0' }); const pdfUint8Array = await page.pdf({ format: 'A4', printBackground: true }); await browser.close(); return Buffer.from(pdfUint8Array); }