All pages of PDF file that I am generating from my NestJS based AWS Lambda function are blank. When I generate PDF file and attach it to an email then I receive the correct file with all content in it.
But when I download the same file in browser from AWS Lambda GET API request, then a get a file with blank pages.
The following code works perfectly fine.
@Get('/send-pdf-email')
async sendPDF() {
const buffer = await this.reportsService.getPDFBuffer();
this.emailService.sendApplicationPDF({ filename: "report.pdf", data: buffer });
}
But when I generate the same PDF file and return in response then downloaded file has all pages blank.
@Get('/download-pdf')
@Header('Content-Type', 'application/pdf')
@Header('Content-Disposition', 'attachment; filename=report.pdf')
async getApplicationCompilancePDF(
@Param('id', ParseIntPipe) id: number,
@Res() res: Response,
) {
const buffer = await this.reportsService.getPDFBuffer();
const stream = this.reportsService.getReadableStream(buffer);
stream.pipe(res);
}
Here is my code for ReportsService
import { Injectable } from '@nestjs/common';
import htmlPdf from 'html-pdf';
import path from 'path';
import { Readable } from 'stream';
@Injectable()
export class ReportsService {
async getPDFBuffer(): Promise<Buffer> {
const html = "<p>Hello World!</p>";
return new Promise((resolve, reject) => {
htmlPdf.create(html, {
phantomPath: path.resolve(
process.cwd(),
"node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs"
),
}).toBuffer((err, buffer) => {
if (err) {
reject(err);
} else {
resolve(buffer);
}
});
});
}
getReadableStream(buffer: Buffer): Readable {
const stream = new Readable();
stream.push(buffer);
stream.push(null);
return stream;
}
}
Here I come two years later with a response for your issue. I hope this can help someone else to save hours. I have spent two days with the same issue and I finally get it working.
The problem is in the handler function. The http server instance created in the handler should specify that binary data is expected in the response. See the following code, the binarySettings are key. In this case I am also using serverless for deploying the app to AWS Lambda.
One final step is required. Go to you serverless.yaml add the binary types supported for your API Gateway
I tried to add application/pdf in this section. But It returned a corrupted pdf