"Error loading PDF document."
Closed this issue · 4 comments
I can create a PDF file with puppeteer-report and also save it. The file size seems to be correct, but when I open the file in the browser I get the message "Error loading PDF document. I use the following code:
const express = require('express');
const puppeteer = require('puppeteer');
const puppeteerReport = require('puppeteer-report');
const app = express();
const port = 3000;
app.get('/build', async (req, res) => {
const url = req.query.url;
const filename = req.query.filename ? req.query.filename : 'default';
let pdfBuffer;
if (!url) {
res.status(400).send('Missing URL parameter');
return;
}
try {
// Open Chromium in a new Headless Mode and deactivte sandbox
const browser = await puppeteer.launch({
executablePath: '/usr/bin/chromium-browser',
headless: 'new',
args: ["--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage"]
});
// Open a new Page with given url
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle2' });
pdfBuffer = await puppeteerReport.pdfPage(page, {
format: 'A4'
});
await browser.close();
} catch (error) {
console.error('Ein Fehler ist aufgetreten:', error);
}
if (pdfBuffer) {
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `inline; filename=${filename}.pdf; title=${filename}`);
res.send(pdfBuffer);
} else {
console.error('Ein Fehler ist aufgetreten: pdfBuffer', pdfBuffer);
}
});
app.listen(port, () => {
console.log(`Microservice listening at http://localhost:${port}`);
});
If I replace the function await puppeteerReport.pdfPage(page,...
with the puppeteer following code, it works. But I want to use this package because I want to include the header and footer.
pdfBuffer = await page.pdf({
format: 'A4'
});
Any idea what is wrong with my code?
puppeteer version: 21.3.8
puppeteer-core: 21.3.8
puppeteer-report: 3.1.0
pdf-lib: 1.17.1
datenblatt.pdf
the output of puppeteerReport.pdfPage is an array of bytes (Uint8Array), if you open your file in a notepad, you can see that.
Check this link: https://stackoverflow.com/questions/62657362/send-binary-response-from-uint8array-in-express-js
Please don't hesitate to reopen it if you still require assistance.
Thanks, you helped me. I save the PDF file on the host with following code and with fs I'm able to read and send it
pdfBuffer = await puppeteerReport.pdfPage(page, {
path: "filename.pdf",
format: 'A4'
});
You're welcome, that solution comes with a performance penalty as it adds extra IO operation for writing to the file and then reading it back