@Stroy-St

Как конвертировать Excel в PDF nodeJS на Ubuntu?

Есть сервер nodeJS на Ubuntu. На нем формируются Excel файлы с помощью ExcelJS (расширение .xlsx). Необходимо реализовать конвертер в PDF этих файлов.
Cкрипт, но он не работает.
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);
}

Выдает ошибку:
node: internal/event_target:1010 process.nextTick(() => { throw err; }); Error: Can't find end of central directory: is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html ZipEntries.readEndOfCentral (C:\reactProjects\proj44\server44\node_modules\jszip\lib\zipEntries.js:167:23) at at ZipEntries.load (C:\reactProjects\proj44\server44\node_modules\jszip\lib\zipEntries.js:255:14) at C:\reactProjects\proj44\server44\node_modules\jszip\lib\load.js:48:24 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Вызвал отдельно convertExcelToPDF. Выдает вот это:
C:\reactProjects\proj44\server44\service\files\temp.xlsx C:\reactProjects\proj44\server44\service\download C:\reactProjects\proj44\server44\node_modules\exceljs\lib\doc\cell.js:730 return this.value.toString(); TypeError: Cannot read properties of null (reading 'toString') at MergeValue.toString (C:\reactProjects\proj44\server44\node_modules\exceljs\lib\doc\cell.js:730:23) at get text [as text] (C:\reactProjects\proj44\server44\node_modules\exceljs\lib\doc\cell.js:233:24)

Все модули установлены: worker_threads, path, exceljs, pdfkit, fs, functions-have-names
  • Вопрос задан
  • 87 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы