File size: 1,757 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
import { ClassicPreset } from 'rete';
import { BaseWorkflowNode } from './base-node';
import { pdfSocket } from '../sockets';
import type { SocketData } from '../types';
import { requirePdfInput, processBatch } from '../types';
import { deletePdfPages, parseDeletePages } from '../../utils/pdf-operations';
import { PDFDocument } from 'pdf-lib';

export class DeletePagesNode extends BaseWorkflowNode {
  readonly category = 'Organize & Manage' as const;
  readonly icon = 'ph-trash';
  readonly description = 'Remove specific pages';

  constructor() {
    super('Delete Pages');
    this.addInput('pdf', new ClassicPreset.Input(pdfSocket, 'PDF'));
    this.addOutput('pdf', new ClassicPreset.Output(pdfSocket, 'PDF'));
    this.addControl(
      'pages',
      new ClassicPreset.InputControl('text', { initial: '1' })
    );
  }

  async data(
    inputs: Record<string, SocketData[]>
  ): Promise<Record<string, SocketData>> {
    const pdfInputs = requirePdfInput(inputs, 'Delete Pages');
    const pagesControl = this.controls['pages'] as
      | ClassicPreset.InputControl<'text'>
      | undefined;
    const deleteStr = pagesControl?.value || '';

    return {
      pdf: await processBatch(pdfInputs, async (input) => {
        const srcDoc = await PDFDocument.load(input.bytes);
        const totalPages = srcDoc.getPageCount();
        const pagesToDelete = parseDeletePages(deleteStr, totalPages);
        const resultBytes = await deletePdfPages(input.bytes, pagesToDelete);
        const resultDoc = await PDFDocument.load(resultBytes);
        return {
          type: 'pdf',
          document: resultDoc,
          bytes: resultBytes,
          filename: input.filename.replace(/\.pdf$/i, '_trimmed.pdf'),
        };
      }),
    };
  }
}