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;
}
}