Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unified feature added. #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
105 changes: 51 additions & 54 deletions handlers/generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,65 +4,62 @@ const config = require('../config');
const baseURL = config('BASE_URL');
const expiresIn = config('EXPIRES_IN');

module.exports = async function(req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({
success: true,
errors: errors.errors
});
};

const timestamp = Math.round(Date.now() / 1000);
const randomID = `${timestamp}-${revisedRandId()}`;
const pdfOptions = {
path: `static/exports/${randomID}.pdf`,
format: 'A4',
margin: {
top: 0,
right: 0,
bottom: 0,
left: 0
}
};
const availableOptions = ['scale', 'displayHeaderFooter', 'headerTemplate', 'footerTemplate', 'printBackground', 'landscape',
'pageRanges', 'format', 'width', 'height', 'margin.top', 'right', 'margin.bottom', 'margin.left', 'preferCSSPageSize'];
const integerOptions = ['scale', 'width', 'height'];
for (const option of availableOptions) {
if (req.body[option] && !option.includes('margin')) {
if (integerOptions.indexOf(option) > -1) {
pdfOptions[option] = Number(req.body[option]);
} else {
pdfOptions[option] = req.body[option];
}
}
module.exports = async function (req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({
success: true,
errors: errors.errors,
});
}

if (req.body[option] && option.includes('margin')) {
pdfOptions.margin[option.replace('margin.', '')] = req.body[option];
}
const timestamp = Math.round(Date.now() / 1000);
const randomID = `${timestamp}-${revisedRandId()}`;
const pdfOptions = {
path: `static/exports/${randomID}.pdf`,
format: 'A4',
margin: {
top: 0,
right: 0,
bottom: 0,
left: 0,
},
};
const availableOptions = ['scale', 'displayHeaderFooter', 'headerTemplate', 'footerTemplate', 'printBackground', 'landscape', 'pageRanges', 'format', 'width', 'height', 'margin.top', 'margin.right', 'margin.bottom', 'margin.left', 'preferCSSPageSize'];
const integerOptions = ['scale', 'width', 'height'];
for (const option of availableOptions) {
if (req.body[option] && !option.includes('margin')) {
if (integerOptions.indexOf(option) > -1) {
pdfOptions[option] = Number(req.body[option]);
} else {
pdfOptions[option] = req.body[option];
}
}

if (!global.browser) {
global.browser = await puppeteer.launch({ args: ['--no-sandbox'] })
if (req.body[option] && option.includes('margin')) {
pdfOptions.margin[option.replace('margin.', '')] = req.body[option];
}
const page = await global.browser.newPage();
if (req.body.url) {
await page.goto(req.body.url);
} else {
await page.setContent(req.body.html);
}
await page.pdf(pdfOptions);
}

await page.close();
if (!global.browser) {
global.browser = await puppeteer.launch({ args: ['--no-sandbox'] });
}
const page = await global.browser.newPage();
if (req.body.url) {
await page.goto(req.body.url);
} else {
await page.setContent(req.body.html);
}
await page.pdf(pdfOptions);

return res.status(200).json({
success: true,
url: `${baseURL}/exports/${randomID}.pdf`,
path: `/exports/${randomID}.pdf`,
expires: timestamp + expiresIn
});
}
await page.close();

return res.download(`static/exports/${randomID}.pdf`);
};

function revisedRandId() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}
return Math.random()
.toString(36)
.replace(/[^a-z]+/g, '')
.substr(2, 10);
}
89 changes: 89 additions & 0 deletions handlers/generateUnified.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
const { validationResult } = require('express-validator');
const puppeteer = require('puppeteer');
const config = require('../config');
const baseURL = config('BASE_URL');
const expiresIn = config('EXPIRES_IN');
const PDFMerger = require('pdf-merger-js');

module.exports = async function (req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({
success: true,
errors: errors.errors,
});
}

const timestamp = Math.round(Date.now() / 1000);

const files = [];

const mergedFileId = `${timestamp}-merged-${revisedRandId()}`;

req.body.base64Htmls.forEach((htmlElement) => {});

for (const index in req.body.base64Htmls) {
const htmlElement = req.body.base64Htmls[index];

const randomID = `${timestamp}-${revisedRandId()}`;
const pdfOptions = {
path: `static/exports/${randomID}.pdf`,
format: 'A4',
margin: {
top: 0,
right: 0,
bottom: 0,
left: 0,
},
};

const availableOptions = ['scale', 'displayHeaderFooter', 'headerTemplate', 'footerTemplate', 'printBackground', 'landscape', 'pageRanges', 'format', 'width', 'height', 'margin.top', 'margin.right', 'margin.bottom', 'margin.left', 'preferCSSPageSize'];
const integerOptions = ['scale', 'width', 'height'];
for (const option of availableOptions) {
if (req.body[option] && !option.includes('margin')) {
if (integerOptions.indexOf(option) > -1) {
pdfOptions[option] = Number(req.body[option]);
} else {
pdfOptions[option] = req.body[option];
}
}

if (req.body[option] && option.includes('margin')) {
pdfOptions.margin[option.replace('margin.', '')] = req.body[option];
}
}

if (!global.browser) {
global.browser = await puppeteer.launch({ args: ['--no-sandbox'] });
}
const page = await global.browser.newPage();

const dec = Buffer(htmlElement, 'base64').toString('UTF8');
await page.setContent(dec);

await page.pdf(pdfOptions);

await page.close();

files.push(randomID);
}

const merger = new PDFMerger();

await (async () => {
files.forEach((id) => {
merger.add('static/exports/' + id + '.pdf');
});

await merger.save('static/exports/' + mergedFileId + '.pdf'); //save under given name and reset the internal document
})();

return res.download(`static/exports/${mergedFileId}.pdf`);
};

function revisedRandId() {
return Math.random()
.toString(36)
.replace(/[^a-z]+/g, '')
.substr(2, 10);
}
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const speedLimiter = slowDown({
delayMs: config('RATE_LIMIT_DELAY_MS')
});

app.use(bodyParser.json());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(express.static('static'))
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"express-slow-down": "^1.3.1",
"express-validator": "^6.1.1",
"multer": "^1.4.2",
"pdf-merger-js": "^3.4.0",
"puppeteer": "^1.19.0"
},
"engines": {
Expand Down
Loading