-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatchExtract.js
More file actions
715 lines (593 loc) · 23.1 KB
/
batchExtract.js
File metadata and controls
715 lines (593 loc) · 23.1 KB
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
#!/usr/bin/env bun
import { readdirSync, statSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join, extname, basename } from 'node:path';
import process from 'node:process';
import { execSync } from 'node:child_process';
/**
* PDF Batch Extractor
* Extrai links e texto de múltiplos arquivos PDF de uma pasta
*
* Uso: bun batchExtract.js <caminho-da-pasta>
* Exemplo: bun batchExtract.js ./pdfs/
*/
class PDFBatchExtractor {
constructor(outputPath = null, preserveStructure = false) {
this.urlRegex = /https?:\/\/(?:[-\w.])+(?:\:[0-9]+)?(?:\/(?:[\w\/_.])*(?:\?(?:[\w&=%.])*)?(?:\#(?:[\w.])*)?)?/gi;
this.emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/gi;
this.processedCount = 0;
this.errorCount = 0;
this.results = [];
this.outputPath = outputPath;
this.preserveStructure = preserveStructure;
this.basePath = null;
}
async extractFromPDF(filePath) {
try {
console.log(`📄 Processando: ${basename(filePath)}`);
// Método 1: Usar pdftotext primeiro (mais confiável)
let text = '';
let pages = 0;
let metadata = {};
try {
const pdftotextResult = this.extractTextWithPdftotext(filePath);
if (pdftotextResult.text && pdftotextResult.text.length > 50) {
text = pdftotextResult.text;
pages = pdftotextResult.pages;
metadata = { extractor: 'pdftotext' };
console.log(`✅ pdftotext extraiu ${text.length} caracteres de ${pages} páginas`);
} else {
throw new Error('pdftotext não retornou texto suficiente');
}
} catch (pdftotextError) {
console.log('⚠️ pdftotext não disponível ou falhou, tentando pdf-parse...');
// Método 2: Tentar pdf-parse como fallback
const pdfParse = await import('pdf-parse');
const pdfBuffer = readFileSync(filePath);
let parseFunction = pdfParse.default;
if (!parseFunction) {
parseFunction = pdfParse;
}
const data = await parseFunction(pdfBuffer);
text = data.text || '';
pages = data.numpages || 0;
metadata = data.info || {};
console.log(`📊 Páginas encontradas: ${pages}`);
console.log(`📝 Caracteres extraídos: ${text.length}`);
}
// Extrai hyperlinks
const hyperlinks = await this.extractHyperlinks(filePath);
// Extrai URLs do texto também (como fallback)
const textUrls = this.extractURLs(text);
const emails = this.extractEmails(text);
// Combina hyperlinks clicáveis + URLs do texto
const allUrls = [...hyperlinks, ...textUrls];
const uniqueUrls = [...new Set(allUrls)];
const uniqueEmails = [...new Set(emails)];
// Referencia hyperlinks no texto
const hyperlinkReferences = this.findHyperlinkReferences(text, hyperlinks);
console.log(`🔗 Hyperlinks clicáveis encontrados: ${hyperlinks.length}`);
console.log(`🔗 URLs no texto encontrados: ${textUrls.length}`);
console.log(`🔗 Total de links únicos: ${uniqueUrls.length}`);
console.log(`📍 Referências de hyperlinks encontradas: ${hyperlinkReferences.length}`);
return {
text,
hyperlinks,
textUrls,
urls: uniqueUrls,
emails: uniqueEmails,
hyperlinkReferences,
pages,
metadata: { ...metadata, extractor: 'pdf-lib + pdf-parse' }
};
} catch (error) {
throw new Error(`Erro ao processar PDF: ${error.message}`);
}
}
async extractHyperlinks(filePath) {
try {
// Método 1: Usar pdf-lib (melhor para annotations)
try {
const { PDFDocument } = await import('pdf-lib');
const pdfBuffer = readFileSync(filePath);
const pdfDoc = await PDFDocument.load(pdfBuffer);
const hyperlinks = [];
const pages = pdfDoc.getPages();
for (let pageIndex = 0; pageIndex < pages.length; pageIndex++) {
const page = pages[pageIndex];
const annotations = page.node.Annots;
if (annotations) {
const annotArray = pdfDoc.context.lookup(annotations);
if (annotArray && annotArray.asArray) {
for (const annotRef of annotArray.asArray()) {
const annot = pdfDoc.context.lookup(annotRef);
if (annot && annot.dict) {
const action = annot.dict.lookup('A');
if (action && action.dict) {
const uri = action.dict.lookup('URI');
if (uri && uri.asString) {
const url = uri.asString();
if (url.startsWith('http') || url.startsWith('www')) {
hyperlinks.push(url);
}
}
}
}
}
}
}
}
if (hyperlinks.length > 0) {
console.log(`✅ pdf-lib encontrou ${hyperlinks.length} hyperlinks`);
return hyperlinks;
}
} catch (_pdfLibError) {
console.log('⚠️ pdf-lib falhou, tentando extração raw...');
}
// Método 2: Extração raw das annotations
const pdfBuffer = readFileSync(filePath);
const pdfString = pdfBuffer.toString('latin1');
const hyperlinks = [];
// Regex para encontrar URIs em annotations
const uriRegex = /\/URI\s*\(([^)]+)\)/g;
let match;
while ((match = uriRegex.exec(pdfString)) !== null) {
const uri = match[1];
if (uri && (uri.startsWith('http') || uri.includes('www.'))) {
hyperlinks.push(uri);
}
}
// Também busca por padrão /A << /S /URI /URI (URL)
const actionRegex = /\/A\s*<<[^>]*\/URI\s*\(([^)]+)\)/g;
while ((match = actionRegex.exec(pdfString)) !== null) {
const uri = match[1];
if (uri && (uri.startsWith('http') || uri.includes('www.'))) {
hyperlinks.push(uri);
}
}
console.log(`✅ Extração raw encontrou ${hyperlinks.length} hyperlinks`);
return hyperlinks;
} catch (error) {
console.log(`⚠️ Erro na extração de hyperlinks: ${error.message}`);
return [];
}
}
extractTextWithPdftotext(filePath) {
try {
// Verifica se pdftotext está disponível
execSync('which pdftotext', { stdio: 'ignore' });
// Executa pdftotext
const result = execSync(`pdftotext "${filePath}" -`, {
encoding: 'utf8',
maxBuffer: 1024 * 1024 * 10 // 10MB buffer
});
const text = result.toString().trim();
// Tenta obter número de páginas
let pages = 0;
try {
const pageResult = execSync(`pdfinfo "${filePath}" | grep Pages`, {
encoding: 'utf8',
stdio: 'pipe'
});
const pageMatch = pageResult.toString().match(/Pages:\s*(\d+)/);
if (pageMatch) {
pages = parseInt(pageMatch[1]);
}
} catch (_error) {
// Se pdfinfo falhar, estima baseado no texto
pages = Math.max(1, Math.ceil(text.length / 2000));
}
return {
text,
pages,
extractor: 'pdftotext'
};
} catch (error) {
throw new Error(`pdftotext falhou: ${error.message}`);
}
}
extractURLs(text) {
const urls = text.match(this.urlRegex) || [];
return urls.map(url => url.trim()).filter(url => url.length > 0);
}
extractEmails(text) {
const emails = text.match(this.emailRegex) || [];
return emails.map(email => email.trim()).filter(email => email.length > 0);
}
findHyperlinkReferences(text, hyperlinks) {
const references = [];
for (const hyperlink of hyperlinks) {
// Busca por padrões de referência no texto
const patterns = [
// Padrão: [Texto](@URL)
new RegExp(`\\[([^\\]]+)\\]\\(@${this.escapeRegex(hyperlink)}\\)`, 'gi'),
// Padrão: [Texto](URL)
new RegExp(`\\[([^\\]]+)\\]\\(${this.escapeRegex(hyperlink)}\\)`, 'gi'),
// Padrão: "Texto" (URL)
new RegExp(`"([^"]+)"\\s*\\(${this.escapeRegex(hyperlink)}\\)`, 'gi'),
// Padrão: Texto (URL)
new RegExp(`([^\\s]+)\\s*\\(${this.escapeRegex(hyperlink)}\\)`, 'gi')
];
for (const pattern of patterns) {
let match;
while ((match = pattern.exec(text)) !== null) {
const reference = {
url: hyperlink,
text: match[1] || match[0],
context: match[0],
position: match.index,
line: text.substring(0, match.index).split('\n').length,
type: 'explicit_reference'
};
// Evita duplicatas
if (!references.some(ref =>
ref.url === reference.url &&
ref.position === reference.position
)) {
references.push(reference);
}
}
}
// Se não encontrou referências explícitas, busca por contexto próximo
if (!references.some(ref => ref.url === hyperlink)) {
// Busca por texto próximo ao hyperlink no texto
const contextPattern = new RegExp(`([^\\n]{0,100})\\s*${this.escapeRegex(hyperlink)}\\s*([^\\n]{0,100})`, 'gi');
let match;
while ((match = contextPattern.exec(text)) !== null) {
const beforeContext = match[1].trim();
const afterContext = match[2].trim();
// Extrai texto relevante do contexto
const relevantText = this.extractRelevantTextFromContext(beforeContext, afterContext);
if (relevantText) {
const reference = {
url: hyperlink,
text: relevantText,
context: match[0],
position: match.index,
line: text.substring(0, match.index).split('\n').length,
type: 'contextual_reference'
};
references.push(reference);
break; // Apenas uma referência contextual por URL
}
}
}
// Se ainda não encontrou, busca por texto relacionado baseado no conteúdo da URL
if (!references.some(ref => ref.url === hyperlink)) {
const relatedText = this.findRelatedTextForUrl(text, hyperlink);
if (relatedText) {
const reference = {
url: hyperlink,
text: relatedText.text,
context: relatedText.context,
position: relatedText.position,
line: relatedText.line,
type: 'related_text'
};
references.push(reference);
}
}
}
return references;
}
extractRelevantTextFromContext(beforeContext, afterContext) {
// Tenta extrair texto relevante do contexto
const beforeWords = beforeContext.split(/\s+/).filter(word => word.length > 2);
const afterWords = afterContext.split(/\s+/).filter(word => word.length > 2);
// Pega as últimas palavras do contexto anterior
const relevantBefore = beforeWords.slice(-3).join(' ');
// Pega as primeiras palavras do contexto posterior
const relevantAfter = afterWords.slice(0, 3).join(' ');
// Combina contexto relevante
const relevantText = [relevantBefore, relevantAfter].filter(text => text.length > 0).join(' ');
return relevantText || 'Contexto não identificado';
}
findRelatedTextForUrl(text, url) {
// Extrai palavras-chave da URL para buscar texto relacionado
const urlKeywords = this.extractKeywordsFromUrl(url);
for (const keyword of urlKeywords) {
// Busca por texto que contenha a palavra-chave
const keywordPattern = new RegExp(`([^\\n]{0,50}\\b${this.escapeRegex(keyword)}\\b[^\\n]{0,50})`, 'gi');
let match;
while ((match = keywordPattern.exec(text)) !== null) {
const context = match[1].trim();
// Verifica se o contexto é relevante (não é apenas metadados)
if (this.isRelevantContext(context)) {
return {
text: this.extractTitleFromContext(context),
context: context,
position: match.index,
line: text.substring(0, match.index).split('\n').length
};
}
}
}
return null;
}
extractKeywordsFromUrl(url) {
// Extrai palavras-chave relevantes da URL
const keywords = [];
// Extrai domínio
const domainMatch = url.match(/https?:\/\/([^\/]+)/);
if (domainMatch) {
const domain = domainMatch[1];
const domainParts = domain.split('.');
keywords.push(...domainParts.filter(part => part.length > 2));
}
// Extrai palavras do caminho
const pathMatch = url.match(/https?:\/\/[^\/]+(.*)/);
if (pathMatch) {
const path = pathMatch[1];
const pathWords = path.split(/[\/\-_]/).filter(word =>
word.length > 2 &&
!word.match(/^\d+$/) && // Não números puros
!word.match(/^(form|view|file|d)$/i) // Palavras muito genéricas
);
keywords.push(...pathWords);
}
// Mapeia palavras-chave específicas
const keywordMap = {
'kabum': ['KaBuM', 'Kabum', 'kabum'],
'movidesk': ['Movidesk', 'movidesk', 'formulário', 'formulario'],
'form': ['formulário', 'formulario', 'form'],
'drive': ['Drive', 'drive', 'Google Drive'],
'google': ['Google', 'google'],
'trello': ['Trello', 'trello']
};
for (const [key, values] of Object.entries(keywordMap)) {
if (url.toLowerCase().includes(key)) {
keywords.push(...values);
}
}
return [...new Set(keywords)]; // Remove duplicatas
}
isRelevantContext(context) {
// Verifica se o contexto é relevante (não metadados)
const metadataWords = ['Mozilla', 'Skia', 'PDF', 'KHTML', 'Gecko', 'Linux', 'x86_64'];
const contextLower = context.toLowerCase();
for (const word of metadataWords) {
if (contextLower.includes(word.toLowerCase())) {
return false;
}
}
return context.length > 10; // Contexto deve ter pelo menos 10 caracteres
}
extractTitleFromContext(context) {
// Extrai um título relevante do contexto
const lines = context.split('\n').filter(line => line.trim().length > 0);
// Procura por linhas que parecem títulos (curtas, sem pontuação no final)
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length > 5 && trimmed.length < 100 && !trimmed.endsWith('.')) {
return trimmed;
}
}
// Se não encontrou título, retorna as primeiras palavras do contexto
const words = context.split(/\s+/).slice(0, 5).join(' ');
return words || 'Texto relacionado';
}
escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
async saveResults(data, inputPath) {
const baseName = basename(inputPath, extname(inputPath));
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
// Determina o caminho de saída
let outputDir = '.';
let fileName = `${baseName}_data_${timestamp}.json`;
if (this.outputPath) {
outputDir = this.outputPath;
// Se preserveStructure está ativo, mantém a estrutura de pastas
if (this.preserveStructure && this.basePath) {
const relativePath = inputPath.replace(this.basePath, '').replace(/^\//, '');
const relativeDir = join(outputDir, relativePath.replace(basename(inputPath), ''));
// Cria a estrutura de pastas se necessário
try {
const { mkdirSync } = await import('node:fs');
mkdirSync(relativeDir, { recursive: true });
outputDir = relativeDir;
} catch (error) {
console.log(`⚠️ Erro ao criar estrutura de pastas: ${error.message}`);
}
}
}
const jsonPath = join(outputDir, fileName);
// Salva apenas JSON com todos os dados
writeFileSync(jsonPath, JSON.stringify(data, null, 2), 'utf8');
return {
jsonPath
};
}
async convertFolder(folderPath) {
console.log(`🔄 Iniciando conversão em lote da pasta: ${folderPath}\n`);
// Define o caminho base para preservação de estrutura
this.basePath = folderPath;
// Verifica se a pasta existe
if (!existsSync(folderPath)) {
console.error(`❌ Erro: Pasta não encontrada: ${folderPath}`);
process.exit(1);
}
// Verifica se é uma pasta
if (!statSync(folderPath).isDirectory()) {
console.error(`❌ Erro: O caminho deve ser uma pasta: ${folderPath}`);
process.exit(1);
}
// Mostra configurações de saída
if (this.outputPath) {
console.log(`📁 Pasta de saída: ${this.outputPath}`);
if (this.preserveStructure) {
console.log(`📂 Preservando estrutura de pastas: SIM`);
} else {
console.log(`📂 Preservando estrutura de pastas: NÃO`);
}
console.log('');
}
// Busca todos os arquivos PDF na pasta
const pdfFiles = this.findPDFFiles(folderPath);
if (pdfFiles.length === 0) {
console.log('⚠️ Nenhum arquivo PDF encontrado na pasta.');
return;
}
console.log(`📁 Encontrados ${pdfFiles.length} arquivos PDF:`);
pdfFiles.forEach((file, index) => {
console.log(` ${index + 1}. ${basename(file)}`);
});
console.log('');
// Processa cada arquivo PDF
for (let i = 0; i < pdfFiles.length; i++) {
const filePath = pdfFiles[i];
const fileName = basename(filePath);
console.log(`📄 [${i + 1}/${pdfFiles.length}] Processando: ${fileName}`);
try {
const startTime = Date.now();
const data = await this.extractFromPDF(filePath);
const endTime = Date.now();
const processingTime = endTime - startTime;
// Salva os resultados
const paths = await this.saveResults(data, filePath);
const result = {
file: fileName,
path: filePath,
success: true,
processingTime: processingTime,
outputFile: paths.jsonPath,
stats: {
pages: data.pages,
hyperlinks: data.hyperlinks?.length || 0,
textUrls: data.textUrls?.length || 0,
totalUrls: data.urls?.length || 0,
emails: data.emails?.length || 0,
hyperlinkReferences: data.hyperlinkReferences?.length || 0,
textLength: data.text?.length || 0
}
};
this.results.push(result);
this.processedCount++;
console.log(`✅ Concluído em ${processingTime}ms`);
console.log(` 📊 Páginas: ${result.stats.pages}`);
console.log(` 🔗 Hyperlinks: ${result.stats.hyperlinks}`);
console.log(` 📧 Emails: ${result.stats.emails}`);
console.log(` 📍 Referências: ${result.stats.hyperlinkReferences}`);
console.log(` 💾 Salvo em: ${basename(paths.jsonPath)}\n`);
} catch (error) {
console.error(`❌ Erro ao processar ${fileName}: ${error.message}\n`);
this.errorCount++;
this.results.push({
file: fileName,
path: filePath,
success: false,
error: error.message
});
}
}
// Exibe resumo final
this.showSummary();
}
findPDFFiles(folderPath) {
const pdfFiles = [];
try {
const items = readdirSync(folderPath);
for (const item of items) {
const itemPath = join(folderPath, item);
const stat = statSync(itemPath);
if (stat.isFile() && extname(item).toLowerCase() === '.pdf') {
pdfFiles.push(itemPath);
} else if (stat.isDirectory()) {
// Busca recursivamente em subpastas
const subPdfs = this.findPDFFiles(itemPath);
pdfFiles.push(...subPdfs);
}
}
} catch (error) {
console.error(`❌ Erro ao ler pasta ${folderPath}: ${error.message}`);
}
return pdfFiles;
}
showSummary() {
console.log('='.repeat(60));
console.log('📊 RESUMO DA CONVERSÃO EM LOTE');
console.log('='.repeat(60));
console.log(`✅ Arquivos processados com sucesso: ${this.processedCount}`);
console.log(`❌ Arquivos com erro: ${this.errorCount}`);
console.log(`📁 Total de arquivos: ${this.results.length}`);
if (this.processedCount > 0) {
const totalHyperlinks = this.results
.filter(r => r.success)
.reduce((sum, r) => sum + r.stats.hyperlinks, 0);
const totalEmails = this.results
.filter(r => r.success)
.reduce((sum, r) => sum + r.stats.emails, 0);
const totalReferences = this.results
.filter(r => r.success)
.reduce((sum, r) => sum + r.stats.hyperlinkReferences, 0);
console.log(`🔗 Total de hyperlinks encontrados: ${totalHyperlinks}`);
console.log(`📧 Total de emails encontrados: ${totalEmails}`);
console.log(`📍 Total de referências encontradas: ${totalReferences}`);
}
if (this.errorCount > 0) {
console.log('\n❌ Arquivos com erro:');
this.results
.filter(r => !r.success)
.forEach(r => console.log(` - ${r.file}: ${r.error}`));
}
console.log('\n🎉 Conversão em lote concluída!');
}
}
// Função principal
async function main() {
const args = process.argv.slice(2);
if (args.length === 0) {
console.log(`
🔄 PDF Batch Extractor
📁 USO: bun batchExtract.js <caminho-da-pasta> [opções]
📄 EXEMPLOS:
bun batchExtract.js ./pdfs/
bun batchExtract.js /caminho/para/pasta/pdf/
bun batchExtract.js . --output ./resultados/
bun batchExtract.js ./pdfs/ --output ./saida/ --preserve-structure
🚩 OPÇÕES:
--output <pasta> Pasta onde salvar os arquivos JSON
--preserve-structure Manter a mesma estrutura de pastas da origem
💡 FUNCIONALIDADES:
- Processa todos os PDFs de uma pasta
- Busca recursivamente em subpastas
- Gera arquivo JSON para cada PDF
- Exibe resumo detalhado
- Tratamento de erros individual
- Controle de pasta de saída
- Preservação de estrutura de pastas
📋 PRÉ-REQUISITOS:
- Bun instalado
- Poppler Utils (pdftotext) instalado
- Dependências: bun install
`);
process.exit(1);
}
// Processa argumentos
let folderPath = null;
let outputPath = null;
let preserveStructure = false;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--output' && i + 1 < args.length) {
outputPath = args[i + 1];
i++; // Pula o próximo argumento
} else if (arg === '--preserve-structure') {
preserveStructure = true;
} else if (!folderPath && !arg.startsWith('--')) {
folderPath = arg;
}
}
if (!folderPath) {
console.error('❌ Erro: Caminho da pasta é obrigatório');
process.exit(1);
}
try {
const converter = new PDFBatchExtractor(outputPath, preserveStructure);
await converter.convertFolder(folderPath);
} catch (error) {
console.error(`❌ Erro fatal: ${error.message}`);
process.exit(1);
}
}
// Executa o script
main().catch(console.error);