const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
const path = require('path');
const exceljs = require('exceljs');
const PDFDocument = require('pdfkit');
const fs = require('fs');
// Функция для конвертации Excel-файла в PDF
function convertExcelToPDF(excelFilePath, outputPdfPath) {
const workbook = new exceljs.Workbook();
workbook.xlsx.readFile(excelFilePath).then(() => {
const worksheet = workbook.getWorksheet(1);
const pdfDoc = new PDFDocument();
pdfDoc.font('Helvetica');
let currentRow = 1;
worksheet.eachRow({ includeEmpty: true }, (row) => {
const height = row.height;
let rowData = [];
row.eachCell({ includeEmpty: true }, (cell) => {
rowData.push(cell.text);
});
rowData.forEach((cellData, columnIndex) => {
pdfDoc.text(cellData, 50 * (columnIndex + 1), 50 * currentRow);
});
currentRow += height / 14;
if (currentRow > 27) {
pdfDoc.addPage();
currentRow = 1;
}
});
pdfDoc.pipe(fs.createWriteStream(outputPdfPath));
pdfDoc.end();
console.log('PDF файл сохранен: ${outputPdfPath}');
});
}
if (isMainThread) {
// Папка, где находятся Excel-файлы
const excelFolder = path.join(__dirname, '../service/files');
// Получение списка файлов в указанной папке
fs.readdir(excelFolder, (err, files) => {
if (err) {
console.error(err);
return;
}
// Обработка каждого файла в папке
files.forEach((file) => {
const excelFilePath = path.join(excelFolder, file);
const outputPdfPath = path.join(__dirname, '../service/download', '${path.parse(file).name}.pdf');
// Создание нового worker thread для каждого файла
new Worker(__filename, { workerData: { excelFilePath, outputPdfPath } });
});
});
} else {
// Внутри worker thread
const { excelFilePath, outputPdfPath } = workerData;
convertExcelToPDF(excelFilePath, outputPdfPath);
}