Commit 6b1480a3 authored by Fred Chasen's avatar Fred Chasen

Add Printer class

parent 566cdf62
#!/usr/bin/env node
const Paged = require('pagedjs');
const puppeteer = require('puppeteer');
const program = require('commander');
// const temp = require("temp").track();
const Printer = require("../");
const path = require('path');
const fs = require('fs');
const { promisify } = require('util');
const writeFileAsync = promisify(fs.writeFile);
const replaceExt = require('replace-ext');
const express = require('express');
const app = express();
const PORT = 9999;
program
.version(require('../package.json').version)
.arguments('[inputPath]')
......@@ -28,6 +23,7 @@ program
// .option('-ho, --hypher_only [str]', 'Only hyphenate passed elements selector, such as ".hyphenate, aside"')
// .option('-e, --encoding [type]', 'Set the encoding of the input html, defaults to "utf-8"')
.option('-t, --timeout [ms]', 'Set a max timeout of [ms]')
.option('-x, --html', 'output html file')
.parse(process.argv);
......@@ -95,64 +91,26 @@ if (program.hyphenate) {
(async () => {
const browser = await puppeteer.launch({
headless: headless
// args: ['--no-sandbox', '--allow-file-access-from-files', '--enable-local-file-accesses']
});
const page = await browser.newPage();
let relativePath = path.resolve(dir, input);
let dirname = path.dirname(relativePath);
let basename = path.basename(relativePath);
app.use("/print", express.static(dirname))
let scriptPath = path.resolve(dir, "./node_modules/pagedjs/dist/");
app.use("/polyfill", express.static(scriptPath))
let server = app.listen(PORT);
await page.goto(`http://localhost:${PORT}/print/${basename}?preview=true`);
await page.exposeFunction('PuppeteerLogger', (msg, counter) => {
console.log(msg, counter);
});
await page.exposeFunction('onPagesRendered', async (msg, width, height, orientation) => {
console.log(msg, width, height, orientation);
let printer = new Printer(headless);
let file;
if (headless) {
let pages = await page.waitForSelector(".pagedjs_pages");
let pdf = await page.pdf({
path: output,
printBackground: true,
displayHeaderFooter: false,
width: width,
height: height,
orientation: orientation,
margin: {
top: 0,
right: 0,
bottom: 0,
left: 0,
let options = {};
if (program.html) {
file = await printer.html(input, options);
output = replaceExt(output, '.html');
} else {
file = await printer.pdf(input, options);
}
}).catch((e) => {
console.error(e);
});
console.log("Saved to", output);
server.close();
await browser.close();
} else {
printer.preview(input);
}
});
await page.addScriptTag({
url: `http://localhost:${PORT}/polyfill/paged.polyfill.js`
if (file) {
fs.writeFile(output, file, (err) => {
if (err) throw err;
console.log('Saved to', output);
process.exit(0);
});
}
})();
const Paged = require('pagedjs');
const EventEmitter = require('events');
const puppeteer = require('puppeteer');
// const temp = require("temp").track();
const path = require('path');
const fs = require('fs');
const express = require('express');
const app = express();
const PORT = 9999;
let dir = process.cwd();
let scriptPath = path.resolve(dir, "./node_modules/pagedjs/dist/");
const PDF_SETTINGS = {
printBackground: true,
displayHeaderFooter: false,
preferCSSPageSize: true,
margin: {
top: 0,
right: 0,
bottom: 0,
left: 0,
}
};
class Printer extends EventEmitter {
constructor(headless) {
super();
this.headless = headless !== false;
}
async setup() {
const browser = await puppeteer.launch({
headless: this.headless
});
return browser;
}
async serve(input) {
let relativePath = path.resolve(dir, input);
let dirname = path.dirname(relativePath);
app.use("/print", express.static(dirname))
let scriptPath = path.resolve(dir, "./node_modules/pagedjs/dist/");
app.use("/polyfill", express.static(scriptPath))
app.set('port', process.env.PORT || 0);
return new Promise(function(resolve, reject) {
let server = app.listen(app.get('port'), () => {
resolve(server);
});
});
}
async render(input) {
let resolver;
let rendered = new Promise(function(resolve, reject) {
resolver = resolve;
});
if (!this.browser) {
this.browser = await this.setup();
}
const page = await this.browser.newPage();
let server = await this.serve(input);
let port = server.address().port;
let relativePath = path.resolve(dir, input);
let basename = path.basename(relativePath);
await page.goto(`http://localhost:${port}/print/${basename}`)
.catch((e) => {
console.error(e);
});
await page.exposeFunction('PuppeteerLogger', (msg, counter) => {
console.log(msg, counter);
this.emit(msg, counter);
});
await page.exposeFunction('onPagesRendered', async (msg, width, height, orientation) => {
console.log('onPagesRendered', msg, width, height, orientation);
this.emit(msg, width, height, orientation);
resolver({msg, width, height, orientation});
});
await page.addScriptTag({
url: `http://localhost:${port}/polyfill/paged.polyfill.js`
});
await rendered;
await page.waitForSelector(".pagedjs_pages");
server.close();
return page;
}
async pdf(input, options={}) {
let page = await this.render(input);
let settings = {
printBackground: true,
displayHeaderFooter: false,
preferCSSPageSize: options.width ? false : true,
width: options.width,
height: options.height,
orientation: options.orientation,
margin: {
top: 0,
right: 0,
bottom: 0,
left: 0,
}
}
let pdf = await page.pdf(PDF_SETTINGS)
.catch((e) => {
console.error(e);
});
await page.close();
return pdf;
}
async html(input, stayopen) {
let page = await this.render(input);
let content = await page.content()
.catch((e) => {
console.error(e);
});
await page.close();
return content;
}
async preview(input) {
let page = await this.render(input);
return page;
}
}
module.exports = Printer;
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -9,13 +9,20 @@
"url": "https://gitlab.pagedmedia.org/polyfills/pagedjs-cli.git"
},
"scripts": {
"start": "./bin/paged"
"start": "./bin/paged",
"pkg": "./bin/pkg"
},
"main": "index.js",
"dependencies": {
"commander": "^2.15.1",
"express": "^4.16.3",
"commander": "^2.19.0",
"express": "^4.16.4",
"hyphenopoly": "^2.5.1",
"pagedjs": "latest",
"puppeteer": "^1.5.0",
"pkg": "^4.3.4",
"puppeteer": "^1.10.0",
"replace-ext": "^1.0.0"
},
"devDependencies": {
"eslint": "^5.9.0"
}
}
......@@ -10,16 +10,9 @@ html{
}
@page {
size: 148mm 210mm portait
size: A5;
}
@media screen {
.baseline .pagedjs_page {
background-image: repeating-linear-gradient(180deg, transparent 0, transparent 14px , rgba(0,255,0,0.7) var(--baseline)) ;
background-size: cover;
background-position: 0 -3px , 0 0
}
}
@page cover {
margin: 0;
......
......@@ -24,7 +24,7 @@
<!-- Prince XML-->
<!-- <link href="prince/layout-prince.css" rel="stylesheet"/> -->
<!-- <script src="http://localhost:9090/dist/paged.polyfill.js"></script> -->
<!-- Typos -->
<link rel="stylesheet" href="fonts/spectral/stylesheet.css" />
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment