2
0
mirror of https://github.com/frappe/books.git synced 2024-11-10 15:50:56 +00:00
books/server/pdf.js

90 lines
2.6 KiB
JavaScript
Raw Normal View History

const frappe = require('frappejs');
2018-03-29 18:51:56 +00:00
const puppeteer = require('puppeteer');
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) {
2018-03-29 18:51:56 +00:00
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'
})
2018-03-29 18:51:56 +00:00
await page.pdf({
path: filepath,
format: 'A4'
});
await browser.close();
}
async function getPDFForElectron(doctype, name, destination, htmlContent) {
2018-10-24 17:52:02 +00:00
const { remote, shell } = require('electron');
const { BrowserWindow } = remote;
const html = htmlContent || await getHTML(doctype, name);
const filepath = path.join(destination, name + '.pdf');
2018-10-24 17:52:02 +00:00
const fs = require('fs')
2018-10-24 18:12:40 +00:00
let printWindow = new BrowserWindow({
width: 600,
height: 800,
show: false
})
2018-10-24 17:52:02 +00:00
printWindow.loadURL(`file://${path.join(__static, 'print.html')}`);
printWindow.on('closed', () => {
printWindow = null;
});
const code = `
document.body.innerHTML = \`${html}\`;
`;
printWindow.webContents.executeJavaScript(code);
2018-10-24 18:12:40 +00:00
const printPromise = new Promise(resolve => {
printWindow.webContents.on('did-finish-load', () => {
printWindow.webContents.printToPDF({}, (error, data) => {
2018-10-24 17:52:02 +00:00
if (error) throw error
2018-10-24 18:12:40 +00:00
printWindow.close();
fs.writeFile(filepath, data, (error) => {
if (error) throw error
resolve(shell.openItem(filepath));
})
2018-10-24 17:52:02 +00:00
})
})
})
2018-10-24 18:12:40 +00:00
await printPromise;
2018-10-24 17:52:02 +00:00
// await makePDF(html, filepath);
2018-04-16 09:32:31 +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,
2018-04-16 09:32:31 +00:00
setupExpressRoute,
getPDFForElectron
}