Jspdf (imgage to pdf) not converting whole image to pdf - javascript

var pdff ;
function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log(reader.result)
pdff = reader.result;
pdf();
}
reader.readAsDataURL(file);
}
function pdf() {
var doc = new jsPDF();
var img = new Image();
img.src = pdff;
var width = doc.internal.pageSize.getWidth;
var height = doc.internal.pageSize.getHeight;
doc.addImage(img, 'JPG', 0, 0, width, height);
doc.save('imkk.pdf'); // downloads pdf
}
This is the code I am using currently to convert image to base64 string and then to pdf, it works with small images but I need to make a pdf in which the image is large it makes the pdf but only with a portion of image here is the image link that I want in pdf :- https://drive.google.com/file/d/1X3G3gGsTUKvAtBh78iHMh_G4oy2-O73D/

// You need to make your image into a Data URL and declare page size
var imgData = 'data:image/jpeg;base64,/9j/.............../an/9k='
var width = 8.33
var height = 125
var doc = new jsPDF({ unit: 'in', format: [width, height],})
doc.addImage(imgData, 'JPG', 0, 0, width, height)
doc.save('imkk.pdf')
The default will just be the start of image on the page, by declaring page width and height that one page can be whatever the URL length limit is for that environment, so note it can often be 1.5 MB.

Related

Can't draw image to canvas in javascript

I'm attempting to put a watermark image on an input image before saving it to a database. I'm using a canvas to do this then convert the canvas back to a blob but when I reference the watermark image in the projects local file directory to draw onto the canvas, I get a "Tainted canvases may not be exported." error in the console.
// Read input file
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
// Create canvas & calculate Stamp size and position
const canvas = document.createElement("canvas");
canvas.width = canvasSize.width;
canvas.height = canvasSize.height;
var calcW = canvasSize.width/2;
var calcH = calcW/2.16;
var calcX = (canvasSize.width - calcW)/2;
var calcY = (canvasSize.height - calcH)/2;
// Load input image into canvas
const img = document.createElement("img");
img.src = reader.result;
img.onload = () => {
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
//Load & draw the Stamp image
const mark = new Image();
mark.src = 'assets/img/compliant.png'; // <<TAINTED ASSET?
mark.onload = () => {
ctx.drawImage(mark, calcX,calcY,calcW,calcH);
// Convert to blob and get URL
canvas.toBlob((canvasBlob) => {
const newImg = document.createElement("img"),
url = URL.createObjectURL(canvasBlob);
newImg.onload = function () {
//Destroy objecturl after image loading
URL.revokeObjectURL(url);
};
// Show stamped image
newImg.src = url;
window.open(url);
});
};
};
};
});
You have to use
img.crossOrigin='anonymous';
On every image you want to manipulate (draw in a canvas, transform to an array buffer… this is to prevent you from manipulating potentially private user data)
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin

Export To Pdf angular 6

