Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions bin/index.js
Original file line number Diff line number Diff line change
@@ -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])
Expand All @@ -13,7 +13,7 @@ if (args.length >= 2) {
}

function help () {
var help = [
const help = [
'Usage: html-pdf <source> <destination>',
'e.g.: html-pdf source.html destination.pdf'
].join('\n')
Expand All @@ -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) {
Expand Down
30 changes: 15 additions & 15 deletions examples/businesscard/test.js
Original file line number Diff line number Diff line change
@@ -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')
})
})
2 changes: 1 addition & 1 deletion examples/serve-http/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var PDF = require('./pdf')
const PDF = require('./pdf')

module.exports = {
create: function createPdf (html, options, callback) {
Expand All @@ -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)
}
Expand Down
33 changes: 18 additions & 15 deletions lib/pdf.js
Original file line number Diff line number Diff line change
@@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand All @@ -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)

Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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()
}
Expand Down
82 changes: 41 additions & 41 deletions lib/scripts/pdf_a4_portrait.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
/* 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)
}

// 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) {
Expand All @@ -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') {
Expand All @@ -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)
}

Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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. <div id="pageHeader-first"> or <div id="pageHeader-0">
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. <div id="pageHeader">
var h = getElement(document, 'pageHeader')
var f = getElement(document, 'pageFooter')
const h = getElement(document, 'pageHeader')
const f = getElement(document, 'pageFooter')

if (h) {
header = header || {}
Expand All @@ -148,16 +148,16 @@ function getContent (page) {
footer.default = f
}

var body
var $body = document.getElementById('pageContent')
let body
const $body = document.getElementById('pageContent')
if ($body) body = $body.outerHTML
else body = document.body.outerHTML

return {
styles: styles,
header: header,
body: body,
footer: footer
styles,
header,
body,
footer
}
})
}
Expand All @@ -166,19 +166,19 @@ function getContent (page) {
// --------------------
function createSection (section, content, options) {
options = options[section] || {}
var c = content[section] || {}
var o = options.contents
var paginationOffset = Math.floor(options.paginationOffset) || 0
const c = content[section] || {}
let o = options.contents
const paginationOffset = Math.floor(options.paginationOffset) || 0

if (typeof o !== 'object') o = {default: o}
if (typeof o !== 'object') o = { default: o }

return {
height: options.height,
contents: phantom.callback(function (pageNum, numPages) {
var html = o[pageNum] || c[pageNum]
let html = o[pageNum] || c[pageNum]

var pageNumFinal = pageNum + paginationOffset
var numPagesFinal = numPages + paginationOffset
const pageNumFinal = pageNum + paginationOffset
const numPagesFinal = numPages + paginationOffset

if (pageNumFinal === 1 && !html) html = o.first || c.first
if (pageNumFinal === numPages && !html) html = o.last || c.last
Expand All @@ -192,7 +192,7 @@ function createSection (section, content, options) {
// Creates paper with specified options
// ------------------------------------
function definePaperOrientation (options) {
var paper = {border: options.border || '0'}
const paper = { border: options.border || '0' }

if (options.height && options.width) {
paper.width = options.width
Expand All @@ -208,7 +208,7 @@ function definePaperOrientation (options) {
// Creates paper with generated footer & header
// --------------------------------------------
function definePaperSize (content, options) {
var paper = definePaperOrientation(options)
const paper = definePaperOrientation(options)

if (options.header || content.header) {
paper.header = createSection('header', content, options)
Expand Down
Loading