Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
2 tasks done
AnasNabli opened this issue Jul 4, 2024 · 0 comments
Open
2 tasks done

Comments

@AnasNabli
Copy link

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

[email protected]

What environment are you running pdf-lib in?

Other

Checklist

  • My report includes a Short, Self Contained, Correct (Compilable) Example.
  • I have attached all PDFs, images, and other files needed to run my SSCCE.

Additional Notes

nan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant