How can I load pdf with base64 using mozilla pdf js viewer - javascript

I am using mozilla pdf js viewer to render pdf on my page.
I never used this third party dependency and I am struggling with basic things because there is very small amount of documentation how things works.
I am getting base 64 from API and I need to show this base 64 on my page.
I found some examples on their page but they are not working
https://mozilla.github.io/pdf.js/examples/
I tried
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>'Hello, world!' example</title>
</head>
<link href="index.css" rel="stylesheet" />
<body>
<h1>'Hello, world!' example</h1>
<h1>PDF.js 'Hello, world!' example</h1>
<canvas id="the-canvas"></canvas>
<script src="index.js"></script>
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
</body>
</html>
#the-canvas {
border: 1px solid black;
direction: ltr;
}
// atob() is used to convert base64 encoded PDF to binary-like data.
// (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
// Base64_encoding_and_decoding.)
var pdfData = atob(
'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
// Using DocumentInitParameters object to load binary data.
var loadingTask = pdfjsLib.getDocument({data: pdfData});
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
// Fetch the first page
var pageNumber = 1;
pdf.getPage(pageNumber).then(function(page) {
console.log('Page loaded');
var scale = 1.5;
var viewport = page.getViewport({scale: 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 renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
console.log('Page rendered');
});
});
}, function (reason) {
// PDF loading error
console.error(reason);
});
but I get error Uncaught TypeError: Cannot read properties of undefined (reading 'GlobalWorkerOptions')
I have downloaded pdfjs-dist locally in my project I have the web and build folders.
How can i U se the viewer html from web folder and load files on my page ?
I also tried this
https://www.youtube.com/watch?v=TstpR_gGb-4
I also need to load the pdf in iframe

Related

Rendering with PDF.js - misprinting issue

I am working on PDF.js and trying to render a pdf on a webpage. I am facing misprinting issue when displaying pdf. You can see that some text is not printed properly
Bad display
However, when I see the pdf in Acrobat, it is displayed perfectly.
Good Display
Note* - The Pdf contains only text, no images.
I'm using very basic code to display the pdf file
var url = './highlighter_updated.pdf';
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
// Asynchronous download of PDF
var loadingTask = pdfjsLib.getDocument(url);
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
// Fetch the first page
var pageNumber = 1;
pdf.getPage(pageNumber).then(function(page) {
console.log('Page loaded');
var scale = 1.0;
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 renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
console.log('Page rendered');
});
});
}, function (reason) {
// PDF loading error
console.error(reason);
});
Can anyone suggest what is wrong with this.
Thanks in advance.

Error loading image through localforage blob on ios

I am grabbing camera image on an ios device through Cordova camera API and then saving it through localforage. However, it seems that the resource is not being loaded since clicking on the blob under Resources tag of Safari Web Inspector shows An error occured while trying to load resources error, and the image renders as 20x20 white background instead of photo. Here is my HTML wrapper around Cordova Camera API:
<head>
<title>Capture Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/camera.js"></script>
<script type="text/javascript" charset="utf-u" src="js/localforage.js"></script>
<script type="text/javascript">
function savePhoto(contents){
localforage.setItem('photo', contents, function(img) {
// This will be a valid blob URI for an <img> tag.
var blob = new Blob([img], { type: "image/jpeg" } );
var imageURI = window.URL.createObjectURL(blob);
console.log(imageURI);
var newImg = document.createElement("img");
newImg.src=imageURI;
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newImg, currentDiv);
});
console.log(contents.byteLength);
}
function grabPhoto(){
capturePhotoEdit(savePhoto,function(e){console.log(e);});
}
</script>
</head>
<body>
<button onclick="grabPhoto();">Capture Photo</button> <br>
<div id="div1"> </div>
</body>
</html>
We use savePhoto to save down the image grabbed from the camera (in js/camera.js). Console logging of blob prints out stuff like blob:null/916d1852-c8c5-4b3b-ac8c-86b6c71d0e86.
I will very much appreciate pointers on what I am doing wrong here with image rendering.
Fixed now by switching to "Promise" style API. Somehow, it doesn't work for async callback API version. Fixed JS code below:
function savePhoto(contents){
localforage.setItem('photo', contents).then(function(image) {
// This will be a valid blob URI for an <img> tag.
var blob = new Blob([image],{ type:"image/jpeg" });
console.log('size=' + blob.size);
console.log('type=' + blob.type);
var imageURI = window.URL.createObjectURL(blob);
var newImg = document.createElement("img");
newImg.src=imageURI;
newImg.onload = function() {
URL.revokeObjectURL(imageUrI);
};
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newImg, currentDiv);
}).catch(function(err) {
// This code runs if there were any errors
console.log(err);
});
}
function grabPhoto(){
capturePhotoEdit(savePhoto,function(e){console.log(e);});
}

