Hopding / pdf-lib

Create and modify PDF documents in any JavaScript environment
https://pdf-lib.js.org
MIT License
6.6k stars 635 forks source link

Error converting Excel to PDF: PDFDocument.registerFontkit is not a function #1648

Open AnasNabli opened 3 weeks ago

AnasNabli commented 3 weeks ago

What were you trying to do?

const ExcelJS = require('exceljs'); const { PDFDocument, rgb } = require('pdf-lib'); const fs = require('fs'); const fontkit = require('fontkit'); // Import fontkit

async function convertExcelToPdf(filePath) { const smallerWidthColumns = [1, 2, 3, 4, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20]; const defaultCellWidth = 50; const smallerCellWidth = 30; const fontSize = 12; // Adjusted font size for readability const cellPadding = 5; const tableTopPadding = 50; const tableLeftPadding = 50; // Adjusted for better alignment

try {
    // Register fontkit with PDFDocument
    PDFDocument.registerFontkit(fontkit);

    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.readFile(filePath);

    const pdfDoc = await PDFDocument.create();

    // Load and embed custom Arabic font (NotoSansArabic-Regular.ttf)
    const fontBytes = fs.readFileSync('./fonts/NotoSansArabic-Regular.ttf');
    const customFont = await pdfDoc.embedFont(fontBytes);

    let pageWidth = 600; // Adjusted for better fit
    let pageHeight = 800;

    workbook.eachSheet((worksheet, sheetId) => {
        let page = pdfDoc.addPage([pageWidth, pageHeight]);
        const { width, height } = page.getSize();
        let y = height - tableTopPadding;

        worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
            let maxRowHeight = 0;
            let xPosition = tableLeftPadding; // Adjusted for left padding

            row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
                const cellText = cell.value ? cell.value.toString().trim() : "";
                const isSmallerWidth = smallerWidthColumns.includes(colNumber);
                const cellWidth = isSmallerWidth ? smallerCellWidth : defaultCellWidth;
                const cellHeight = fontSize + 2 * cellPadding;
                maxRowHeight = Math.max(maxRowHeight, cellHeight);

                page.drawRectangle({
                    x: xPosition,
                    y: y - cellHeight,
                    width: cellWidth,
                    height: cellHeight,
                    borderColor: rgb(0, 0, 0),
                    borderWidth: 0.5
                });

                page.drawText(cellText, {
                    x: xPosition + cellPadding,
                    y: y - cellHeight + cellPadding,
                    size: fontSize,
                    font: customFont, // Use the embedded custom font
                    color: rgb(0, 0, 0)
                });

                xPosition += cellWidth;
            });

            y -= maxRowHeight;
            if (y <= tableTopPadding) {
                y = height - tableTopPadding;
                page = pdfDoc.addPage([pageWidth, pageHeight]);
            }
        });

        worksheet.getRow(1).eachCell({ includeEmpty: true }, (cell, colNumber) => {
            const cellText = cell.value ? cell.value.toString().trim() : "";
            const isSmallerWidth = smallerWidthColumns.includes(colNumber);
            const cellWidth = isSmallerWidth ? smallerCellWidth : defaultCellWidth;
            const cellHeight = fontSize + 2 * cellPadding;

            page.drawRectangle({
                x: tableLeftPadding + (colNumber - 1) * cellWidth,
                y: height - tableTopPadding,
                width: cellWidth,
                height: cellHeight,
                borderColor: rgb(0, 0, 0),
                borderWidth: 0.5
            });

            page.drawText(cellText, {
                x: tableLeftPadding + (colNumber - 1) * cellWidth + cellPadding,
                y: height - tableTopPadding + cellPadding,
                size: fontSize,
                font: customFont, // Use the embedded custom font
                color: rgb(0, 0, 0),
                bold: true
            });
        });
    });

    const pdfBytes = await pdfDoc.save();
    fs.writeFileSync('output.pdf', pdfBytes);

    return pdfBytes;
} catch (error) {
    console.error('Error in convertExcelToPdf:', error.message);
    console.error(error.stack);
    throw error;
}

}

module.exports = { convertExcelToPdf };

How did you attempt to do it?

convert excel to pdf

What actually happened?

ereur

What did you expect to happen?

convert succesfly

How can we reproduce the issue?

tnx

Version

─ pdf-lib@1.17.1

What environment are you running pdf-lib in?

Other

Checklist

Additional Notes

nan