Skip to content
This repository has been archived by the owner on Apr 7, 2020. It is now read-only.

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
msokk committed Jan 18, 2016
0 parents commit ce65650
Show file tree
Hide file tree
Showing 13 changed files with 367 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": ["es2015-node5"]
}
10 changes: 10 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.git
.gitignore
.envrc
.babelrc
.eslintrc
dev.js
npm-debug.log

src/
node_modules/
4 changes: 4 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"parser": "babel-eslint",
"extends": "airbnb/base"
}
29 changes: 29 additions & 0 deletions .fonts.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?xml version='1.0'?>
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'>
<fontconfig>
<match target="font">
<edit mode="assign" name="rgba">
<const>rgb</const>
</edit>
</match>
<match target="font">
<edit mode="assign" name="hinting">
<bool>true</bool>
</edit>
</match>
<match target="font">
<edit mode="assign" name="hintstyle">
<const>hintslight</const>
</edit>
</match>
<match target="font">
<edit mode="assign" name="antialias">
<bool>true</bool>
</edit>
</match>
<match target="font">
<edit mode="assign" name="lcdfilter">
<const>lcddefault</const>
</edit>
</match>
</fontconfig>
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
lib/
node_modules/
.envrc
npm-debug.log
19 changes: 19 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
FROM node:slim

ENV RENDERER_ACCESS_KEY=changeme CONCURRENCY=1

# Add subpixel hinting
COPY .fonts.conf /root

COPY . /app
WORKDIR /app

# Install the packages needed to run Electron
RUN npm install --production && \
sed -i 's/main/main contrib/g' /etc/apt/sources.list && \
apt-get update && apt-get install -y xvfb \
libgtk2.0-0 ttf-mscorefonts-installer libnotify4 libgconf2-4 libnss3 && \
apt-get clean

