Skip to content

Instantly share code, notes, and snippets.

@clakech

clakech/index.js

Last active Jun 5, 2020
Embed
What would you like to do?
const express = require('express');
const portfinder = require('portfinder');
const { render } = require('url-to-pdf-api/src/core/render-core.js');
const { Storage } = require("@google-cloud/storage");
const storage = new Storage({});
const getImage = async (path, bucketName) => storage.bucket(bucketName).file(path).createReadStream();
const streamImage = async (path, imageId, bucketName, res) => {
res.set('Content-Type', 'image/jpg');
res.set('Content-Disposition', 'attachment;filename=' + imageId);
await getImage(path, bucketName).pipe(res);
}
const store = (inspectionId, pdf, bucketName) => storage.bucket(bucketName).file(`inspection/${inspectionId}/report.pdf`).save(pdf);
const generate = async ({ data }) => {
# get the report in json
const report = JSON.parse(Buffer.from(data, "base64").toString());
# configure express
const app = express();
app.use('/api/inspections/:inspectionId/images/:imageId', ({ params: { inspectionId, imageId } }, res) =>
streamImage(`inspection/${inspectionId}/${imageId}`, imageId, process.env.IMAGE_BUCKET, res));
app.use('/api/inspections/:inspectionId/report', (req, res) => res.json(report));
app.use(express.static('www'));
# find an available port
const port = await portfinder.getPortPromise();
return new Promise((resolve) => {
const server = app.listen(port, async () => {
try {
const id = report.id;
const pdf = await render({
url: `http://localhost:${port}#/report/${id}`,
goto: { timeout: 0 }, # I don't remember why I needed this :P
emulateScreenMedia: false # use @media print to display the web page
});
await store(id, pdf, process.env.REPORT_BUCKET);
resolve(pdf);
} catch (e) {
console.error(e);
throw e;
} finally {
server.close();
}
});
});
};
exports.run = arg => generate(arg).catch(e => console.error(e));
{
"name": "pdf-report-generator",
"main": "index.js",
"version": "1.°.0",
"private": true,
"keywords": [],
"author": "",
"license": "UNLICENSED",
"dependencies": {
"@google-cloud/storage": "^4.7.0",
"express": "^4.17.1",
"portfinder": "^1.0.26",
"url-to-pdf-api": "git+https://github.com/alvarcarto/url-to-pdf-api.git"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment