-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
911 lines (757 loc) · 30 KB
/
main.js
File metadata and controls
911 lines (757 loc) · 30 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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
#!/usr/bin/env bun
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { basename, extname } from 'node:path';
import process from 'node:process';
import { execSync } from 'node:child_process';
/**
* PDF Link Extractor - Versão Melhorada
* Extrai texto legível e todos os links (URLs) de arquivos PDF
*
* Funcionalidades:
* - Extração de hyperlinks clicáveis (annotations)
* - Extração de texto legível (pdftotext + múltiplos métodos)
* - Detecção automática de texto encodado
* - Extração de emails
* - Múltiplos métodos de fallback
*
* Métodos de extração (em ordem de prioridade):
* 1. pdftotext (mais confiável - requer poppler-utils)
* 2. pdf-parse (biblioteca JavaScript)
* 3. pdf-lib (objetos de página)
* 4. Extração raw (regex e streams)
*
* Uso: bun pdf-extractor.js <caminho-do-pdf>
*/
export class PDFLinkExtractor {
constructor() {
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;
}
async extractFromPDF(filePath) {
try {
console.log(`📄 Processando: ${basename(filePath)}`);
// Método 1: Usar pdf-lib para extrair annotations (hyperlinks)
const hyperlinks = await this.extractHyperlinks(filePath);
// Método 2: pdf-parse para texto completo
let text = '';
let pages = 0;
let metadata = {};
try {
// Método 1: Tentar pdftotext primeiro (mais confiável)
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}`);
// Se o texto está muito pequeno ou parece estar encodado, tenta método alternativo
if (text.length < 100 || this.isEncodedText(text) || this.isMetadataOnly(text)) {
console.log('⚠️ Texto parece estar encodado ou contém apenas metadados, tentando método alternativo...');
const altText = await this.extractTextAlternative(filePath);
if (altText.length > text.length) {
text = altText;
console.log(`✅ Método alternativo extraiu ${text.length} caracteres`);
}
}
}
} catch (_pdfParseError) {
console.log('⚠️ pdf-parse falhou, tentando extração alternativa...');
text = await this.extractTextAlternative(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, // Links clicáveis específicos
textUrls, // URLs que aparecem no texto
urls: uniqueUrls, // Todos combinados
emails: uniqueEmails,
hyperlinkReferences, // Referências dos hyperlinks no texto
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 [];
}
}
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, '\\$&');
}
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}`);
}
}
async extractTextAlternative(filePath) {
try {
// Método 1: Tentar com pdf2pic + OCR (se disponível)
try {
const { PDFDocument } = await import('pdf-lib');
const pdfBuffer = readFileSync(filePath);
const pdfDoc = await PDFDocument.load(pdfBuffer);
const pages = pdfDoc.getPages();
let extractedText = '';
for (let pageIndex = 0; pageIndex < pages.length; pageIndex++) {
const page = pages[pageIndex];
// Extrai texto dos objetos de página
const pageText = this.extractTextFromPageObject(page);
if (pageText) {
extractedText += pageText + '\n';
}
}
if (extractedText.trim().length > 0) {
console.log(`✅ pdf-lib extraiu ${extractedText.length} caracteres de texto`);
return extractedText;
}
} catch (_pdfLibError) {
console.log('⚠️ pdf-lib falhou na extração de texto...');
}
// Método 2: Extração raw focada no conteúdo real
const pdfBuffer = readFileSync(filePath);
const pdfString = pdfBuffer.toString('latin1');
let extractedText = '';
// Método 2a: Busca por texto em streams de conteúdo (mais específico)
const contentStreamRegex = /\/Contents\s*(\d+\s+\d+\s+R)\s*\/MediaBox/g;
let match;
// Primeiro, encontra streams de conteúdo
while ((match = contentStreamRegex.exec(pdfString)) !== null) {
const streamRef = match[1];
const streamRegex = new RegExp(`${streamRef}\\s*<<[^>]*>>\\s*stream\\s*([\\s\\S]*?)\\s*endstream`, 'g');
let streamMatch;
while ((streamMatch = streamRegex.exec(pdfString)) !== null) {
const streamContent = streamMatch[1];
const textFromStream = this.extractTextFromStream(streamContent);
if (textFromStream) {
extractedText += textFromStream + ' ';
}
}
}
// Método 2b: Busca por texto em operadores de texto PDF
if (extractedText.length < 50) {
const textOperatorsRegex = /BT\s*([\s\S]*?)\s*ET/g;
while ((match = textOperatorsRegex.exec(pdfString)) !== null) {
const textBlock = match[1];
const textFromBlock = this.extractTextFromTextBlock(textBlock);
if (textFromBlock) {
extractedText += textFromBlock + ' ';
}
}
}
// Método 2c: Busca por strings de texto diretas (fallback)
if (extractedText.length < 50) {
const directTextRegex = /\((.*?)\)/g;
while ((match = directTextRegex.exec(pdfString)) !== null) {
const text = match[1];
if (text && text.length > 3 && this.isContentText(text)) {
extractedText += text + ' ';
}
}
}
console.log(`✅ Extração raw extraiu ${extractedText.length} caracteres`);
return extractedText.trim();
} catch (error) {
console.log(`⚠️ Erro na extração alternativa: ${error.message}`);
return '';
}
}
extractTextFromPageObject(page) {
try {
// Tenta extrair texto dos objetos de página do pdf-lib
const pageDict = page.node;
if (pageDict && pageDict.dict) {
const contents = pageDict.dict.lookup('Contents');
if (contents) {
// Implementação básica de extração de conteúdo
return this.extractTextFromContents(contents);
}
}
return '';
} catch (_error) {
return '';
}
}
extractTextFromContents(contents) {
// Implementação simplificada para extrair texto de objetos de conteúdo
try {
if (contents.asString) {
return contents.asString();
}
return '';
} catch (_error) {
return '';
}
}
decodeFlateStream(streamData) {
// Implementação básica de decodificação FlateDecode
// Em um ambiente real, você usaria uma biblioteca como zlib
try {
// Remove caracteres de controle e extrai texto legível
// eslint-disable-next-line no-control-regex
const cleanData = streamData.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, '');
const textMatches = cleanData.match(/[a-zA-Z0-9\s.,;:!?@#$%&*()_+\-=\[\]{}|\\:";'<>?,.\/]+/g);
return textMatches ? textMatches.join(' ') : '';
} catch (_error) {
return '';
}
}
isReadableText(text) {
// Verifica se o texto é legível (contém principalmente caracteres imprimíveis)
const printableChars = text.replace(/[^a-zA-Z0-9\s.,;:!?@#$%&*()_+\-=\[\]{}|\\:";'<>?,.\/]/g, '').length;
const totalChars = text.length;
return totalChars > 0 && (printableChars / totalChars) > 0.7;
}
isEncodedText(text) {
// Detecta se o texto está encodado (contém muitos caracteres não imprimíveis)
if (!text || text.length === 0) return true;
// Conta caracteres imprimíveis vs não imprimíveis
const printableChars = text.replace(/[^a-zA-Z0-9\s.,;:!?@#$%&*()_+\-=\[\]{}|\\:";'<>?,.\/]/g, '').length;
const totalChars = text.length;
const printableRatio = printableChars / totalChars;
// Se menos de 50% dos caracteres são imprimíveis, provavelmente está encodado
if (printableRatio < 0.5) return true;
// Verifica se há muitos caracteres de controle
// eslint-disable-next-line no-control-regex
const controlChars = text.match(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g);
if (controlChars && controlChars.length > text.length * 0.1) return true;
// Verifica se há muitos caracteres especiais de PDF
const pdfSpecialChars = text.match(/[<>\[\]()\/]/g);
if (pdfSpecialChars && pdfSpecialChars.length > text.length * 0.3) return true;
return false;
}
extractTextFromStream(streamContent) {
try {
let text = '';
// Remove caracteres de controle e decodifica
const cleanStream = streamContent.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, '');
// Busca por operadores de texto TJ (texto com ajuste)
const tjRegex = /\[(.*?)\]\s*TJ/g;
let match;
while ((match = tjRegex.exec(cleanStream)) !== null) {
const textArray = match[1];
const textParts = textArray.match(/\((.*?)\)/g);
if (textParts) {
textParts.forEach(part => {
const cleanText = part.replace(/[()]/g, '');
if (cleanText && this.isContentText(cleanText)) {
text += cleanText + ' ';
}
});
}
}
// Busca por operadores Tj (texto simples)
const tjSimpleRegex = /\((.*?)\)\s*Tj/g;
while ((match = tjSimpleRegex.exec(cleanStream)) !== null) {
const textContent = match[1];
if (textContent && this.isContentText(textContent)) {
text += textContent + ' ';
}
}
return text.trim();
} catch (_error) {
return '';
}
}
extractTextFromTextBlock(textBlock) {
try {
let text = '';
// Busca por strings de texto em blocos BT...ET
const textRegex = /\((.*?)\)/g;
let match;
while ((match = textRegex.exec(textBlock)) !== null) {
const textContent = match[1];
if (textContent && this.isContentText(textContent)) {
text += textContent + ' ';
}
}
return text.trim();
} catch (_error) {
return '';
}
}
isContentText(text) {
// Verifica se o texto é conteúdo real do documento (não metadados)
if (!text || text.length < 2) return false;
// Filtra metadados comuns
const metadataPatterns = [
/^Mozilla\/\d+/i,
/^Skia\/PDF/i,
/^D:\d{14}/,
/^pt-BR$/i,
/^Atlassian Sans$/i,
/^image-\d{8}-\d{6}\.png$/i,
/^%V@N$/,
/^RFd/,
/^KHTML/i,
/^like Gecko/i,
/^X11; Linux x86_64/i
];
for (const pattern of metadataPatterns) {
if (pattern.test(text)) {
return false;
}
}
// Verifica se é texto legível
if (!this.isReadableText(text)) return false;
// Verifica se não é apenas caracteres especiais
const specialChars = text.replace(/[a-zA-Z0-9\s.,;:!?@#$%&*()_+\-=\[\]{}|\\:";'<>?,.\/]/g, '').length;
if (specialChars > text.length * 0.5) return false;
return true;
}
isMetadataOnly(text) {
// Verifica se o texto contém apenas metadados e informações técnicas
if (!text || text.length === 0) return true;
const metadataKeywords = [
'Mozilla', 'Skia', 'PDF', 'KHTML', 'Gecko', 'Linux', 'x86_64',
'Atlassian', 'Sans', 'pt-BR', 'image-', '.png', '%V@N', 'RFd',
'D:20250714154312', 'HeadlessChrome', 'Safari'
];
let metadataCount = 0;
const words = text.split(/\s+/);
for (const word of words) {
for (const keyword of metadataKeywords) {
if (word.includes(keyword)) {
metadataCount++;
break;
}
}
}
// Se mais de 70% das palavras são metadados, considera apenas metadados
return metadataCount > words.length * 0.7;
}
generateReport(data, outputPath) {
const report = `
=====================================
📄 RELATÓRIO DE EXTRAÇÃO DE LINKS PDF
=====================================
📁 Arquivo processado: ${outputPath}
📊 Total de páginas: ${data.pages}
📝 Caracteres extraídos: ${data.text.length}
🔗 Hyperlinks clicáveis: ${data.hyperlinks?.length || 0}
🔗 URLs no texto: ${data.textUrls?.length || 0}
🔗 Total de links únicos: ${data.urls.length}
📧 Emails encontrados: ${data.emails.length}
=====================================
🎯 HYPERLINKS CLICÁVEIS (${data.hyperlinks?.length || 0})
=====================================
${data.hyperlinks?.length > 0 ?
'Estes são os links que você pode clicar no PDF:\n\n' +
data.hyperlinks.map((url, i) => `${i + 1}. ${url}`).join('\n') :
'Nenhum hyperlink clicável encontrado.'}
=====================================
🔗 URLs ENCONTRADOS NO TEXTO (${data.textUrls?.length || 0})
=====================================
${data.textUrls?.length > 0 ?
'URLs que aparecem como texto no PDF:\n\n' +
data.textUrls.map((url, i) => `${i + 1}. ${url}`).join('\n') :
'Nenhuma URL encontrada no texto.'}
=====================================
📧 EMAILS EXTRAÍDOS (${data.emails.length})
=====================================
${data.emails.length > 0 ? data.emails.map((email, i) => `${i + 1}. ${email}`).join('\n') : 'Nenhum email encontrado.'}
=====================================
📄 TEXTO COMPLETO
=====================================
${data.text}
=====================================
ℹ️ METADADOS DO PDF
=====================================
${Object.entries(data.metadata).map(([key, value]) => `${key}: ${value}`).join('\n')}
`;
return report;
}
saveResults(data, inputPath) {
const baseName = basename(inputPath, extname(inputPath));
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
// Salva apenas JSON com todos os dados
const jsonPath = `${baseName}_data_${timestamp}.json`;
writeFileSync(jsonPath, JSON.stringify(data, null, 2), 'utf8');
return {
jsonPath
};
}
}
// Função principal
async function main() {
const args = process.argv.slice(2);
if (args.length === 0) {
console.log(`
🔧 USO: bun pdf-extractor.js <caminho-do-pdf>
📄 EXEMPLO:
bun pdf-extractor.js documento.pdf
bun pdf-extractor.js /caminho/para/arquivo.pdf
📦 INSTALAÇÃO DE DEPENDÊNCIAS:
bun add pdf-parse
🔧 INSTALAÇÃO RECOMENDADA (para melhor extração de texto):
# macOS:
brew install poppler
# Ubuntu/Debian:
sudo apt-get install poppler-utils
# Windows:
scoop install poppler
💡 MÉTODOS DE EXTRAÇÃO:
1. pdftotext (mais confiável - requer poppler-utils)
2. pdf-parse (biblioteca JavaScript)
3. pdf-lib (objetos de página)
4. Extração raw (regex e streams)
✨ O script irá gerar:
- Dados completos (.json) com texto, links e referências
`);
process.exit(1);
}
const filePath = args[0];
// Verifica se o arquivo existe
if (!existsSync(filePath)) {
console.error(`❌ Erro: Arquivo não encontrado: ${filePath}`);
process.exit(1);
}
// Verifica se é um PDF
if (extname(filePath).toLowerCase() !== '.pdf') {
console.error(`❌ Erro: O arquivo deve ter extensão .pdf`);
process.exit(1);
}
try {
console.log('🚀 Iniciando extração...\n');
const extractor = new PDFLinkExtractor();
const data = await extractor.extractFromPDF(filePath);
console.log(`\n✅ Extração concluída!`);
console.log(`🔗 Links encontrados: ${data.urls.length}`);
console.log(`📧 Emails encontrados: ${data.emails.length}\n`);
// Mostra preview dos primeiros links
if (data.urls.length > 0) {
console.log('🔗 Preview dos links encontrados:');
data.urls.slice(0, 5).forEach((url, i) => {
console.log(` ${i + 1}. ${url}`);
});
if (data.urls.length > 5) {
console.log(` ... e mais ${data.urls.length - 5} links\n`);
}
}
// Salva os resultados
const paths = extractor.saveResults(data, filePath);
console.log('💾 Arquivo gerado:');
console.log(`📊 Dados JSON: ${paths.jsonPath}`);
// Mostra preview das referências de hyperlinks
if (data.hyperlinkReferences && data.hyperlinkReferences.length > 0) {
console.log('\n📍 Referências de hyperlinks encontradas:');
data.hyperlinkReferences.slice(0, 3).forEach((ref, i) => {
console.log(` ${i + 1}. "${ref.text}" → ${ref.url}`);
console.log(` Contexto: ${ref.context.substring(0, 80)}...`);
});
if (data.hyperlinkReferences.length > 3) {
console.log(` ... e mais ${data.hyperlinkReferences.length - 3} referências\n`);
}
}
} catch (error) {
console.error(`❌ Erro: ${error.message}`);
process.exit(1);
}
}
// Executa o script
main().catch(console.error);