Created
November 8, 2023 19:15
-
-
Save jgcmarins/78350d2b9bbffdadd89e530c52f0ac30 to your computer and use it in GitHub Desktop.
Chat GPT code to generate pdf from xlsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const { PDFDocument, rgb } = require('pdf-lib'); | |
const ExcelJS = require('exceljs'); | |
// Function to convert XLSX to PDF | |
async function convertXlsxToPdf(inputXlsxPath, outputPdfPath) { | |
// Create a new PDF document | |
const pdfDoc = await PDFDocument.create(); | |
// Load the XLSX file | |
const workbook = new ExcelJS.Workbook(); | |
await workbook.xlsx.readFile(inputXlsxPath); | |
// Create a new page for each sheet in the XLSX file | |
for (const sheet of workbook.worksheets) { | |
const pdfPage = pdfDoc.addPage([595, 842]); // A4 size | |
const pdfContentStream = pdfDoc.createContentStream(); | |
// Create a font | |
const timesRomanFont = await pdfDoc.embedFont('Helvetica'); | |
// Set font properties | |
pdfContentStream.setFont(timesRomanFont, 12); | |
pdfContentStream.setFillColor(rgb(0, 0, 0)); | |
// Convert the sheet to a PDF page | |
sheet.eachRow((row, rowNumber) => { | |
row.eachCell((cell, colNumber) => { | |
pdfContentStream.drawText( | |
cell.text, | |
{ | |
x: 50 * colNumber, | |
y: 750 - 20 * rowNumber, | |
} | |
); | |
}); | |
}); | |
pdfPage.addContentStreams(pdfContentStream); | |
} | |
// Serialize the PDF and save it to a file | |
const pdfBytes = await pdfDoc.save(); | |
fs.writeFileSync(outputPdfPath, pdfBytes); | |
} | |
// Usage | |
const inputXlsxPath = 'input.xlsx'; | |
const outputPdfPath = 'output.pdf'; | |
convertXlsxToPdf(inputXlsxPath, outputPdfPath) | |
.then(() => { | |
console.log('Conversion completed.'); | |
}) | |
.catch((error) => { | |
console.error('Error:', error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment