Trying to add image to pdf using jsPDF - javascript

Trying this code
pdfGenerate.js
generatePDF = function() {
var imgData = 'D:/work/TiffImages/png/895153.0000.png';
var doc = new jsPDF('p', 'pt', 'a4');
doc.text(20, 20, 'CTS Aarchival');
doc.addImage(imgData, 'PNG', 15, 40, 180, 180);
doc.save('CTStest.pdf'); }
Error:
Uncaught TypeError: doc.addImage is not a function
In HTML I am just calling this method onclick()
And all required js files are included.

addImage function is in another module called *drumroll please* addImage. So if you're importing the jsPdf.js it doens't contain that module.
Here is the doc link. Also check out these github issues here and here

Simple solution:
Instead of using jsPDF.js library use jsPDF.debug.js , it includes all the modules which we need.

You can also do it in this way:
var pdf = new jsPDF();
var img = new Image;
img.onload = function() {
pdf.addImage(this, 10, 10);
pdf.save("CTStest.pdf");
};
img.crossOrigin = "";
img.src = 'D:/work/TiffImages/png/895153.0000.png';

Related

Not able to add image to PDF using jspdf in IE11

I am using jsPDF to generate PDF file using JavaScript. In my PDF file I am adding images. I am able to generate PDF in Chrome and Firefox, but adding image to PDF creates security error in IE11.
JS Code:
(function() {
var doc = new jsPDF();
doc.setFont("courier");
doc.setFontType("bolditalic");
doc.setFontSize(20);
doc.text(105, 15, 'IE 11 PDF Image Insert Test', null, null, 'center');
var img = new Image();
img.onload = function() {
console.log('img onload');
doc.addImage(img, 'png', 24, 63, 80, 80);
doc.save('ie11_test.pdf');
};
img.src = 'https://developers.google.com/maps/solutions/images/storelocator_clothing.png';
img.crossOrigin = "anonymous";
})();
How fix this image insert issue with IE11?

pass html content as a variable to html2canvas for pdf generation

var doc = document.getElementById('name').innerHTML;
html2canvas(doc, {
useCORS: true,
allowTaint: true,
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
}
});
I am getting the following error
jspdf.min.js:143 Uncaught (in promise) Proxy must be used when rendering url
i have tried setting proxy as http://localhost:8080, it didn't work..
any suggestions?
Use
var doc = document.getElementById('name');
Because the first argument needs to be an element, not an HTML string;

FabricJS SVG to canvas (using FileReader)

On my page, I have a button and a canvas with the following attributes -
<button onclick="openSVG()">Open</button>
<canvas></canvas>
On clicking the button, the openSVG() function is supposed to
Let the user select and open an SVG file from their local hard drive (previously created using FabricJS)
Read the contents of the SVG file using FileReader and storing it in a variable
Using that variable to populate the canvas using fabric.loadSVGFromString() method
Now clicking on Open button opens a file selection window but doesnt draw objects into canvas. Here's my openSVG() function -
function openSVG() {
// importing file
var input = $(document.createElement('input'));
input.attr("id", "mySVGFile")
input.attr("type", "file");
input.trigger('click');
//storing file contents in var using FileReader
var myInputFile = document.getElementById('mySVGFile');
var myFile = myInputFile.files[0];
var fr = new FileReader();
fr.onload = function(){
var canvasD = this.result;
//loading data from var to canvas
fabric.loadSVGFromString(canvasD, function(objects, options) {
var obj = fabric.util.groupSVGElements(objects, options);
canvas.add(obj).renderAll();
});
};
fr.readAsText(myFile); }
I'm new to FileReader. There's no errors in console so I can't even tell where I'm going wrong.
Does my approach not work? Is there a better way to achieve what I want.
Here is a much more easier and better approach using URL.createObjectURL() method ...
var canvas = new fabric.Canvas('c');
function openSVG(e) {
var url = URL.createObjectURL(e.target.files[0]);
fabric.loadSVGFromURL(url, function(objects, options) {
objects.forEach(function(svg) {
svg.set({
top: 90,
left: 90,
originX: 'center',
originY: 'center'
});
svg.scaleToWidth(50);
svg.scaleToHeight(50);
canvas.add(svg).renderAll();
});
});
}
canvas{margin-top:5px;border:1px solid #ccc}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<input type="file" onchange="openSVG(event)">
<canvas id="c" width="180" height="180"></canvas>

where should i put controller code in a angularjs application

I have just started learning angularjs and nodejs.
I am trying to build an app using fabric.js to upload pictures and edit it. I have seen a link here, the second answer is really helpful.
However when I tried to implement it in my own application I have faced problem. I use the angular tutorial for the application. In my own application I know I should put the last part of the code from the question linked in index.html, and put the middle part of the code in style.css. However, I don't know where to put the first part of the code, from my previous experience in extJS I know it should be a controller.
I tried to create a new file called controller.js under the same directory of index.html, paste the code there and include the controller into the index.html in the script tag, but it didn't work.
Here is the js code I am trying to implement
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
You don't need the filereader, just have to call createObjectURL
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var url = URL.createObjectURL(file);
fabric.Image.fromURL(url, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
});
});
I find where I do wrong. There is nothing wrong with these backend code, it is in index.html, where I script the controller in the wrong place that caused the trouble. I have already solved that.

