Files
advx/scripts/test_pdf_operations.ts
rodrigo 61a1631519 pdf: add new feature
Signed-off-by: Rodrigo Bertoldo de Sousa Martins <rodrigo.sousa.577@gmail.com>
2026-02-27 17:32:18 -03:00

272 lines
8.3 KiB
TypeScript

import { PDFService } from '../src/services/pdfService';
import path from 'path';
import fs from 'fs/promises';
/**
* Script de teste para funcionalidades de PDF
*
* ATENÇÃO: Este é um script de teste. Certifique-se de ter arquivos de teste
* disponíveis antes de executar.
*
* Uso:
* ts-node scripts/test_pdf_operations.ts
*/
async function testPDFInfo() {
console.log('\n=== Testando: Informações do PDF ===');
try {
const testPdfPath = path.join(process.cwd(), 'test', 'sample.pdf');
// Verifica se o arquivo existe
try {
await fs.access(testPdfPath);
} catch {
console.log('⚠️ Arquivo de teste não encontrado. Pulando teste.');
return;
}
const info = await PDFService.getPDFInfo(testPdfPath);
console.log('✅ Informações obtidas com sucesso:');
console.log(' Páginas:', info.pages);
console.log(' Tamanho:', (info.size / 1024).toFixed(2), 'KB');
console.log(' Título:', info.title || 'N/A');
} catch (error) {
console.error('❌ Erro:', error);
}
}
async function testCompression() {
console.log('\n=== Testando: Compressão de PDF ===');
try {
const testPdfPath = path.join(process.cwd(), 'test', 'sample.pdf');
try {
await fs.access(testPdfPath);
} catch {
console.log('⚠️ Arquivo de teste não encontrado. Pulando teste.');
return;
}
const result = await PDFService.compressPDF(testPdfPath, undefined, {
quality: 95,
});
console.log('✅ Compressão concluída:');
console.log(' Tamanho original:', (result.originalSize / 1024).toFixed(2), 'KB');
console.log(' Tamanho comprimido:', (result.compressedSize / 1024).toFixed(2), 'KB');
console.log(' Redução:', result.reduction.toFixed(2), '%');
console.log(' Arquivo salvo em:', result.outputPath);
// Limpa o arquivo de teste
await fs.unlink(result.outputPath);
} catch (error) {
console.error('❌ Erro:', error);
}
}
async function testSplit() {
console.log('\n=== Testando: Divisão de PDF ===');
try {
const testPdfPath = path.join(process.cwd(), 'test', 'sample.pdf');
try {
await fs.access(testPdfPath);
} catch {
console.log('⚠️ Arquivo de teste não encontrado. Pulando teste.');
return;
}
// Primeiro, verifica quantas páginas o PDF tem
const info = await PDFService.getPDFInfo(testPdfPath);
if (info.pages < 2) {
console.log('⚠️ PDF tem menos de 2 páginas. Pulando teste de divisão.');
return;
}
const outputPaths = await PDFService.splitPDF(testPdfPath, {
splitType: 'chunks',
chunkSize: 1,
});
console.log('✅ Divisão concluída:');
console.log(' Arquivos criados:', outputPaths.length);
// Limpa os arquivos de teste
for (const outputPath of outputPaths) {
await fs.unlink(outputPath);
}
} catch (error) {
console.error('❌ Erro:', error);
}
}
async function testMerge() {
console.log('\n=== Testando: Mesclagem de PDFs ===');
try {
const testPdf1 = path.join(process.cwd(), 'test', 'sample1.pdf');
const testPdf2 = path.join(process.cwd(), 'test', 'sample2.pdf');
try {
await fs.access(testPdf1);
await fs.access(testPdf2);
} catch {
console.log('⚠️ Arquivos de teste não encontrados. Pulando teste.');
return;
}
const outputPath = await PDFService.mergePDFs({
filePaths: [testPdf1, testPdf2],
outputPath: path.join(process.cwd(), 'storage', 'pdf-output', 'test-merged.pdf'),
});
console.log('✅ Mesclagem concluída:');
console.log(' Arquivo salvo em:', outputPath);
// Limpa o arquivo de teste
await fs.unlink(outputPath);
} catch (error) {
console.error('❌ Erro:', error);
}
}
async function testImagesToPDF() {
console.log('\n=== Testando: Imagens para PDF ===');
try {
const testImage1 = path.join(process.cwd(), 'test', 'image1.png');
const testImage2 = path.join(process.cwd(), 'test', 'image2.png');
try {
await fs.access(testImage1);
} catch {
console.log('⚠️ Imagens de teste não encontradas. Pulando teste.');
return;
}
const imagePaths = [testImage1];
try {
await fs.access(testImage2);
imagePaths.push(testImage2);
} catch {
// Ignora se a segunda imagem não existe
}
const outputPath = await PDFService.imagesToPDF({
imagePaths,
outputPath: path.join(process.cwd(), 'storage', 'pdf-output', 'test-images.pdf'),
fitToPage: true,
});
console.log('✅ Conversão concluída:');
console.log(' Imagens processadas:', imagePaths.length);
console.log(' Arquivo salvo em:', outputPath);
// Limpa o arquivo de teste
await fs.unlink(outputPath);
} catch (error) {
console.error('❌ Erro:', error);
}
}
async function testPDFToImages() {
console.log('\n=== Testando: PDF para Imagens ===');
try {
const testPdfPath = path.join(process.cwd(), 'test', 'sample.pdf');
try {
await fs.access(testPdfPath);
} catch {
console.log('⚠️ Arquivo de teste não encontrado. Pulando teste.');
return;
}
const outputPaths = await PDFService.pdfToImages(testPdfPath, {
format: 'png',
quality: 95,
density: 150, // Menor DPI para teste mais rápido
pages: [1], // Apenas primeira página
});
console.log('✅ Conversão concluída:');
console.log(' Imagens criadas:', outputPaths.length);
// Limpa os arquivos de teste
for (const outputPath of outputPaths) {
await fs.unlink(outputPath);
}
} catch (error) {
console.error('❌ Erro:', error);
}
}
async function testOCR() {
console.log('\n=== Testando: OCR ===');
console.log('⚠️ OCR pode levar vários segundos. Aguarde...');
try {
const testPdfPath = path.join(process.cwd(), 'test', 'sample-text.pdf');
try {
await fs.access(testPdfPath);
} catch {
console.log('⚠️ Arquivo de teste não encontrado. Pulando teste.');
return;
}
const result = await PDFService.performOCR(testPdfPath, {
language: 'por',
pages: [1], // Apenas primeira página
});
console.log('✅ OCR concluído:');
console.log(' Confiança:', result.confidence.toFixed(2), '%');
console.log(' Páginas processadas:', result.pages.length);
console.log(' Texto extraído (primeiros 100 caracteres):');
console.log(' ', result.text.substring(0, 100).replace(/\n/g, ' '));
} catch (error) {
console.error('❌ Erro:', error);
}
}
async function main() {
console.log('╔════════════════════════════════════════════╗');
console.log('║ Teste de Operações de PDF ║');
console.log('╚════════════════════════════════════════════╝');
console.log('\nPré-requisitos:');
console.log('- Coloque arquivos de teste na pasta "test/"');
console.log('- sample.pdf: PDF com múltiplas páginas');
console.log('- sample1.pdf e sample2.pdf: PDFs para mesclagem');
console.log('- image1.png e image2.png: Imagens para conversão');
console.log('- sample-text.pdf: PDF com texto para OCR');
// Criar diretório de teste se não existir
const testDir = path.join(process.cwd(), 'test');
try {
await fs.mkdir(testDir, { recursive: true });
} catch {
// Ignora se já existe
}
await PDFService.initialize();
await testPDFInfo();
await testCompression();
await testSplit();
await testMerge();
await testImagesToPDF();
await testPDFToImages();
await testOCR();
console.log('\n╔════════════════════════════════════════════╗');
console.log('║ Testes concluídos! ║');
console.log('╚════════════════════════════════════════════╝\n');
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error('\n❌ Erro fatal durante os testes:', error);
process.exit(1);
});