Created
February 24, 2022 10:33
-
-
Save lapo-luchini/08eb5f83af16d3cdc907d21155947981 to your computer and use it in GitHub Desktop.
Create a custom PDF in base64 form (with preview)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset='utf-8'> | |
<title>Generate PDF</title> | |
<script src="https://github.com/devongovett/pdfkit/releases/download/v0.6.2/pdfkit.js"></script> | |
<script src="https://github.com/devongovett/blob-stream/releases/download/v0.1.2/blob-stream-v0.1.2.js"></script> | |
<style> | |
html, | |
body { | |
height: 100%; | |
} | |
#src { | |
width: 100%; | |
height: 5rem; | |
} | |
#b64 { | |
width: 80%; | |
} | |
</style> | |
</head> | |
<body> | |
<textarea id="src"> | |
doc.fontSize(25).text('Module 1', 50, 50); | |
doc.fontSize(5).text('random text', 50, 300) | |
</textarea> | |
<button onclick="create()">Crea</button> | |
<p>Base64: <input id="b64" type="text"></p> | |
<iframe width="100%" height="80%"></iframe> | |
<script> | |
const | |
src = document.getElementById('src'), | |
b64 = document.getElementById('b64'), | |
iframe = document.getElementsByTagName('iframe')[0]; | |
function create() { | |
const | |
doc = new PDFDocument(), | |
stream = doc.pipe(blobStream()); | |
eval(src.value); | |
doc.end(); | |
stream.on('finish', function () { | |
const | |
blob = stream.toBlob('application/pdf'), | |
reader = new FileReader(); | |
reader.readAsDataURL(blob); | |
reader.onloadend = function () { | |
var base64data = reader.result; | |
b64.value = base64data.slice(28); | |
iframe.src = base64data; | |
b64.focus(); | |
b64.select(); | |
} | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment