File size: 5,421 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
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
import { ClassicPreset } from 'rete';
import { BaseWorkflowNode } from './base-node';
import { pdfSocket } from '../sockets';
import type { SocketData } from '../types';
import { requirePdfInput, processBatch } from '../types';
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
import { hexToRgb } from '../../utils/helpers.js';

export class HeaderFooterNode extends BaseWorkflowNode {
  readonly category = 'Edit & Annotate' as const;
  readonly icon = 'ph-paragraph';
  readonly description = 'Add header and footer text';

  constructor() {
    super('Header & Footer');
    this.addInput('pdf', new ClassicPreset.Input(pdfSocket, 'PDF'));
    this.addOutput(
      'pdf',
      new ClassicPreset.Output(pdfSocket, 'PDF with Header/Footer')
    );
    this.addControl(
      'headerLeft',
      new ClassicPreset.InputControl('text', { initial: '' })
    );
    this.addControl(
      'headerCenter',
      new ClassicPreset.InputControl('text', { initial: '' })
    );
    this.addControl(
      'headerRight',
      new ClassicPreset.InputControl('text', { initial: '' })
    );
    this.addControl(
      'footerLeft',
      new ClassicPreset.InputControl('text', { initial: '' })
    );
    this.addControl(
      'footerCenter',
      new ClassicPreset.InputControl('text', {
        initial: 'Page {page} of {total}',
      })
    );
    this.addControl(
      'footerRight',
      new ClassicPreset.InputControl('text', { initial: '' })
    );
    this.addControl(
      'fontSize',
      new ClassicPreset.InputControl('number', { initial: 10 })
    );
    this.addControl(
      'color',
      new ClassicPreset.InputControl('text', { initial: '#000000' })
    );
  }

  async data(
    inputs: Record<string, SocketData[]>
  ): Promise<Record<string, SocketData>> {
    const pdfInputs = requirePdfInput(inputs, 'Header & Footer');

    const getText = (key: string) => {
      const ctrl = this.controls[key] as
        | ClassicPreset.InputControl<'text'>
        | undefined;
      return ctrl?.value || '';
    };
    const sizeCtrl = this.controls['fontSize'] as
      | ClassicPreset.InputControl<'number'>
      | undefined;
    const fontSize = Math.max(4, Math.min(72, sizeCtrl?.value ?? 10));

    const colorHex = getText('color') || '#000000';
    const c = hexToRgb(colorHex);
    const color = rgb(c.r, c.g, c.b);

    const fields = {
      headerLeft: getText('headerLeft'),
      headerCenter: getText('headerCenter'),
      headerRight: getText('headerRight'),
      footerLeft: getText('footerLeft'),
      footerCenter: getText('footerCenter'),
      footerRight: getText('footerRight'),
    };

    const hasAny = Object.values(fields).some((v) => v.length > 0);

    return {
      pdf: await processBatch(pdfInputs, async (input) => {
        if (!hasAny) return input;

        const pdfDoc = await PDFDocument.load(input.bytes);
        const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
        const pages = pdfDoc.getPages();
        const totalPages = pages.length;
        const margin = 36;

        for (let i = 0; i < pages.length; i++) {
          const page = pages[i];
          const { width, height } = page.getSize();
          const pageNum = i + 1;

          const processText = (tmpl: string) =>
            tmpl
              .replace(/{page}/g, String(pageNum))
              .replace(/{total}/g, String(totalPages));

          const drawOpts = { size: fontSize, font, color };

          if (fields.headerLeft) {
            page.drawText(processText(fields.headerLeft), {
              ...drawOpts,
              x: margin,
              y: height - margin,
            });
          }
          if (fields.headerCenter) {
            const text = processText(fields.headerCenter);
            const tw = font.widthOfTextAtSize(text, fontSize);
            page.drawText(text, {
              ...drawOpts,
              x: (width - tw) / 2,
              y: height - margin,
            });
          }
          if (fields.headerRight) {
            const text = processText(fields.headerRight);
            const tw = font.widthOfTextAtSize(text, fontSize);
            page.drawText(text, {
              ...drawOpts,
              x: width - margin - tw,
              y: height - margin,
            });
          }
          if (fields.footerLeft) {
            page.drawText(processText(fields.footerLeft), {
              ...drawOpts,
              x: margin,
              y: margin - fontSize,
            });
          }
          if (fields.footerCenter) {
            const text = processText(fields.footerCenter);
            const tw = font.widthOfTextAtSize(text, fontSize);
            page.drawText(text, {
              ...drawOpts,
              x: (width - tw) / 2,
              y: margin - fontSize,
            });
          }
          if (fields.footerRight) {
            const text = processText(fields.footerRight);
            const tw = font.widthOfTextAtSize(text, fontSize);
            page.drawText(text, {
              ...drawOpts,
              x: width - margin - tw,
              y: margin - fontSize,
            });
          }
        }

        const pdfBytes = await pdfDoc.save();
        return {
          type: 'pdf',
          document: pdfDoc,
          bytes: new Uint8Array(pdfBytes),
          filename: input.filename.replace(/\.pdf$/i, '_hf.pdf'),
        };
      }),
    };
  }
}