Reputation: 338
I use puppeteer to generate a pdf on backend and send it to front end with codes as below:
exports.createPdf = async (req, res) => {
const { resumeContent } = req.body;
console.log("datadatadatadatadatadatadatadatadatadata", resumeContent);
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(resumeContent, { waitUntil: ['domcontentloaded', 'networkidle0'] });
const resumePdf = await page.pdf(
// { path: './resume.pdf' }
);
await browser.close();
res.set({ 'Content-Type': 'application/pdf', 'Content-Length': resumePdf.length });
res.send(resumePdf);
};
if I add { path: './resume.pdf' }
, puppteer will save the pdf file in back end server, which I have checked and it is exactly what I want.
Now I hope to send it to front end instead of saving it on back end, and my front end codes showed as below:
await dispatch({
type: 'resume/createResumePdf',
payload: {
resumeContent
}
});
console.log("this.props.resumePdf", this.props.resumePdf)
const blob = new Blob([this.props.resumePdf], {
type: 'application/pdf'
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'resume.pdf';
link.click();
this.props.resumePdf
is a string like
%PDF-1.4
%����
1 0 obj
<</Creator (Chromium)
/Producer (Skia/PDF m90)
/CreationDate (D:20210412022817+00'00')
/ModDate (D:20210412022817+00'00')>>
endobj
3 0 obj
<</ca 1
/BM /Normal>>
endobj
12 0 obj...
However, I could only get a blank pdf on front end. Most implements are referred from https://blog.risingstack.com/pdf-from-html-node-js-puppeteer/
Upvotes: 6
Views: 4528
Reputation: 338
Download File from Bytes in JavaScript Downloaded PDF looks empty although it contains some data
Here is the answer, I should encode the pdf string into base64 on backend and then send it to frontend to avoid "byte-shaving". On frontend, I should convert the base64 string to Uint8 array then feed it to Blob.
Upvotes: 4