I want to export my HTML page into pdf using angular 6.
I have written following code to convert into pdf
let dataPdf = document.getElementById('contentToPrint');
const pdf = new jspdf('p', 'pt', 'a4');
pdf.addHTML(document.getElementById('contentToPrint'),()=>{
pdf.save('web.pdf');
});
Getting Following Error:
core.js:12301 ERROR Error: Supplied Data is not a valid base64-String jsPDF.convertStringToImageData
at Object.x.convertStringToImageData (jspdf.min.js:50)
at Object.x.addImage (jspdf.min.js:50)
at Object.<anonymous> (jspdf.min.js:188)
at Object.options.complete (html2canvas.js:2711)
at start (html2canvas.js:2215)
at Object._html2canvas.Preload (html2canvas.js:2488)
at html2canvas.js:2719
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:13842)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
You need to convert your image to base64.
If your images are static you can convert them here:
https://www.base64-image.de/
If images are dynamic:
Converting an image to base64 in angular 2
After image conversion to base64 string, you can pass that to jsPDf as:
pdf.addHTML('your base64 string);
I'm facing a similar problem.
It looks like you need convert your DOM element into a PNG. Once you have it, you have to convert it to base64 string and add it with pdf.addImage()
You can use html2canvas to convert DOM elements into images.
EDIT
let dataPdf = document.getElementById('contentToPrint');
const pdf = new jspdf('p', 'pt', 'a4');
html2canvas(dataPdf).then((canvas) => {
let img = canvas.toDataURL('image/png');
pdf.addImage(img, 'png', 40, 90, 515, 600); //sizings here
pdf.save('web.pdf');
}
You can do something like this
import html2canvas from 'html2canvas';
var data = document.getElementById('ELEMENT_ID');
html2canvas(data).then(canvas => {
var imgWidth = 208;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
var position = 0;
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
//save file with specific name
pdf.save("Wallet.pdf");
});

Getting Image height and width from base64 Image string in GoJS

I am trying to get the Image height and width from a base64 string representation of the image and I am using GoJS.
What I eventually want to do is to add that image to a PDF using jspdf library.
Here is what I have done so far:
download() {
let imgData = this.diagram.makeImageData({background: "white", returnType: "string"});
let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
var position = 0;
var imgWidth = imgData.width; //Reading width from Image Data
var imgHeight = imgData.height; //Reading height from Image Data
pdf.setFontSize(30);
pdf.text("Diagram", 100, 20, 'center');
pdf.addImage(imgData, 'PNG', 1, 25, position, imgWidth, imgHeight);
pdf.save("Diagram.pdf');
}
In that imgData.width and imgData.height, the visual studio intellisense is showing "Property 'height' and 'width' does not exist on type 'string'.
How can I get the height and width property of the image?
Create an HTMLImageElement using that image data, and then get its naturalWidth and naturalHeight once it has been loaded:
var imgData = myDiagram.makeImageData(. . .);
var img = document.createElement("img");
img.addEventListener('load', function(e) {
console.log(img.naturalWidth + " " + img.naturalHeight);
});
img.src = imgData;

Convert blob to image file

I am trying to convert an image file captured from an input type=file element without success. Below is my javascript code
var img = document.getElementById('myimage');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
var theBlob = reader.result;
theBlob.lastModifiedDate = new Date();
theBlob.name = file;
img.src = theBlob;
var newfile = new File([theBlob], "c:files/myfile.jpg");
}, false);
if (file) {
reader.readAsDataURL(file);
}
The image is displayed properly in the img element but the File command does not create the myfile.jpg image file. I am trying to capture the image and then resizing it using javascript before I upload it to the server. Anyone know why the image file is not being created? Better yet, anyone have code on how to resize an image file on the client and then upload it to a server?
This is how you can get a resized jpeg file from your "myimage" element using Canvas.
I commented every line of code so you could understand what I was doing.
// Set the Width and Height you want your resized image to be
var width = 1920;
var height = 1080;
var canvas = document.createElement('canvas'); // Dynamically Create a Canvas Element
canvas.width = width; // Set the width of the Canvas
canvas.height = height; // Set the height of the Canvas
var ctx = canvas.getContext("2d"); // Get the "context" of the canvas
var img = document.getElementById("myimage"); // The id of your image container
ctx.drawImage(img,0,0,width,height); // Draw your image to the canvas
var jpegFile = canvas.toDataURL("image/jpeg"); // This will save your image as a
//jpeg file in the base64 format.
The javascript variable "jpegFile" now contains your image encoded into a URL://Base64 format. Which looks something like this:
// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z"
You can put that variable as an image source in HTML code and it will display your image in the browser, or you can upload the Base64 encoded string to the server.
Edit: How to convert the file to a blob (binary file) and upload it to the server
// This function is used to convert base64 encoding to mime type (blob)
function base64ToBlob(base64, mime)
{
mime = mime || '';
var sliceSize = 1024;
var byteChars = window.atob(base64);
var byteArrays = [];
for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
var slice = byteChars.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
return new Blob(byteArrays, {type: mime});
}
Now clean the base64 up and then pass it into the function above:
var jpegFile64 = jpegFile.replace(/^data:image\/(png|jpeg);base64,/, "");
var jpegBlob = base64ToBlob(jpegFile64, 'image/jpeg');
Now send the "jpegBlob" with ajax
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.onload = function (oEvent) {
// Uploaded.
};
oReq.send(jpegBlob);
You can't manipulate hard drive directly from the browser. What you can do though is create a link that can be downloaded.
To do this change your var newfile = new File([theBlob], "c:files/myfile.jpg"); into:
const a = document.createElement('a');
a.setAttribute('download', "some image name");
a.setAttribute('href', theBlob);
a.click();

can html canvas draw uploaded images?

I am trying to create an uploading image resizing function using javascript. However, using filereader to convert upload files into base64, gives no image on canvas. Rather, if I use an external image, and convert that into base64, the function works like a charm. How would that be? What is the problem?
Here is my code, it's pretty long.
//When changes are made to our input field
$ ('#input-file').change (function (evt) {
//The selected file is recovered
var file = evt.target.files [0];
//And processFiles function that will resize and send the file to the server is started
processFiles (file);
});
processFiles = function (file) {
var reader = new FileReader ();
//When the file has been completely read, the function will be executed ResizeImage
reader.onloadend = function (evt) {
//Reader.result represents our base64 encoded file
ResizeImage (reader.result, file);
};
//Allows you to play the file
reader.readAsDataURL (file);
};
ResizeImage = function (data, file) {
var fileType = file.type,
maxWidth = 960
maxHeight = 960;
//The file is loaded in a <img>
var image = new Image ();
image.src = data;
//Once the image is loaded, the following operations are performed
image.onload = function () {
//The ImageSize function calculates the final file size keeping the proportions
var size = ImageSize (image.width, image.height, maxWidth, maxHeight)
ImageWidth = size.width,
imageHeight = size.height,
//We create a canvas element
//canvas = document.createElement ('canvas');
canvas=document.getElementById('hahaha')
canvas.width = ImageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext ("2d");
//DrawImage will allow resizing the image
//This is our image here
var img=document.getElementById('haha')
ctx.drawImage (img, 0, 0, ImageWidth, imageHeight);
//Allows you to export the contents of the canvas element (our resized image) base64
data = canvas.toDataURL(fileType);
alert(data)
//All the elements used for resizing is suppressed
delete image;
delete canvas;
//SubmitFile (data);
}
};
//Function to resize an image keeping the proportions
ImageSize = function (width, height, maxWidth, maxHeight) {
var newWidth = width,
newHeight = height;
if (width> height) {
if (width> maxWidth) {
newHeight = maxWidth / width;
newWidth = maxWidth;
}
else {}
if (height> maxHeight) {
newWidth = maxHeight / height;
newHeight = maxHeight;
}
}
return {width: newWidth, height: newHeight};
};
You may refer this fiddle, http://jsfiddle.net/aliasm2k/tAum2/ for some ideas. It may help you. This is a fiddle I implemented just for fun to generate a thumbnail of a user selected image. It uses FileReader API to select the file and then loads the thumbnail on a canvas.
Personally I'd preffer classic JS than using jQuery and lot of event handlers are used
oFileIn.addEventListener()
oFileReader.addEventListener()
oImage.addEventListener()

Categories