diff --git a/bin/index.js b/bin/index.js index d8b7661..9cee52b 100755 --- a/bin/index.js +++ b/bin/index.js @@ -1,10 +1,10 @@ #!/usr/bin/env node -var fs = require('fs') -var pdf = require('../') -var path = require('path') +const fs = require('fs') +const pdf = require('../') +const path = require('path') -var args = process.argv.slice(2) +const args = process.argv.slice(2) if (args.length >= 2) { htmlpdf(args[0], args[1]) @@ -13,7 +13,7 @@ if (args.length >= 2) { } function help () { - var help = [ + const help = [ 'Usage: html-pdf ', 'e.g.: html-pdf source.html destination.pdf' ].join('\n') @@ -22,8 +22,8 @@ function help () { } function htmlpdf (source, destination) { - var html = fs.readFileSync(source, 'utf8') - var options = { + const html = fs.readFileSync(source, 'utf8') + const options = { base: 'file://' + path.resolve(source) } pdf.create(html, options).toFile(destination, function (err, res) { diff --git a/examples/businesscard/test.js b/examples/businesscard/test.js index 8739cf4..3e21a06 100644 --- a/examples/businesscard/test.js +++ b/examples/businesscard/test.js @@ -1,28 +1,28 @@ -var test = require('tape') -var pdf = require('../../') -var path = require('path') -var fs = require('fs') +const test = require('tape') +const pdf = require('../../') +const path = require('path') +const fs = require('fs') test('allows custom html and css', function (t) { t.plan(3) - var template = path.join(__dirname, 'businesscard.html') - var filename = template.replace('.html', '.pdf') - var templateHtml = fs.readFileSync(template, 'utf8') + const template = path.join(__dirname, 'businesscard.html') + const filename = template.replace('.html', '.pdf') + let templateHtml = fs.readFileSync(template, 'utf8') - var image = path.join('file://', __dirname, 'image.png') + const image = path.join('file://', __dirname, 'image.png') templateHtml = templateHtml.replace('{{image}}', image) - var options = { + const options = { width: '50mm', height: '90mm' } pdf - .create(templateHtml, options) - .toFile(filename, function (err, pdf) { - t.error(err) - t.assert(pdf.filename, 'Returns the filename') - t.assert(fs.existsSync(pdf.filename), 'Saves the file to the desired destination') - }) + .create(templateHtml, options) + .toFile(filename, function (err, pdf) { + t.error(err) + t.assert(pdf.filename, 'Returns the filename') + t.assert(fs.existsSync(pdf.filename), 'Saves the file to the desired destination') + }) }) diff --git a/examples/serve-http/index.js b/examples/serve-http/index.js index 2af62e6..bda0d33 100644 --- a/examples/serve-http/index.js +++ b/examples/serve-http/index.js @@ -6,7 +6,7 @@ const tmpl = fs.readFileSync(require.resolve('../businesscard/businesscard.html' const server = http.createServer(function (req, res) { if (req.url === '/favicon.ico') return res.end('404') const html = tmpl.replace('{{image}}', `file://${require.resolve('../businesscard/image.png')}`) - pdf.create(html, {width: '50mm', height: '90mm'}).toStream((err, stream) => { + pdf.create(html, { width: '50mm', height: '90mm' }).toStream((err, stream) => { if (err) return res.end(err.stack) res.setHeader('Content-type', 'application/pdf') stream.pipe(res) diff --git a/lib/index.js b/lib/index.js index d6bbcf1..03c70e6 100755 --- a/lib/index.js +++ b/lib/index.js @@ -1,4 +1,4 @@ -var PDF = require('./pdf') +const PDF = require('./pdf') module.exports = { create: function createPdf (html, options, callback) { @@ -15,8 +15,10 @@ module.exports = { options = {} } + let pdf + try { - var pdf = new PDF(html, options) + pdf = new PDF(html, options) } catch (err) { return callback(err) } diff --git a/lib/pdf.js b/lib/pdf.js index 46f2ce4..3205ec5 100644 --- a/lib/pdf.js +++ b/lib/pdf.js @@ -1,10 +1,12 @@ -var fs = require('fs') -var childprocess = require('child_process') -var path = require('path') -var assert = require('assert') +const fs = require('fs') +const childprocess = require('child_process') +const path = require('path') +const assert = require('assert') + +let phantomjs try { - var phantomjs = require('phantomjs-prebuilt') + phantomjs = require('phantomjs-prebuilt') } catch (err) { console.log('html-pdf: Failed to load PhantomJS module.', err) } @@ -58,8 +60,9 @@ PDF.prototype.toBuffer = function PdfToBuffer (callback) { PDF.prototype.toStream = function PdfToStream (callback) { this.exec(function (err, res) { if (err) return callback(err) + let stream try { - var stream = fs.createReadStream(res.filename) + stream = fs.createReadStream(res.filename) } catch (err) { return callback(err) } @@ -86,10 +89,10 @@ PDF.prototype.toFile = function PdfToFile (filename, callback) { } PDF.prototype.exec = function PdfExec (callback) { - var child = childprocess.spawn(this.options.phantomPath, [].concat(this.options.phantomArgs, [this.script]), this.options.childProcessOptions) - var stderr = [] + const child = childprocess.spawn(this.options.phantomPath, [].concat(this.options.phantomArgs, [this.script]), this.options.childProcessOptions) + const stderr = [] - var timeout = setTimeout(function execTimeout () { + const timeout = setTimeout(function execTimeout () { respond(null, new Error('html-pdf: PDF generation timeout. Phantom.js script did not exit.')) }, this.options.timeout) @@ -98,9 +101,9 @@ PDF.prototype.exec = function PdfExec (callback) { } function onData (buffer) { - var result + let result try { - var json = buffer.toString().trim() + const json = buffer.toString().trim() if (json) result = JSON.parse(json) } catch (err) { // Proxy for debugging purposes @@ -110,7 +113,7 @@ PDF.prototype.exec = function PdfExec (callback) { if (result) respond(null, null, result) } - var callbacked = false + let callbacked = false function respond (code, err, data) { if (callbacked) return callbacked = true @@ -124,7 +127,7 @@ PDF.prototype.exec = function PdfExec (callback) { // Also, as per your script and standards, having a code value of 1 means one can always assume that // an error occured. if (((typeof code !== 'undefined' && code !== null) && code !== 0) || err) { - var error = null + let error = null if (err) { // Rudimentary checking if err is an instance of the Error class @@ -135,7 +138,7 @@ PDF.prototype.exec = function PdfExec (callback) { } // Append anything caught from the stderr - var postfix = stderr.length ? '\n' + Buffer.concat(stderr).toString() : '' + const postfix = stderr.length ? '\n' + Buffer.concat(stderr).toString() : '' if (postfix) error.message += postfix return callback(error) @@ -152,7 +155,7 @@ PDF.prototype.exec = function PdfExec (callback) { child.on('close', respond) child.on('exit', respond) - var config = JSON.stringify({html: this.html, options: this.options}) + const config = JSON.stringify({ html: this.html, options: this.options }) child.stdin.write(config + '\n', 'utf8') child.stdin.end() } diff --git a/lib/scripts/pdf_a4_portrait.js b/lib/scripts/pdf_a4_portrait.js index debc93a..ec6bfef 100755 --- a/lib/scripts/pdf_a4_portrait.js +++ b/lib/scripts/pdf_a4_portrait.js @@ -1,10 +1,10 @@ /* global phantom */ -var system = require('system') -var webpage = require('webpage') +const system = require('system') +const webpage = require('webpage') // Error handler function exit (error) { - var message + let message if (typeof error === 'string') message = error if (error) system.stderr.write('html-pdf: ' + (message || 'Unknown Error ' + error) + '\n') phantom.exit(error ? 1 : 0) @@ -12,7 +12,7 @@ function exit (error) { // Build stack to print function buildStack (msg, trace) { - var msgStack = [msg] + const msgStack = [msg] if (trace && trace.length) { msgStack.push('Stack:') trace.forEach(function (t) { @@ -27,16 +27,16 @@ phantom.onError = function (msg, trace) { } // Load configurations from stdin -var json = JSON.parse(system.stdin.readLine()) +const json = JSON.parse(system.stdin.readLine()) if (!json.html || !json.html.trim()) exit('Did not receive any html') -var options = json.options -var page = webpage.create() +const options = json.options +const page = webpage.create() // Completely load page & end process // ---------------------------------- -var rendered = false -var renderTimeout +let rendered = false +let renderTimeout // If renderDelay is manual, then listen for an event and don't automatically render if (options.renderDelay === 'manual') { @@ -57,16 +57,16 @@ function renderNow () { clearTimeout(renderTimeout) page.paperSize = definePaperSize(getContent(page), options) - var fileOptions = { + const fileOptions = { type: options.type || 'pdf', quality: options.quality || 75 } - var filename = options.filename || (options.directory || '/tmp') + '/html-pdf-' + system.pid + '.' + fileOptions.type + const filename = options.filename || (options.directory || '/tmp') + '/html-pdf-' + system.pid + '.' + fileOptions.type page.render(filename, fileOptions) // Output to parent process - system.stdout.write(JSON.stringify({filename: filename})) + system.stdout.write(JSON.stringify({ filename })) exit(null) } @@ -86,7 +86,7 @@ page.onError = function (msg, trace) { // Force cleanup after 2 minutes // Add 2 seconds to make sure master process triggers kill // before to the phantom process -var timeout = (options.timeout || 120000) + 2000 +const timeout = (options.timeout || 120000) + 2000 setTimeout(function () { exit('Force timeout') }, timeout) @@ -96,13 +96,13 @@ setTimeout(function () { function getContent (page) { return page.evaluate(function () { function getElements (doc, wildcard) { - var wildcardMatcher = new RegExp(wildcard + '(.*)') - var hasElements = false - var elements = {} - var $elements = document.querySelectorAll("[id*='" + wildcard + "']") + const wildcardMatcher = new RegExp(wildcard + '(.*)') + let hasElements = false + const elements = {} + const $elements = document.querySelectorAll("[id*='" + wildcard + "']") - var $elem, match, i - var len = $elements.length + let $elem, match, i + const len = $elements.length for (i = 0; i < len; i++) { $elem = $elements[i] match = $elem.attributes.id.value.match(wildcardMatcher) @@ -117,26 +117,26 @@ function getContent (page) { } function getElement (doc, id) { - var $elem = doc.getElementById(id) + const $elem = doc.getElementById(id) if ($elem) { - var html = $elem.outerHTML + const html = $elem.outerHTML $elem.parentNode.removeChild($elem) return html } } - var styles = document.querySelectorAll('link,style') + let styles = document.querySelectorAll('link,style') styles = Array.prototype.reduce.call(styles, function (string, node) { return string + (node.outerHTML || '') }, '') // Wildcard headers e.g.
or
- var header = getElements(document, 'pageHeader-') - var footer = getElements(document, 'pageFooter-') + let header = getElements(document, 'pageHeader-') + let footer = getElements(document, 'pageFooter-') // Default header and footer e.g.