EXPOSE 3000
CMD xvfb-run --server-args="-screen 0 800x600x24" npm start
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 Mihkel Sokk <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
66 changes: 66 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# electron-render-service
[![Docker Hub](https://img.shields.io/badge/docker-ready-blue.svg)](https://registry.hub.docker.com/u/msokk/electron-render-service/)
[![](https://badge.imagelayers.io/msokk/electron-render-service:latest.svg)](https://imagelayers.io/?images=msokk/electron-render-service:latest 'Get your own badge on imagelayers.io')

Simple PDF render service, accepts webpage URL and returns it as a PDF.


## Docker usage

Based on official [Node.js Jessie](https://hub.docker.com/_/node/) image,
uses latest [electron](https://github.com/atom/electron).


1. `docker run -t -e RENDERER_ACCESS_KEY=secret -p 3000:3000 msokk/electron-render-service`
2. `wget -o out.pdf http://<node_address>:3000/pdf?url=https://github.com/msokk/electron-render-service&access_key=secret`


## Installation on Debian with Node.js

```sh
# Enable contrib packages
sed -i 's/main/main contrib/g' /etc/apt/sources.list

# Install packages needed for runtime
apt-get update && apt-get install -y xvfb libgtk2.0-0 ttf-mscorefonts-installer libnotify4 libgconf2-4 libnss3

# Clone project (not yet on NPM)
git clone https://github.com/msokk/electron-render-service.git
npm install

# Run in virtual framebuffer
RENDERER_ACCESS_KEY=secret xvfb-run --server-args="-screen 0 800x600x24" npm start

wget -o out.pdf http://localhost:3000/pdf?url=https://github.com/msokk/electron-render-service&access_key=secret
```

## Endpoints

#### `GET /pdf` - Render PDF

> Query params ([About PDF params](https://github.com/atom/electron/blob/master/docs/api/web-contents.md#webcontentsprinttopdfoptions-callback)):
* `access_key` - Authentication key.
* `url` - Full URL to fetch.
* `pageSize` - Specify page size of the generated PDF. (default: `A4`)
* `marginsType` - Specify the type of margins to use (default: `0`)
* `printBackground` - Whether to print CSS backgrounds. (default: `true`)
* `landscape` - `true` for landscape, `false` for portrait. (default: `false`)


#### `GET /stats` - Display render pool stats

> Query params:
* `access_key` - Generic authentication key is required.


## Environment variables

##### *Required*
* `RENDERER_ACCESS_KEY` or `RENDERER_ACCESS_KEY_<suffix>` - Secret key for limiting access. Suffixed keys are used as labels in access log for debugging usage.

##### *Optional*
* `CONCURRENCY` - Number of browser windows to run in parallel (default: `1`)
* `INTERFACE` - Network interface for Express to listen on (default: `0.0.0.0`)
* `PORT` - (default: `3000`)
2 changes: 2 additions & 0 deletions dev.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
require('babel-register');
require('./src/server');
37 changes: 37 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "electron-render-service",
"version": "0.1.0",
"description": "Microservice for rendering PDFs from HTML with Electron",
"scripts": {
"start": "electron lib/server.js",
"dev": "electron dev.js",
"build": "babel src -d lib"
},
"keywords": [
"electron",
"render",
"pdf",
"html",
"microservice"
],
"author": "Mihkel Sokk <[email protected]>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/msokk/electron-render-service.git"
},
"dependencies": {
"async": "^1.5.2",
"electron-prebuilt": "^0.36.4",
"express": "^4.13.3",
"morgan": "^1.6.1"
},
"devDependencies": {
"babel-cli": "^6.4.0",
"babel-eslint": "5.0.0-beta6",
"babel-preset-es2015-node5": "^1.1.1",
"babel-register": "^6.4.3",
"eslint": "^1.10.3",
"eslint-config-airbnb": "^3.1.0"
}
}
25 changes: 25 additions & 0 deletions src/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const KEY_PREFIX = 'RENDERER_ACCESS_KEY';
const validKeys = {};

// Global key
if (process.env[KEY_PREFIX]) validKeys.global = process.env[KEY_PREFIX];

// Labeled keys
Object.keys(process.env)
.filter(k => k.startsWith(KEY_PREFIX + '_'))
.filter(k => process.env[k].length > 0)
.forEach(k => validKeys[k.replace(KEY_PREFIX + '_', '').toLowerCase()] = process.env[k]);

if (Object.keys(validKeys).length === 0) throw new Error('No access key defined!');

/**
* Simple token auth middleware
*/
export default function authMiddleware(req, res, next) {
const sentKey = req.query.access_key;
const key = Object.keys(validKeys).filter(k => validKeys[k] === sentKey);
if (!sentKey || key.length === 0) return res.sendStatus(403);

req.keyLabel = key[0];
next();
}
81 changes: 81 additions & 0 deletions src/render_pool.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import pjson from '../package.json';
import { queue } from 'async';
import { BrowserWindow } from 'electron';

const DEFAULT_HEADERS = 'Cache-Control: no-cache, no-store, must-revalidate';
const CONCURRENCY = process.env.CONCURRENCY || 1;
const windowPool = [];

/**
* Get renderer from pool and lock it
*/
function getRenderer() {
const win = windowPool.filter(p => p.busy === false)[0];
if (win) windowPool[win.id - 1].busy = true;
return win;
}


// Render queue
const rendererQueue = queue(({ type, res, url, options }, done) => {
const win = getRenderer();
if (!win) throw new Error('Pool is empty?');

const { webContents } = win;
webContents.loadURL(url, { extraHeaders: DEFAULT_HEADERS });

webContents.once('did-finish-load', () => {
if (type === 'pdf') {
webContents.printToPDF(options, (error, data) => {
if (error) throw error;

res.set('Content-Disposition', `inline; filename="render-${Date.now()}.pdf"`);
res.type('pdf').send(data);
win.release();
done();
});
}
});
}, CONCURRENCY);


export default {
/**
* Push a render task to queue
*/
enqueue(task) {
rendererQueue.push(task);
},

/**
* Fetch stats for debugging
*/
stats() {
return {
concurrency: rendererQueue.concurrency,
length: rendererQueue.length(),
workersList: rendererQueue.workersList().map(({ data }) =>
({ url: data.url, options: data.options, type: data.type })),
};
},

/**
* Create Electron window pool
*/
init() {
Array.from({ length: CONCURRENCY }, (v, k) => k).forEach(i => {
const browserWindow = new BrowserWindow({ show: false });

// Set user agent
const webContents = browserWindow.webContents;
webContents.setUserAgent(`${webContents.getUserAgent()} ${pjson.name}/${pjson.version}`);

// Basic locking
browserWindow.busy = false;
browserWindow.release = () => windowPool[i].busy = false;

// Add to pool
windowPool.push(browserWindow);
});
},
};
66 changes: 66 additions & 0 deletions src/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import express from 'express';
import morgan from 'morgan';
import { app as electronApp } from 'electron';

import renderPool from './render_pool';
import auth from './auth';

const INTERFACE = process.env.INTERFACE || '0.0.0.0';
const PORT = process.env.PORT || 3000;
const app = express();

function printPDFUsage(url = '') {
return `Usage: GET ${url}/pdf?url=http://google.com&access_key=<token>`;
}

// Log with token
morgan.token('key-label', req => req.keyLabel);
app.use(morgan(`[:date[iso]] :key-label@:remote-addr - :method :status
:url :res[content-length] ":user-agent" :response-time ms`.replace('\n', '')));


/**
* GET /pdf - Render PDF
*
* Query: https://github.com/atom/electron/blob/master/docs/api/web-contents.md#webcontentsprinttopdfoptions-callback
*/
app.get('/pdf', auth, (req, res) => {
const { url = 'data:text/plain;charset=utf-8,' + printPDFUsage(),
marginsType = 0, pageSize = 'A4', printBackground = true, landscape = false } = req.query;

renderPool.enqueue({ url, res, type: 'pdf',
options: { marginsType, pageSize, landscape, printBackground } });
});


/**
* GET /stats - Output some stats as JSON
*/
app.get('/stats', auth, (req, res) => {
if (req.keyLabel !== 'global') return res.sendStatus(403);

res.send(renderPool.stats());
});


/**
* GET / - Print usage
*/
app.get('/', (req, res) => res.status(404).send(printPDFUsage()));


// Electron finished booting
electronApp.on('ready', () => {
renderPool.init();

const listener = app.listen(PORT, INTERFACE, () => {
const { port, address } = listener.address();
const url = `http://${address}:${port}`;
process.stdout.write(`Renderer listening on ${url}\n\n`);
process.stdout.write(printPDFUsage(url) + '\n');
});
});


// Stop Electron on SIG*
process.on('exit', code => electronApp.exit(code));

0 comments on commit ce65650

Please sign in to comment.