PDF being compressed when downloaded

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;

No body can help me with this?

@salomaos In case this is still open for you: the server side of that handler looks fine. NocoBase’s dataWrapping middleware returns early when ctx.body is a Buffer or a stream, so the bytes leave the server as they are. That points at the client.

The usual cause is a frontend request made with the default JSON response type. The PDF bytes get decoded as text, so the saved file changes size and readers refuse to open it. The built-in export plugin handles the same case like this:

const { data } = await api.request({
  url: 'downloadPdf:downloadPdf',
  method: 'get',
  responseType: 'blob',
});
const blob = new Blob([data], { type: 'application/pdf' });
saveAs(blob, 'oqueeframework.pdf'); // from file-saver

To confirm where it breaks, call the endpoint with curl and an API token, then compare the byte count with stats.size from your log:

curl -H "Authorization: Bearer <token>" -o test.pdf "http://localhost:13000/api/downloadPdf:downloadPdf"

If test.pdf opens, the server is fine and only the frontend call needs responseType: 'blob'.

(Disclosure: I’m connected to thirds.ai.)