2018-04-14 19:14:02 +00:00
|
|
|
const frappe = require('frappejs');
|
|
|
|
const fs = require('fs');
|
|
|
|
const path = require('path');
|
|
|
|
const { getTmpDir } = require('frappejs/server/utils');
|
|
|
|
const { getHTML } = require('frappejs/common/print');
|
|
|
|
const { getRandomString } = require('frappejs/utils');
|
2018-03-29 18:51:56 +00:00
|
|
|
|
2021-11-09 10:42:39 +00:00
|
|
|
async function makePDF(html, filePath) {
|
2019-12-06 18:12:06 +00:00
|
|
|
const puppeteer = require('puppeteer-core');
|
2019-08-14 09:39:55 +00:00
|
|
|
const browser = await puppeteer.launch();
|
|
|
|
const page = await browser.newPage();
|
|
|
|
await page.setContent(html);
|
|
|
|
await page.addStyleTag({
|
2021-11-09 10:42:39 +00:00
|
|
|
url: 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css',
|
2019-08-14 09:39:55 +00:00
|
|
|
});
|
|
|
|
await page.pdf({
|
2021-11-09 10:42:39 +00:00
|
|
|
path: filePath,
|
|
|
|
format: 'A4',
|
2019-08-14 09:39:55 +00:00
|
|
|
});
|
|
|
|
await browser.close();
|
2018-03-29 18:51:56 +00:00
|
|
|
}
|
2018-04-14 19:14:02 +00:00
|
|
|
|
|
|
|
function setupExpressRoute() {
|
2019-08-14 09:39:55 +00:00
|
|
|
if (!frappe.app) return;
|
|
|
|
frappe.app.post('/api/method/pdf', frappe.asyncHandler(handlePDFRequest));
|
2018-04-14 19:14:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function handlePDFRequest(req, res) {
|
2019-08-14 09:39:55 +00:00
|
|
|
const args = req.body;
|
|
|
|
const { doctype, name } = args;
|
|
|
|
const html = await getHTML(doctype, name);
|
2018-04-14 19:14:02 +00:00
|
|
|
|
2021-11-09 10:42:39 +00:00
|
|
|
const filePath = path.join(
|
2019-08-14 09:39:55 +00:00
|
|
|
getTmpDir(),
|
|
|
|
`frappe-pdf-${getRandomString()}.pdf`
|
|
|
|
);
|
2021-11-09 10:42:39 +00:00
|
|
|
await makePDF(html, filePath);
|
2018-04-14 19:14:02 +00:00
|
|
|
|
2021-11-09 10:42:39 +00:00
|
|
|
const file = fs.createReadStream(filePath);
|
|
|
|
const stat = fs.statSync(filePath);
|
2019-08-14 09:39:55 +00:00
|
|
|
res.setHeader('Content-Length', stat.size);
|
|
|
|
res.setHeader('Content-Type', 'application/pdf');
|
|
|
|
res.setHeader(
|
|
|
|
'Content-Disposition',
|
2021-11-09 10:42:39 +00:00
|
|
|
`attachment; filename=${path.basename(filePath)}`
|
2019-08-14 09:39:55 +00:00
|
|
|
);
|
|
|
|
file.pipe(res);
|
2018-04-14 19:14:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
2019-08-14 09:39:55 +00:00
|
|
|
makePDF,
|
2019-12-09 19:58:33 +00:00
|
|
|
setupExpressRoute
|
2019-08-14 09:39:55 +00:00
|
|
|
};
|