Select thumbnails with PDFjs - javascript

After upload a pdf i show with PDF.js a thumbnails and work it.
$(document).ready(function () {
if (!PDFJS.workerSrc && typeof document !== 'undefined') {
// workerSrc is not set -- using last script url to define default location
PDFJS.workerSrc = (function () {
'use strict';
var scriptTagContainer = document.body ||
document.getElementsByTagName('head')[0];
var pdfjsSrc = scriptTagContainer.lastChild.src;
return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
})();
PDFJS.workerSrc = 'pdfjs-dist-master/build/pdf.worker.js';
}
$("#pdfInp").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
showInCanvas(e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
function showInCanvas(url) {
// See README for overview
'use strict';
// Fetch the PDF document from the URL using promises
var pdfAsArray = convertDataURIToBinary(url);
PDFJS.getDocument(pdfAsArray).then(function (pdf) {
// Using promise to fetch the page
// Get div#container and cache it for later use
var container = document.getElementById("container");
// Loop from 1 to total_number_of_pages in PDF document
for (var i = 1; i <= pdf.numPages; i++) {
// Get desired page
pdf.getPage(i).then(function(page) {
var scale = .3;
var viewport = page.getViewport(scale);
var div = document.createElement("div");
// Set id attribute with page-#{pdf_page_number} format
div.setAttribute("id", "page-" + (page.pageIndex + 1));
// This will keep positions of child elements as per our needs
//div.setAttribute("style", "position: relative");
div.setAttribute("class", "page");
// Append div within div#container
container.appendChild(div);
// Create a new Canvas element
var canvas = document.createElement("canvas");
// Append Canvas within div#page-#{pdf_page_number}
div.appendChild(canvas);
var node = document.createElement("p");
var textnode = document.createTextNode("pagina " + (page.pageIndex + 1));
node.appendChild(textnode);
div.appendChild(node);
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
});
}//END LOOP
});
}
});
But i want select a multiple thumbnail show it. I think possible with the class css. This the code
$.fn.seleziona = function() {
var menuSel = $(this);
menuSel.find('.page').on('click', function() {
if ($(this).hasClass('open')) {
$(this).removeClass('open');
} else {
$(this).addClass('open');
}
});
};
$(document).ready(function(){
$("#container").seleziona();
});
end not work. That code worked only the DOM be present before the upload

Related

modify function for local HTML code

I have function that works perfect, but not for my scope:
function _svgToCanvas() {
var nodesToRecover = [];
var nodesToRemove = [];
var svgElems = document.getElementsByTagName('svg');
for (var i = 0; i < svgElems.length; i++) {
var node = svgElems[i];
var parentNode = node.parentNode;
var svg = parentNode.innerHTML;
var canvas = document.createElement('canvas');
canvg(canvas, svg);
nodesToRecover.push({
parent: parentNode,
child: node
});
parentNode.removeChild(node);
nodesToRemove.push({
parent: parentNode,
child: canvas
});
parentNode.appendChild(canvas);
}
}
I'm trying to modify it for using local code that comes from param, like this:
function _svgToCanvas(content) {
var nodesToRecover = [];
var nodesToRemove = [];
var svgElems = content.getElementsByTagName('svg');
for (var i = 0; i < svgElems.length; i++) {
}
return content;
}
var content = $('#main_contents').get(0);
result = _svgToCanvas(content);
But I can't modify the for loop. How to modify it?
Looks like the "var svg = parentNode.innerHTML;" doesn't give you the correct parameter for function canvg.
This piece of code comes from canvg.js, try it.
function _svgToCanvas(content) {
var svgTags = content.querySelectorAll('svg');
for (var i=0; i<svgTags.length; i++) {
var svgTag = svgTags[i];
var c = document.createElement('canvas');
c.width = svgTag.clientWidth;
c.height = svgTag.clientHeight;
svgTag.parentNode.insertBefore(c, svgTag);
svgTag.parentNode.removeChild(svgTag);
var div = document.createElement('div');
div.appendChild(svgTag);
canvg(c, div.innerHTML);
}
return content;
}
This funtion will not change the original content, and just return a new dom node.
function _svgToCanvas(content) {
var newContent = content.cloneNode(true);
var svgTags = newContent.querySelectorAll('svg');
var svgTagsOriginal = content.querySelectorAll('svg');
for (var i=0; i<svgTags.length; i++) {
var svgTag = svgTags[i];
var svgTagOriginal = svgTagsOriginal[i];
var c = document.createElement('canvas');
c.width = svgTagOriginal.clientWidth;
c.height = svgTagOriginal.clientHeight;
svgTag.parentNode.insertBefore(c, svgTag);
svgTag.parentNode.removeChild(svgTag);
content.appendChild(c);
var div = document.createElement('div');
div.appendChild(svgTag);
canvg(c, div.innerHTML);
}
return newContent;
}

how to use drawImage after load all images in array

I want to draw image array with drawImage after all the images are loaded.There is a render problem with drawImage(), tried to solve with setTimeout() but its not working all the time.
Here is my code;
while(FocusItem.length>0)
{
FocusItem.pop();
}
ftx=canvas.getContext('2d');
focusImageBackground = new Image();
focusImageBackground.src = "./images/odaklanma/odaklanmaBackground.jpg";
if(RandomSoru==15)
finishSoru=true;
if(finishSoru)
{
RandomSoru = Math.floor((Math.random() * 15)+1);
tempRandomSoru=RandomSoru;
}
if(RandomSoru==tempRandomSoru)
{
RandomSoru = Math.floor((Math.random() * 15)+1);
}
var soru = new Object();
soru["image"] = new Image();
soru.image.src = './images/odaklanma/level/'+RandomSoru+'/soru.png';
soru["x"] = 341;
soru["y"] = 140;
FocusItem.push(soru);
var dogru = new Object();
dogru["image"] = new Image();
dogru.image.src = './images/odaklanma/level/'+RandomSoru+'/dogru.png';
dogru["x"] = xDogru;
dogru["y"] = 280;
FocusItem.push(dogru);
var yanlis = new Object();
yanlis["image"] = new Image();
yanlis.image.src = './images/odaklanma/level/'+RandomSoru+'/yanlis.png';
yanlis["x"] = xYanlis1;
yanlis["y"] = 280;
FocusItem.push(yanlis);
var yanlis2 = new Object();
yanlis2["image"] = new Image();
yanlis2.image.src = './images/odaklanma/level/'+RandomSoru+'/yanlis1.png';
yanlis2["x"] = xYanlis2;
yanlis2["y"] = 280;
FocusItem.push(yanlis2);
}
if(focusImageBackground.complete){
if(FocusItem[0].image.complete && FocusItem[1].image.complete && FocusItem[2].image.complete && FocusItem[3].image.complete)
drawFocus();
else
setTimeout(drawFocus,600);
}
else
focusImageBackground.onload=function(){
if(FocusItem[0].image.complete && FocusItem[1].image.complete && FocusItem[2].image.complete && FocusItem[3].image.complete)
drawFocus();
else
setTimeout(drawFocus,600);
}
function drawFocus(){
ftx.drawImage(focusImageBackground,0,0);
for (var i=0; i<FocusItem.length; i++){
FocusItem[i].image.onload=function(){
ftx.drawImage (FocusItem[i].image, FocusItem[i].x, FocusItem[i].y);
}
}
}
I'd suggest loading all your images, then when they are all done, you can call the rest of your code. I don't quite follow what you're trying to do with all the rest of your code, but here's a simple way to load an array of image URLs and know when they are done.
This is the general idea (I've left out lots of your code that has nothing to do with the central issue of knowing when all the images are loaded) and I've also tried to DRY up your code:
function createImagesNotify(srcs, fn) {
var imgs = [], img;
var remaining = srcs.length;
for (var i = 0; i < srcs.length; i++) {
img = new Image();
imgs.push(img);
img.onload = function() {
--remaining;
if (remaining == 0) {
fn(srcs);
}
};
// must set .src after setting onload handler
img.src = srcs[i];
}
return(imgs);
}
// here's your starting array of filenames
var fnames = ["soru.png", "dogru.png", "yanlis.png", "yanlis1.png"];
// insert your process to create RandomSoru here
var randomSoru = ....;
// build full urls array
var urls = [];
for (var i = 0; i < fnames; i++) {
urls.push('./images/odaklanma/level/' + RandomSoru + '/' + fnames[i]);
}
// load all images and call callback function when they are all done loading
var imgs = createImagesNotify(urls, function() {
// all images have been loaded here
// do whatever you want with all the loaded images now (like draw them)
});
This code is based on an earlier answer of mine here: Cross-browser solution for a callback when loading multiple images?

Detect img src and then change it with javascript

This is my code:
var i;
var pic = document.getElementById('image');
var picSrc = pic.src;
var fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
document.getElementById('next').onmousedown = function () {
i = 0;
// it works up to here
pic.addEventListener("DOMAttrModified", function(event) {
if (i == 0 && event.attrName == "src") {
pic = document.getElementById('image');
i = 1; // this is to prevent endless loop
picSrc = pic.src;
fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
}
});
return true;
};
It should work on imgur's horizontal layout albums, and replace the low-res images with full-res ones, one image at a time (currently displayed image).
On click of the "next" button, a new image is displayed. However, the script does not load the next full-res image. It only works with the first image loaded.
You're messing up your scope completely, invalidating the entire code after the first run. This should also pop up more than enough errors in your console. Reshuffle assignments to the right spot:
document.getElementById('next').onmousedown = function () {
var i;
var pic = document.getElementById('image');
var picSrc = pic.src;
var fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
pic.addEventListener("DOMAttrModified", function(event) {
if (i == 0 && event.attrName == "src") {
pic = document.getElementById('image');
i = 1; // this is to prevent endless loop
picSrc = pic.src;
fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
}
});
return true;
};
Depending on how the page works specifically (I can't see without having a real world use case) you might have to reassign the entire mousedown event as well.
On every mousedown you are adding a new DOMAttrModified event listener.
Try arranging your code to something like following:
var pic = document.getElementById('image');
var i;
pic.addEventListener("DOMAttrModified", function(event) {
if (i == 0 && event.attrName == "src") {
//pic = document.getElementById('image');
i = 1; // this is to prevent endless loop
picSrc = pic.src;
fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
i = 0;
});
document.getElementById('next').onmousedown = function () {
var picSrc = pic.src;
var fullSrc = picSrc.split('h.jpg')[0] + '.jpg';
pic.src = fullSrc;
});
You should also try using the addEventListener instead of onmousedown

Javascript DOM Mouse Event is not working for IE and Mozilla

Working on the Custom File upload application. I have 2 major issues:
The following given below code is not Opening the File Dialogue Box for Mozilla and IE.
In Chrome its working, but when I select File on First Click, it never adds file to the body. But in second click it adds the file which was Browse in First Click to the body.
Any help for the above issues will be appreciated.
function perform1Click(node) {
alert("INIT");
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
node.dispatchEvent(evt);
alert(3)
getFile(evt);
}
function getFile(event) {
var files = event.target.files;
var totalSize = 0;
if (totalSize > 1024*10) {
alert('Total size exceed 1 Mb.');
return;
}
//alert(files)
//alert(files.length);
for (var i = 0, f; f = files[i]; i++) {
displayFileList(f.name, f.size);
totalSize = totalSize+f.size;
}
}
function displayFileList(name, size) {
if (name != '') {
var top_plugin = document.getElementById('top_plugin');
// create tag
var ptag = document.createElement("p");
// create div
var divBox = document.createElement("div");
divBox.setAttribute('class', 'divBox');
// create input[type='checkbox']
var inputCheckBox = document.createElement("input");
inputCheckBox.setAttribute('type', 'checkbox');
inputCheckBox.setAttribute('id', 'checkboxClass')
// add checkbox to div.
divBox.appendChild(inputCheckBox);
// create text node for divBox and add it to divBox.
var txtNode = document.createTextNode(name);
divBox.appendChild(txtNode)
var sizeDivBox = document.createElement("p");
sizeDivBox.setAttribute('style', 'clear:both; display: inline-block;');
var txtSizeNode = document.createTextNode(size);
sizeDivBox.appendChild(txtSizeNode);
divBox.appendChild(sizeDivBox);
// add divBox to ptag.
ptag.appendChild(divBox);
//ptag.appendChild(divTxt);
// add ptag to top_plugin div.
top_plugin.appendChild(ptag);
}
// if file value is not null, make it blank.
if (name != '')
{
name = '';
}
}
I got the solution for the same problems. Please find below the new code.
function uploadDFiles() {
var file = document.getElementById('_file');
file.click();
try {
file.addEventListener("change", getFileName);
}
catch (e) {
file.attachEvent("onclick", getFileNameOnIE);
alert("Error:: "+e.description);
}
}
function getFileName(event) {
var files = event.target.files;
for (var i = 0, f; f = files[i]; i++) {
var fileName = f.name;
var fileSize = f.size;
var fSize = bytesToSize(fileSize, 2);
displayFileList(fileName, fSize);
}
}
But now I have new problem. This code is not working in IE.For IE i am using attachEvent method and its not working. Please find below the code:
function getFileNameOnIE(event) {
alert(event.type);
var files = event.target;
alert(files.length);
for (var i = 0, f; f = files[i]; i++) {
displayFileList(f.name, f.size);
}
}
Can someone provide me the solution for the same now?
--
Tks
Bharat

How to preload images and then change div contents once the imaged are done loading

I am trying to preload a bunch of images, and then once they are FULLY loaded, change the contents of a div, here is my code so far, but it just throws my browser into an infinite loop. Any help would be great. Thanks!
var mydir ='slideshow_pics/';
var myArray = new Array();
myArray[0] = mydir+'0.jpg';
myArray[1] = mydir+'1.jpg';
myArray[2] = mydir+'2.jpg';
myArray[3] = mydir+'3.jpg';
myArray[4] = mydir+'4.jpg';
myArray[5] = mydir+'5.jpg';
myArray[6] = mydir+'6.jpg';
myArray[7] = mydir+'7.jpg';
var myWidth = new Array();
myWidth[0] = '470';
myWidth[1] = '450';
myWidth[2] = '450';
myWidth[3] = '500';
myWidth[4] = '550';
myWidth[5] = '450';
myWidth[6] = '800';
myWidth[7] = '300';
var myCheck = new Array();
function preloader(images){
var i = 0;
// start preloading
for(i=0; i<=images.length; i++){
imageObj = new Image();
imageObj.src=images[i];
imageObj.onLoad = check(i, images.length);
};
}
function checkimg(data, w) {
p=0;
z=0;
o = 'no';
var myImg = new Image();
myImg.src = data;
while (p == 0) {
if (myImg.naturalWidth == w) {
p = 1;
o = 'yes';
}
z++;
}
return o;
}
function check(e,i) {
if( e == i ){
if (document.getElementById('myss') != null) {
//now we need to make sure each image is fully loaded
for(i=0; i<=myArray.length; i++){
p=0;
z=0;
myCheck[i] = checkimg(myArray[i], myWidth[i]);
}//end foreach
if (myCheck.join('') == 'yesyesyesyesyesyesyesyes') {
document.getElementById('myss').innerHTML = '<embed src="RectangleSlideshow.swf" width="1028px" height="324px"></embed>';
}
}
};
}
I believe you need a sort of image pre-loading for a gallery.
I have that code implemented in my index web page:
http://www.becomingthebeast.com/index.html
See if it works for you.

Categories