Browse Source

Improve NodeJS example

Fixes RelaxedJS/ReLaXed#147
Fixes RelaxedJS/ReLaXed#148
Fixes RelaxedJS/ReLaXed#149
pull/150/head
jwmann 4 years ago
parent
commit
142a0156a0
No known key found for this signature in database GPG Key ID: FEAF88A73A68BD1B
  1. 86
      README.md

86
README.md

@ -158,50 +158,61 @@ ReLaXed consists of a few lines of code binding together other software. It uses
An Example:
```javascript
const { masterToPDF } = require('relaxedjs');
const puppeteer = require('puppeteer');
const plugins = require('relaxedjs/src/plugins');
const path = require('path');
class HTML2PDF {
constructor(){
this.puppeteerConfig = {
headless: true,
args: [
'--no-sandbox',
'--disable-translate',
'--disable-extensions',
'--disable-sync'
],
};
this.relaxedGlobals = {
busy: false,
config: {},
configPlugins: [],
};
constructor() {
this.puppeteerConfig = {
headless: true,
args: [
'--no-sandbox',
'--disable-translate',
'--disable-extensions',
'--disable-sync',
],
};
this.relaxedGlobals = {
busy: false,
config: {},
configPlugins: [],
};
this._initializedPlugins = false;
}
async _initializePlugins() {
if (this._initializedPlugins) return; // Do not initialize plugins twice
for (const [i, plugin] of plugins.builtinDefaultPlugins.entries()) {
plugins.builtinDefaultPlugins[i] = await plugin.constructor();
}
async _initializePlugins() {
for (let [i, plugin] of plugins.builtinDefaultPlugins.entries()) {
plugins.builtinDefaultPlugins[i] = await plugin.constructor();
}
await plugins.updateRegisteredPlugins(this.relaxedGlobals, '/');
let chrome = await puppeteer.launch(this.puppeteerConfig);
this.relaxedGlobals.puppeteerPage = await chrome.newPage();
}
async pdf(template_pug, json_data){
await this._initPDFReader();
await masterToPDF(template_pug,
this.relaxedGlobals,
'<path-to-render-html>.htm',
'<path-to-render-pdf>.pdf',
json_data,
);
await plugins.updateRegisteredPlugins(this.relaxedGlobals, '/');
const chrome = await puppeteer.launch(this.puppeteerConfig);
this.relaxedGlobals.puppeteerPage = await chrome.newPage();
this._initializedPlugins = true;
}
async pdf(templatePath, json_data, tempHtmlPath, outputPdfPath) {
await this._initializePlugins();
if (this._initializedPlugins) {
// Paths must be absolute
const defaultTempHtmlPath = tempHtmlPath || path.resolve('temp.html');
const defaultOutputPdfPath =
outputPdfPath || path.resolve('output.pdf');
await masterToPDF(
templatePath,
this.relaxedGlobals,
defaultTempHtmlPath,
defaultOutputPdfPath,
json_data
);
}
}
}
module.exports = new HTML2PDF();
@ -211,7 +222,6 @@ Usage:
```javascript
const HTML2PDF = require('./HTML2PDF.js');
(async () => {
await HTML2PDF._initializePlugins();
await HTML2PDF.pdf('./template.pug', {"a":"b", "c":"d"});
})();
```

Loading…
Cancel
Save