Skip to content

Instantly share code, notes, and snippets.

@hassansin
Created September 22, 2017 09:52
Show Gist options
  • Save hassansin/7a7b7eefa09f9329e77df94a6204c0ce to your computer and use it in GitHub Desktop.
Save hassansin/7a7b7eefa09f9329e77df94a6204c0ce to your computer and use it in GitHub Desktop.
Webtask to send any Webpage to Kindle as PDF
'use latest';
import nodemailer from 'nodemailer@2.5.0';
import request from 'request@2.81.0';
module.exports = function(context, cb) {
const url = context.query.url;
const kindleAddress = context.query.address || context.secrets.KINDLE_ADDRESS;
if (!url) {
return cb(null, "missing url parameter");
}
if (!context.secrets.PDFLAYER_APIKEY) {
return cb(null, 'missing PDFLAYER_APIKEY');
}
if (!context.secrets.SMTP_CONFIG) {
return cb(null, 'missing SMTP_CONFIG');
}
if (!kindleAddress) {
return cb(null, 'missing kindle email address');
}
let filename = "";
return getTitle(url)
.then(title => {
filename = `${title || 'document'}.pdf`;
return htmlToPDF(context.secrets.PDFLAYER_APIKEY, context.secrets.PDFLAYER_SANDBOX, url);
})
.then(pdf => sendToKindle(context.secrets.SMTP_CONFIG, kindleAddress, [{
filename,
content: pdf,
}]))
.then(info => cb(null,info))
.catch(cb);
};
/**
* Validates url and returns page title
*/
function getTitle(url){
return new Promise((resolve, reject)=>{
request(url, (err, res, body) => {
if(err || res.statusCode !== 200) {
return reject(err || res.statusCode);
}
const matches = body.match(/title>(.*?)<\/title/i);
return resolve(matches? matches[1]: '');
});
});
}
/**
* sends attachments to kindle address
*/
function sendToKindle(smtpconfig, address, attachments){
return new Promise((resolve, reject)=>{
var transporter = nodemailer.createTransport(smtpconfig);
var mailOptions = {
to: address,
subject: 'document',
attachments
};
transporter.sendMail(mailOptions, (err, info)=> {
if(err){
return reject(err);
}
return resolve(info);
});
});
}
/**
* converts any url to pdf using pdflayer.com
*/
function htmlToPDF(apiKey, sandbox, source){
let url = `http://api.pdflayer.com/api/convert?access_key=${apiKey}&document_url=${source}&margin_top=0&margin_bottom=0&margin_left=0&margin_right=0&use_print_media=1`;
if (sandbox) {
url += "&test=1";
}
return new Promise((resolve, reject) => {
request({
url,
encoding: null,
}, (err, res, body)=> {
if(err || res.statusCode !== 200) {
return reject(err || res.statusCode);
}
return resolve(body);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment