Getting Image height and width from base64 Image string in GoJS - javascript

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;

Related

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

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.

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");
});

JSPDF - How to export multiple images with various page size (height & width) to a single pdf file

I have multiple images of different size(height & width) that need to be converted to PDF using jspdf, but I have trouble to use addPage() function to do that.
Is it possible to export images with different page sizes to a single pdf?
I was actually able to add multiple pages with different image sizes using addPage([imgWidth, imgHeight]) except the first page, which is defined by new jsPDF('l', 'pt', 'a4').
The blank first page can be deleted using .deletePage(1). You can also add some text to the first page if you will.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"
integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
crossorigin="anonymous"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
function exportPdf(urls) {
let pdf = new jsPDF('l', 'pt', 'a4');
pdf.text(20, 20, 'Some text here');
for (let i = 0; i < urls.length; i++) {
let img = new Image();
img.src = urls[i];
img.onload = function () {
const imgWidth = this.width;
const imgHeight = this.height;
const imgRatio = imgWidth / imgHeight;
if (i >= 0) {
if (imgRatio > 0) {
pdf.addPage([imgWidth, imgHeight]);
}
else {
pdf.addPage([imgWidth, imgHeight], 'p');
}
}
pdf.setPage(i + 2);
pdf.addImage(img, 'JPEG', 0, 0, imgWidth, imgHeight, null, 'NONE');
if (i == urls.length - 1) {
pdf.save('Photos.pdf');
}
}
}
}
</script>
A better, but more complicated, way is to use fixed page format and calculate the image size and aspect ratio and then set the parameters (and rotate the image if needed) accordingly so that the image can fit the paper, i.e., a4 in this case. It can be either pdf.addImage(img, 'JPEG', adjustedX, adjustedY, adjustedWidth, adjustedHeight, null, 'NONE'); or pdf.addImage(img, 'JPEG', adjustedX, adjustedY, adjustedWidth, adjustedHeight, null, -90);
For a code sample, see my answer to this question.

jspdf convert html to pdf with multiple pages

I'm using jsPdf and html2pdf to convert html to a pdf file.
I can convert the html fine and download the file but if the html is too big to fit onto a single page, it does not create the other page(s), how do I do this?
code is:
var pdf = new jsPDF('l', 'pt', 'a4');
pdf.canvas.height = 72 * 11;
pdf.canvas.width = 72 * 8.5;
html2pdf(document.getElementById(id), pdf, function(pdf){
pdf.save('file.pdf');
});
Another Solution.
var pdf = new jsPDF('p', 'pt', 'a4');
var options = {
pagesplit: true
};
pdf.addHTML($(".pdf-wrapper"), options, function()
{
pdf.save("test.pdf");
});
Source : jsPDF multi page PDF with HTML renderrer
another answer : jsPDF multi page PDF with HTML renderrer
If above answer does not work i have done it like this :
download and include in order :
Jquery
html2canvas
jspdf
google them they are easy to find. then have your printable code in a div wrapper report. and call the function with print button.
for example (In jsfiddle code will not work because it does not allow external code from non cdn sites but it will work on server)
$(document).ready(function() {
var form = $('#report');
var cache_width = form.width();
var a4 = [595.28, 841.89];
$('#create_pdf').on('click', function() {
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF() {
getCanvas().then(function(canvas) {
var imgWidth = 200;
var pageHeight = 290;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
var img = canvas.toDataURL("image/jpeg");
doc.addImage(img, 'JPEG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(img, 'JPEG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save('Report.pdf');
form.width(cache_width);
});
}
// create canvas object
function getCanvas() {
form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
return html2canvas(form, {
imageTimeout: 2000,
removeContainer: false
});
}
});
https://jsfiddle.net/vnfts73o/1

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