I’m trying to create a plugin that generate a PDF and send it back to the user, but the file sent has a smaller size and cant be open.
Can anyone help me with this?
Code example:
import { Plugin } from '@nocobase/server';
import * as fs from 'fs';
import * as path from 'path';
export class PluginHelloServer extends Plugin {
async afterAdd() {}
async beforeLoad() {}
async load() {
this.app.resourceManager.define({
name: 'downloadPdf',
actions: {
downloadPdf: this.downloadPdfHandler.bind(this),
},
});
this.app.acl.allow('*', 'downloadPdf', 'loggedIn');
}
async downloadPdfHandler(ctx, next) {
const relativeFilePath = path.join(
'packages',
'plugins',
'@my-project',
'plugin-hello',
'src',
'server',
'oqueeframework.pdf',
);
const absolutePath = path.resolve(relativeFilePath);
try {
console.log('\n=== PDF DOWNLOAD ===');
console.log('1. Path Absoluto:', absolutePath);
if (!fs.existsSync(absolutePath)) {
console.log('2. ERRO: Arquivo não existe');
ctx.status = 404;
ctx.body = { error: 'Arquivo não encontrado' };
return;
}
console.log('2. Arquivo existe ✓');
if (path.extname(absolutePath).toLowerCase() !== '.pdf') {
ctx.status = 400;
ctx.body = { error: 'Arquivo deve ser PDF' };
return;
}
const stats = fs.statSync(absolutePath);
const fileName = path.basename(absolutePath);
const headerBuffer = Buffer.alloc(4);
const fd = fs.openSync(absolutePath, 'r');
fs.readSync(fd, headerBuffer, 0, 4, 0);
fs.closeSync(fd);
if (headerBuffer.toString('utf8', 0, 4) !== '%PDF') {
ctx.status = 400;
ctx.body = { error: 'Arquivo não é um PDF válido' };
return;
}
console.log('3. Nome:', fileName);
console.log('4. Tamanho:', stats.size, 'bytes');
console.log('5. Header PDF válido ✓');
console.log('6. Lendo arquivo inteiro para Buffer...');
const pdfBuffer = fs.readFileSync(absolutePath);
// CRÍTICO: Definir headers
ctx.set('x-no-compression', 'true');
ctx.remove('Content-Encoding');
ctx.set('Content-Length', pdfBuffer.length.toString());
ctx.attachment(encodeURIComponent(fileName));
ctx.set('Cache-Control', 'no-cache');
ctx.body = pdfBuffer;
ctx.set('x-no-compression', 'true');
ctx.remove('Content-Encoding');
ctx.type = 'application/pdf';
ctx.status = 200;
} catch (error) {
console.error('ERRO GERAL no downloadPdfHandler:', error);
ctx.status = 500;
ctx.body = {
error: 'Erro interno do servidor',
message: error.message,
};
}
}
}
export default PluginHelloServer;