How to properly use jsPDF library

I want to convert some of my divs into PDF and I've tried jsPDF library but with no success. It seems I can't understand what I need to import to make the library work. I've been through the examples and I still can't figure it out. I've tried the following:
<script type="text/javascript" src="js/jspdf.min.js"></script>
After jQuery and:
$("#html2pdf").on('click', function(){
var doc = new jsPDF();
doc.fromHTML($('body').get(0), 15, 15, {
'width': 170
});
console.log(doc);
});
for testing purposes but I receive:
"Cannot read property '#smdadminbar' of undefined"
where #smdadminbar is the first div from the body.
you can use pdf from html as follows,
Step 1: Add the following script to the header
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
or download locally
Step 2: Add HTML script to execute jsPDF code
Customize this to pass the identifier or just change #content to be the identifier you need.
<script>
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#content')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme': function (element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function (dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('Test.pdf');
}, margins
);
}
</script>
Step 3: Add your body content
Run Code
<div id="content">
<h1>
We support special element handlers. Register them with jQuery-style.
</h1>
</div>
Refer to the original tutorial
See a working fiddle
You only need this link jspdf.min.js
It has everything in it.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
According to the latest version (1.5.3) there is no fromHTML() method anymore.
Instead you should utilize jsPDF HTML plugin, see: https://rawgit.com/MrRio/jsPDF/master/docs/module-html.html#~html
You also need to add html2canvas library in order for it to work properly: https://github.com/niklasvh/html2canvas
JS (from API docs):
var doc = new jsPDF();
doc.html(document.body, {
callback: function (doc) {
doc.save();
}
});
You can provide HTML string instead of reference to the DOM element as well.
This is finally what did it for me (and triggers a disposition):
function onClick() {
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.canvas.height = 72 * 11;
pdf.canvas.width = 72 * 8.5;
pdf.fromHTML(document.body);
pdf.save('test.pdf');
};
var element = document.getElementById("clickbind");
element.addEventListener("click", onClick);
<h1>Dsdas</h1>
<a id="clickbind" href="#">Click</a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
And for those of the KnockoutJS inclination, a little binding:
ko.bindingHandlers.generatePDF = {
init: function(element) {
function onClick() {
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.canvas.height = 72 * 11;
pdf.canvas.width = 72 * 8.5;
pdf.fromHTML(document.body);
pdf.save('test.pdf');
};
element.addEventListener("click", onClick);
}
};
how about in vuejs how is it applicable?
function onClick() {
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.canvas.height = 72 * 11;
pdf.canvas.width = 72 * 8.5;
pdf.fromHTML(document.body);
pdf.save('test.pdf');
};
var element = document.getElementById("clickbind");
element.addEventListener("click", onClick);
<h1>Dsdas</h1>
<a id="clickbind" href="#">Click</a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
Shouldn't you also be using the jspdf.plugin.from_html.js library? Besides the main library (jspdf.js), you must use other libraries for "special operations" (like jspdf.plugin.addimage.js for using images). Check https://github.com/MrRio/jsPDF.
first, you have to create a handler.
var specialElementHandlers = {
'#editor': function(element, renderer){
return true;
}
};
then write this code in click event:
doc.fromHTML($('body').get(0), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
var pdfOutput = doc.output();
console.log(">>>"+pdfOutput );
assuming you've already declared doc variable.
And Then you have save this pdf file using File-Plugin.

Categories

Resources