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

Use binary support, closes #1 #2

Open
wants to merge 2 commits 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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ For deployment
```
sls deploy
```

Manually set [binary media types](https://s.natalian.org/2017-04-30/binary-support.png) for the end point.

85 changes: 42 additions & 43 deletions example/example.html
Original file line number Diff line number Diff line change
@@ -1,44 +1,43 @@
!<!DOCTYPE html>
<html>
<head>
<title>Convert HTML to PDF Example</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</head>
<body>
<div class="container my-3">
<div class="row">
<form class="col-md-4 offset-md-4">
<div class="form-group">
<label for="url">Enter URL</label>
<input name="url" id="url" type="text" placeholder="ex: http://www.serverless.com" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
<script>
$(function () {
$('form').submit(function (e) {
e.preventDefault();
var url = $('input#url').val();
$.ajax({
method: 'POST',
url: 'https://xe6ofd5xkc.execute-api.us-west-2.amazonaws.com/stage/print',
contentType: 'application/json',
data: JSON.stringify({ url: url }),
success: function (res) {
window.open("data:application/pdf;base64, " + res);
},
dataType: 'text'
});
return;
});
});
</script>
</body>
<!DOCTYPE html>
<html lang=en>


<head>
<meta charset="utf-8" />
<meta name=viewport content="width=device-width, initial-scale=1">
<title>Serverless URL to PDF generator</title>
</head>


<body>
<form id="urlForm">
<input required id=url type=url name=url>
<input type=submit value="Generate PDF">
</form>
<iframe id="viewer">
</iframe>

<script>
document.getElementById("urlForm").addEventListener("submit", function(evt) {
evt.preventDefault();
fetch('YOUR_ENDPOINT_URL/stage/print', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/pdf'
},
body: JSON.stringify({
url: document.getElementById("url").value,
})
}).then(res => res.blob())
.then(data => {
var iframe = document.getElementById('viewer');
iframe.setAttribute('src', URL.createObjectURL(data, {
type: "application/pdf"
}));
}).catch(console.warn)
});
</script>
</body>

</html>
58 changes: 58 additions & 0 deletions example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="utf-8" />
<style>
body {
font-family: "Segoe UI", "Seravek", sans-serif;
font-size: 1.2em;
}
input { height: 1.9em; }
</style>
<meta name=viewport content="width=device-width, initial-scale=1">
<meta name="twitter:creator" content="@webconverger">
<meta name='mobile-web-app-capable' content='yes'>
<meta name='apple-mobile-web-app-capable' content='yes'>
<link rel="icon" type="image/svg+xml" href="/pdf.svg">
<title>Serverless URL to PDF generator</title>
</head>
<body>
<form id="urlForm">
<input required id=url type=url name=url>
<input type=submit value="Generate PDF">
</form>
<iframe id="viewer">
</iframe>

<script>
document.getElementById("urlForm").addEventListener("submit", function(evt) {
evt.preventDefault();
fetch('https://pdf.webconverger.com/stage/print', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/pdf'
},
body: JSON.stringify({
url: document.getElementById("url").value,
})
}).then(res => res.blob())
.then(data => {
// https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example_Using_object_URLs_to_display_PDF
var iframe = document.getElementById('viewer');
iframe.setAttribute('src', URL.createObjectURL(data, {
type: "application/pdf"
}));
}).catch(console.warn)
});
</script>

<p><a href="https://github.com/kaihendry/serverless-html-pdf">Source code</a></p>

<fieldset><legend>Advertisement</legend><p>If you need <a
href=https://webconverger.com/>stateless Web kiosk software</a>, for
showing off (Web sign or dashboard) or interacting with a Web site (school exams, tourist information), choose <a
href="https://webconverger.com">Webconverger</a>!</p></fieldset>

</body>
</html>
1 change: 1 addition & 0 deletions example/pdf.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions example/sync.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
aws --profile mine s3 cp --acl public-read index.html s3://webc-pdf/
aws --profile mine s3 cp --acl public-read pdf.svg s3://webc-pdf/
aws --profile mine cloudfront create-invalidation --distribution-id E23X77OCT994XR --invalidation-batch "{ \"Paths\": { \"Quantity\": 1, \"Items\": [ \"/*\" ] }, \"CallerReference\": \"$(date +%s)\" }"
47 changes: 25 additions & 22 deletions handler.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,49 @@
'use strict';
'use strict'

const fs = require('fs');
const path = require('path');
const execFile = require('child_process').execFile;
const fs = require('fs')
const path = require('path')
const execFile = require('child_process').execFile

module.exports.print = (event, context, callback) => {
console.log(event);
const body = JSON.parse(event.body);
const phantomjs = path.resolve('bin/phantomjs-linux');
const rasterize = path.resolve('lib/rasterize.js');
const outputPDF = '/tmp/output.pdf';
const url = body.url;
console.log(event)
const body = JSON.parse(Buffer.from(event.body, 'base64').toString('utf8'))
const phantomjs = path.resolve('bin/phantomjs-linux')
const rasterize = path.resolve('lib/rasterize.js')
const outputPDF = '/tmp/output.pdf'
const url = body.url

if (!url) {
const err = 'url parameter is undefined';
const err = 'url parameter is undefined'
return callback(err, {
statusCode: 500,
body: JSON.stringify({ 'error': err })
});
})
}

execFile(phantomjs, [rasterize, url, outputPDF, "A4", 0.68], (err, stdout, stderr) => {
console.log('execute phantomjs');
execFile(phantomjs, [rasterize, url, outputPDF], (err, stdout, stderr) => {
console.log('execute phantomjs')
if (err) {
console.log(err);
console.log(err)
callback(err, {
statusCode: 500,
body: JSON.stringify({
'error': err
}),
});
})
})
}
const output = fs.readFileSync(outputPDF);
const output = fs.readFileSync(outputPDF)
callback(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/pdf',
'Content-Disposition': 'inline; filename="sample.pdf"'
},
body: output.toString('base64')
});
});
body: output.toString('base64'),
isBase64Encoded: true
})
})

// Use this code if you don't use the http event with the LAMBDA-PROXY integration
// callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};
}
6 changes: 3 additions & 3 deletions serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ service: serverless-pdf

provider:
name: aws
runtime: nodejs4.3
runtime: nodejs6.10
stage: stage
region: us-west-2
profile: serverless
profile: mine
region: ap-southeast-1

functions:
print:
Expand Down