All files / src/services converter.service.ts

8.91% Statements 9/101
0% Branches 0/105
0% Functions 0/15
8.33% Lines 7/84

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 1881x 1x 1x 1x 1x   1x     1x                                                                                                                                                                                                                                                                                                                                                                    
import { bind, BindingScope } from '@loopback/core';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
 
(pdfMake as any).vfs = (pdfFonts as any).vfs;
 
@bind({ scope: BindingScope.TRANSIENT })
export class ConverterService {
 
  /**
   * Convert an Excel file to a PDF file with a single page.
   * The PDF will be generated with landscape orientation and the content will be
   * centered horizontally.
   * @param inputPath The path to the Excel file.
   * @param outputPath The path to the PDF file to be generated.
   */
  async convertExcelToPdfStrict(inputPath: string, outputPath: string) {
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.readFile(inputPath);
 
    const sheet = workbook.worksheets.find(ws => !ws.state || ws.state === 'visible');
    if (!sheet) throw new Error('No visible sheet found');
 
    const rows: any[][] = [];
 
    // Find the maximum number of columns in the sheet
    let maxRealCols = 0;
    sheet.eachRow({ includeEmpty: false }, (row) => {
      if (row.hidden) return;
 
      let lastNonEmptyCol = 0;
      row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
        const col = sheet.getColumn(colNumber);
        if (col.hidden) return;
 
        const val = this.extractCellText(cell);
        if (val?.trim && val.trim() !== '') {
          lastNonEmptyCol = colNumber;
        }
      });
 
      if (lastNonEmptyCol > maxRealCols) {
        maxRealCols = lastNonEmptyCol;
      }
    });
 
    sheet.eachRow({ includeEmpty: false }, (row) => {
      if (row.hidden) return;
 
      const rowData: any[] = [];
 
      for (let colNumber = 1; colNumber <= maxRealCols; colNumber++) {
        const cell = row.getCell(colNumber);
        const col = sheet.getColumn(colNumber);
        if (col.hidden) continue;
 
        const text = this.extractCellText(cell);
 
        const style: any = { text };
 
        // Font style
        if (cell.font?.bold) style.bold = true;
        if (cell.font?.italic) style.italics = true;
        if (cell.font?.size) style.fontSize = cell.font.size;
        if (cell.font?.color?.argb) style.color = `#${cell.font.color.argb.slice(2)}`;
 
        // Alignment
        if (cell.alignment?.horizontal) style.alignment = cell.alignment.horizontal;
 
        // Fill color
        if (cell.fill?.type === 'pattern' && cell.fill.fgColor?.argb) {
          style.fillColor = `#${cell.fill.fgColor.argb.slice(2)}`;
        }
 
        rowData.push(style);
      }
 
      if (rowData.length > 0) rows.push(rowData);
    });
 
    const widths = Array.from({ length: maxRealCols }, (_, idx) => 'auto');
 
    const docDefinition = {
      pageSize: 'A4',
      pageOrientation: 'landscape',
      pageMargins: [20, 20, 20, 20], // National margins
      content: [
        {
          table: {
            headerRows: 1,
            widths: widths,
            body: rows
          },
          layout: {
            paddingLeft: () => 4,
            paddingRight: () => 4,
            paddingTop: () => 1,
            paddingBottom: () => 1,
            hLineWidth: () => 0,
            vLineWidth: () => 0,
          }
        },
      ],
      defaultStyle: {
        font: 'Roboto',
        fontSize: 7,
      },
    };
 
    const pdfDoc = (pdfMake as any).createPdf(docDefinition);
    await pdfDoc.getBuffer((buffer: Buffer) => {
      fs.writeFileSync(outputPath, buffer);
      console.log('✅ PDF created at', outputPath);      
    });
    // Make sure the file is created before returning
    // This is a workaround for the async nature of pdfMake
    // and the fact that we need to wait for the file to be written
    // before we can return from this function.
    // This is not the best way to do this, but it works for now.
    // In the future, we should use a better way to handle async operations
    // and make sure the file is created before returning.
    while (!fs.existsSync(outputPath)) {
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  }
 
  /**
   * Given an ExcelJS cell, return a string representation of its value.
   *
   * Handles various cases, including:
   * - Formulas and shared formulas
   * - Number formatting, including percentage
   * - Text
   * - Booleans
   * - Errors
   * - Null or undefined
   */
  private extractCellText(cell: ExcelJS.Cell): string {
    if (cell.value === null || cell.value === undefined) {
      return '';
    }
 
    if (typeof cell.value === 'object') {
      if ('formula' in cell.value || 'sharedFormula' in cell.value) {
        // console.log('address:', cell.address, 'cell:', 'cell.result: ', cell.result);
        const result = cell.result;
        if (cell.numFmt === undefined && (result === undefined || result === null))
          return ''
        else if (result === undefined || result === null) {
          return String(cell.numFmt);
        };
 
        if (typeof result === 'number') {
          const numFmt = cell.numFmt || '';
          if (numFmt.includes('%')) {
            const percentage = (result * 100);
            return `${percentage.toFixed(2)}%`;
          } else {
            return String(result);
          }
        } else {
          return String(result);
        }
      } else if ('text' in cell.value) {
        return cell.value.text;
      } else {
        return '"';
      }
    } else if (typeof cell.value === 'number') {
      const numFmt = cell.numFmt || '';
      if (numFmt.includes('%')) {
        const percentage = (cell.value * 100);
        if (Math.round(percentage) === percentage) {
          return `${percentage}%`;
        } else {
          return `${percentage.toFixed(2)}%`;
        }
      } else {
        return String(cell.value);
      }
    } else {
      return String(cell.value);
    }
  }
}