PDF Js does not work in meteor

I am using Mozilla pdf js in meteor. The package I am using is from "https://atmospherejs.com/pascoual/pdfjs"
I am doing almost everything that they have stated in their example, but my pdf file is delivered as a image file. It is not getting displayed as shown in their example "https://mozilla.github.io/pdf.js/web/viewer.html".
Please let me know what have I done wrong. My code is as follows:
<template name="displayResume">
<canvas id="pdfcanvas"></canvas>
</template>
Template.displayResume.rendered = function(){
PDFJS.workerSrc = '/packages/pascoual_pdfjs/build/pdf.worker.js';
console.log(PDFJS)
//PDFJS.workerSrc = '/.meteor/local/build/programs/web.browser/packages/pascoual_pdfjs/build/pdf.worker.js';
var url = '/Lez6dci9xoaiyWuzR.pdf';
PDFJS.getDocument(url).then(function getPdfHelloWorld(pdf) {
// Fetch the first page
pdf.getPage(1).then(function getPageHelloWorld(page) {
var scale = 1;
var viewport = page.getViewport(scale);
// Prepare canvas using PDF page dimensions
var canvas = document.getElementById('pdfcanvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
page.render({canvasContext: context, viewport: viewport}).promise.then(function () {
console.log('rendered');
});
});
});
}
I am just trying to display resume from my public folder as of now. Later, I will have to display file from amazon aws.
Thanks in advance
they had a pageviewer example here:
https://github.com/mozilla/pdf.js/blob/master/examples/components/pageviewer.js
I think the line you are looking for is:
textLayerFactory: new PDFJS.DefaultTextLayerFactory(),

upload a new image in canvas without eliminating existing image

I'm trying to create a web design custom made dress. I made ​​it with easel.js. I have a problem when I upload images into the clothes that are on the canvas when the initial functions, image shirt has disappeared ("upload / men_shirt_front.png").
function init() {
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
var ctx = canvas.getContext("2d");
// Enable touch support
if (createjs.Touch.isSupported()) { createjs.Touch.enable(stage); }
// create amd draw the branding image for the qr-code
var Shirt = new Image();
Shirt.addEventListener('load', function () {
ctx.drawImage(this, 10, 10, 275, 275);
},false);
Shirt.src = "upload/men_shirt_front.png";
}
I know that the real problem is in
displayPicture = function (imgPath) {
var image = new Image();
image.onload = function () {
// Create a Bitmap from the loaded image
var img = new createjs.Bitmap(event.target)
// scale it
img.scaleX = img.scaleY = 0.5;
/// Add to display list
stage.addChild(img);
//Enable Drag'n'Drop
enableDrag(img);
// Render Stage
stage.update();
}
// Load the image
image.src = imgPath;
}
I have tried many many ways to change it but I can not. how to upload a new image in canvas without eliminating existing image in initial function?
below is the full code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Upload and display images on HTML5 Canvas</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<script src="easeljs-0.5.0.min.js"></script>
<script src="jquery-1.8.2.js"></script>
<script type="text/javascript" src="libs/upclick-min.js"></script>
<script src="libs/export_canvas/base64.js" type="text/javascript"></script>
<script src="libs/export_canvas/canvas2image.js" type="text/javascript"></script>
</head>
<script type="text/javascript">
/** Init */
window.onload = init;
function init() {
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
var ctx = canvas.getContext("2d");
// Enable touch support
if (createjs.Touch.isSupported()) { createjs.Touch.enable(stage); }
// create amd draw the branding image for the qr-code
var Shirt = new Image();
Shirt.addEventListener('load', function () {
ctx.drawImage(this, 10, 10, 275, 275);
},false);
Shirt.src = "upload/men_shirt_front.png";
}
/**Export and save the canvas as PNG */
function exportAndSaveCanvas() {
// Get the canvas screenshot as PNG
var screenshot = Canvas2Image.saveAsPNG(canvas, true);
// This is a little trick to get the SRC attribute from the generated <img> screenshot
canvas.parentNode.appendChild(screenshot);
screenshot.id = "canvasimage";
data = $('#canvasimage').attr('src');
canvas.parentNode.removeChild(screenshot);
// Send the screenshot to PHP to save it on the server
var url = 'upload/export.php';
$.ajax({
type: "POST",
url: url,
dataType: 'text',
data: {
base64data : data
}
});
}
/** Export and display the canvas as PNG in a new window */
function exportAndView() {
var screenshot = Canvas2Image.saveAsPNG(canvas, true);
var win = window.open();
$(win.document.body).html(screenshot );
}
</script>
<body onload="init()">
<div style="position: relative" >
<input type="button" value="View screenshot in a new page" onClick="exportAndView()" >
<input type="button" value="Export and Upload Screenshot" onClick="exportAndSaveCanvas()" >
<input id="uploader" type="button" value="Upload picture from hard disk">
</div>
<canvas width="1000" height="550" id="canvas"></canvas>
<script type="text/javascript">
var canvas;
var stage;
var uploader = document.getElementById('uploader');
/**
* UPLOAD SCRIPT
* This script uses the upclick-min.js library to upload files on a webserver folder
* using a PHP script ("upload/upload.php")
* Project homepage: http://code.google.com/p/upload-at-click/
*/
upclick(
{
element: uploader,
action: 'upload/upload.php',
onstart:
function(filename)
{
//alert('Start upload: '+filename);
},
oncomplete:
function(response_data)
{
// Check upload Status
if (response_data != "FAIL") {
// Draw the picture into Canvas
// "response_data" contains the image file name returned from the PHP script
displayPicture("upload/" + response_data);
}
}
});
/**
* Load and display the uploaded picture on CreateJS Stage
*/
displayPicture = function (imgPath) {
var image = new Image();
image.onload = function () {
// Create a Bitmap from the loaded image
var img = new createjs.Bitmap(event.target)
// scale it
img.scaleX = img.scaleY = 0.5;
/// Add to display list
stage.addChild(img);
//Enable Drag'n'Drop
enableDrag(img);
// Render Stage
stage.update();
}
// Load the image
image.src = imgPath;
}
/**
* Enable drag'n'drop on DisplayObjects
*/
enableDrag = function (item) {
// OnPress event handler
item.onPress = function(evt) {
var offset = { x:item.x-evt.stageX,
y:item.y-evt.stageY};
// Bring to front
stage.addChild(item);
// Mouse Move event handler
evt.onMouseMove = function(ev) {
item.x = ev.stageX+offset.x;
item.y = ev.stageY+offset.y;
stage.update();
}
}
}
</script>
</body>
</html>
It's upload script 'upload/upload.php'
<?php
$tmp_file_name = $_FILES['Filedata']['tmp_name'];
$ok = move_uploaded_file($tmp_file_name, $_FILES['Filedata']['name']);
// This message will be passed to 'oncomplete' function
echo $ok ? $_FILES['Filedata']['name'] : "FAIL";
?>

IE Copy Canvas in Pop-Up Window DOM Exception: TYPE_MISMATCH_ERR (17)

I don't know if there is a work around for this IE9 issue I ran into, but here's what I'm trying to do. I have an image in a canvas on my page. I want to copy this canvas image to another canvas, but in a pop-up window I create. What I'm encountering in this experiment is I can copy the canvas image into another dynamically created canvas on the same page, no problem. But when I try to do it in a pop-up window, IE gives me a DOM Exception: TYPE_MISMATCH_ERR (17). Sadly, this seems to be an IE thing, because I ran my same code in Chrome, and it worked...
So here's my code. You'll need to provide your own image though, I used a simple 640x480 jpeg file. You'll also need the console open, since I'm doing a console.error. I also tried this code as a file and running from localhost on my local IIS.
<!DOCTYPE html>
<html>
<head>
<title>Canvas Copy Test</title>
<style>
#mainSrc {
border:1px solid red;
}
#dest01 {
width:640px;
height:480px;
border:1px solid blue;
}
</style>
<script>
var destWin; // Destination Window
window.onload=function()
{
var testImg = new Image();
testImg.src = "me.jpg";
testImg.onload = function()
{
var mainCanvas = document.getElementById("mainSrc");
var mainCtx = mainCanvas.getContext("2d");
mainCtx.drawImage(testImg,0,0);
}
var copyBtn = document.getElementById("copyBtn");
var copyWinBtn = document.getElementById("copy2WinBtn");
copyBtn.addEventListener("click",copyImage,false);
copyWinBtn.addEventListener("click",copy2Win,false);
}
// Copy Canvas Image to Another on the same page.
function copyImage()
{
var mainCanvas = document.getElementById("mainSrc");
var destCanvas = document.createElement("canvas");
var destDiv = document.getElementById("dest01");
destCanvas.width = mainCanvas.width;
destCanvas.height = mainCanvas.height;
var dCtx = destCanvas.getContext("2d");
dCtx.drawImage(mainCanvas,0,0);
destDiv.appendChild(destCanvas);
}
// Copy Canvas to Popup Window
function copy2Win()
{
var mainCanvas = document.getElementById("mainSrc");
try {
destWin = window.open("","destWin");
var destWinDoc = destWin.document;
var destWinHTML = "<!DOCTYPE html><html><head><title>POPUP</title><body><div id='destWinDiv' style='width:640px; height:480px; border:1px solid red'></div></body></html>";
destWinDoc.write(destWinHTML);
var destCanvas = destWinDoc.createElement("canvas");
var destDiv = destWinDoc.getElementById("destWinDiv");
destCanvas.width = mainCanvas.width;
destCanvas.height = mainCanvas.height;
var dCtx = destCanvas.getContext("2d");
dCtx.drawImage(mainCanvas,0,0);
destDiv.appendChild(destCanvas);
}
catch (err)
{
console.error(err);
}
}
</script>
</head>
<body>
<canvas id="mainSrc" width="640" height="480"></canvas>
<p>
<input type="button" name="Copy" value="Copy" id="copyBtn" />
<input type="button" name="Copy2Win" value="Copy To New Window" id="copy2WinBtn" />
</p>
<div id="dest01"></div>
</body>
</html>
Well, after playing around a little more, I figured out that the tag can actually take in a base64 encoded image from the canvas toDataURL() and display it... So I was able to make this modification in my above copy2Win function to be this:
function copy2Win()
{
var mainCanvas = document.getElementById("mainSrc");
destWin = window.open("","destWin");
var destWinDoc = destWin.document;
var destWinHTML = "<!DOCTYPE html><html><head><title>POPUP</title><body><div id='destWin' style='width:640px; height:480px; border:1px solid red'><img src='" + mainCanvas.toDataURL() + "' alt='Copy!' /></div></body></html>";
destWinDoc.write(destWinHTML);
}
The thing to note is I'm writing out the img tag's src to be the canvas.toDataURL(), and this works. IE doesn't complain about this. Although the data isn't into another canvas, I'm able to get what I need, which is my image data pulled from my canvas and displayed in a new window. Interestingly, if you look at the generated source code the image is actually shown as the base64 encoded data in the src, so it seems the browser is decoding the src data for display; interesting.

Categories

Resources