1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
import ExcelJS from 'exceljs'; import fs from 'fs' import { PDFDocument, rgb, StandardFonts } from 'pdf-lib'; async function convertExcelToPDF(excelFilePath, pdfFilePath) { const workbook = new ExcelJS.Workbook(); await workbook.xlsx.readFile(excelFilePath); const pdfDoc = await PDFDocument.create(); const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica); let page = pdfDoc.addPage(); let { width, height } = page.getSize(); let y = height - 50; // Start the content below the sheet name workbook.eachSheet((worksheet) => { const sheetName = worksheet.name; page.drawText(sheetName, { x: 50, y: y, font: helveticaFont, size: 20, color: rgb(0, 0, 0) }); y -= 30; // Move down for the next row const columnWidths = []; worksheet.eachRow((row) => { row.eachCell((cell, colNumber) => { const textWidth = helveticaFont.widthOfTextAtSize(cell.text, 12); columnWidths[colNumber - 1] = Math.max(columnWidths[colNumber - 1] || 0, textWidth); }); }); worksheet.eachRow((row, rowIndex) => { let x = 50; // Start from the left margin if (y < 50) { // If the current page is full, add a new page page = pdfDoc.addPage(); ({ width, height } = page.getSize()); y = height - 50; } row.eachCell((cell, colNumber) => { const textWidth = helveticaFont.widthOfTextAtSize(cell.text, 12); const cellWidth = columnWidths[colNumber - 1] + 80; const cellHeight = 20; // Draw cell background page.drawRectangle({ x, y: y - cellHeight, width: cellWidth, height: cellHeight, color: rowIndex === 1 ? rgb(0.8, 0.8, 0.8) : rgb(1, 1, 1), borderColor: rgb(0, 0, 0), borderWidth: 1, }); // Draw cell text page.drawText(cell.text, { x: x + (cellWidth - textWidth) / 2, y: y - cellHeight / 2 - 6, font: helveticaFont, size: 12, color: rgb(0, 0, 0), }); x += cellWidth; // Move to the right for the next cell }); y -= 20; // Move down for the next row }); }); const pdfBytes = await pdfDoc.save(); await fs.promises.writeFile(pdfFilePath, pdfBytes); } // Usage example const excelFilePath = 'test.xlsx'; const pdfFilePath = 'file.pdf'; convertExcelToPDF(excelFilePath, pdfFilePath) .then(() => { console.log('Excel file converted to PDF successfully!'); }) .catch((error) => { console.error('Error converting Excel file to PDF:', error); }); |