File size: 2,807 Bytes
64011fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { ClassicPreset } from 'rete';
import { BaseWorkflowNode } from './base-node';
import { pdfSocket } from '../sockets';
import type { SocketData } from '../types';
import { requirePdfInput, extractAllPdfs } from '../types';
import { downloadFile } from '../../utils/helpers.js';
import { loadPyMuPDF } from '../../utils/pymupdf-loader.js';

function tableToCsv(rows: (string | null)[][]): string {
  return rows
    .map((row) =>
      row
        .map((cell) => {
          const str = String(cell ?? '');
          if (str.includes(',') || str.includes('"') || str.includes('\n')) {
            return `"${str.replace(/"/g, '""')}"`;
          }
          return str;
        })
        .join(',')
    )
    .join('\n');
}

export class PdfToCsvNode extends BaseWorkflowNode {
  readonly category = 'Output' as const;
  readonly icon = 'ph-file-csv';
  readonly description = 'Extract tables from PDF to CSV';

  constructor() {
    super('PDF to CSV');
    this.addInput('pdf', new ClassicPreset.Input(pdfSocket, 'PDF'));
  }

  private async extractTables(bytes: Uint8Array): Promise<(string | null)[][]> {
    const pymupdf = await loadPyMuPDF();
    const blob = new Blob([new Uint8Array(bytes)], { type: 'application/pdf' });
    const doc = await pymupdf.open(blob);
    const allRows: (string | null)[][] = [];

    try {
      const pageCount = doc.pageCount;
      for (let i = 0; i < pageCount; i++) {
        const page = doc.getPage(i);
        const tables = page.findTables();
        tables.forEach((table: any) => {
          allRows.push(...table.rows);
        });
      }
    } finally {
      doc.close();
    }

    return allRows;
  }

  async data(
    inputs: Record<string, SocketData[]>
  ): Promise<Record<string, SocketData>> {
    const pdfInputs = requirePdfInput(inputs, 'PDF to CSV');
    const allPdfs = extractAllPdfs(pdfInputs);

    if (allPdfs.length === 1) {
      const allRows = await this.extractTables(allPdfs[0].bytes);
      if (allRows.length === 0) {
        throw new Error('No tables found in PDF');
      }
      const csv = tableToCsv(allRows);
      const csvBlob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
      const name = allPdfs[0].filename.replace(/\.pdf$/i, '') + '.csv';
      downloadFile(csvBlob, name);
    } else {
      const JSZip = (await import('jszip')).default;
      const zip = new JSZip();
      for (const pdf of allPdfs) {
        const allRows = await this.extractTables(pdf.bytes);
        if (allRows.length === 0) continue;
        const csv = tableToCsv(allRows);
        const name = pdf.filename.replace(/\.pdf$/i, '') + '.csv';
        zip.file(name, csv);
      }
      const zipBlob = await zip.generateAsync({ type: 'blob' });
      downloadFile(zipBlob, 'csv_files.zip');
    }

    return {};
  }
}