2
0
mirror of https://github.com/frappe/books.git synced 2024-11-14 09:24:04 +00:00
books/server/pdf.js

54 lines
1.4 KiB
JavaScript
Raw Normal View History

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