Skip to content

Instantly share code, notes, and snippets.

@stefanvangastel
Forked from ichord/gist:9808444
Last active October 10, 2017 15:11
Show Gist options
  • Save stefanvangastel/2e31b85b8ec60fa61b32 to your computer and use it in GitHub Desktop.
Save stefanvangastel/2e31b85b8ec60fa61b32 to your computer and use it in GitHub Desktop.
demo of using pdf.js to extract pages to images in CakePHP (http://book.cakephp.org/3.0/en/views.html#using-view-blocks)
//Your layout file
<html>
<head>
//etc
</head>
<body>
//Bla bla
<?php
//Spit out all collected script blocks in viewfile(s)
echo $this->fetch('script');
?>
</body>
</html>
$this->start('script');
<script src="http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
$this->end('script');
<!--
Created using jsbin.com
Source can be edited via http://jsbin.com/pdfjs-helloworld-v2/8598/edit
-->
<canvas id="the-canvas" style="border:1px solid black"></canvas>
<input id='pdf' type='file'/>
<!-- Use latest PDF.js build from Github -->
$this->start('script');
<script type="text/javascript" src="https://rawgithub.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<script type="text/javascript">
//
// Disable workers to avoid yet another cross-origin issue (workers need the URL of
// the script to be loaded, and dynamically loading a cross-origin script does
// not work)
//
PDFJS.disableWorker = true;
//
// Asynchronous download PDF as an ArrayBuffer
//
var pdf = document.getElementById('pdf');
pdf.onchange = function(ev) {
if (file = document.getElementById('pdf').files[0]) {
fileReader = new FileReader();
fileReader.onload = function(ev) {
console.log(ev);
PDFJS.getDocument(fileReader.result).then(function getPdfHelloWorld(pdf) {
//
// Fetch the first page
//
console.log(pdf)
pdf.getPage(1).then(function getPageHelloWorld(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
//
// Render PDF page into canvas context
//
var task = page.render({canvasContext: context, viewport: viewport})
task.promise.then(function(){
console.log(canvas.toDataURL('image/jpeg'));
});
});
}, function(error){
console.log(error);
});
};
fileReader.readAsArrayBuffer(file);
}
}
</script>
$this->end('script');
@euyulio
Copy link

euyulio commented Oct 1, 2015

thank you stefanvangastel,
but seems like the problem is with the redirections, when I debug, I see that pdf.js send this error: expected expression, got '<' like trying to read the index.php because cakephp redirects it to that file... this happens here PDFJS.getDocument(fileReader.result)
cakephp 2.x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment