How to make a HTML page as Downloadable PDF - javascript

I want to make Something like this:
There will be a form and after filling the form and press submit it will go to the preview of the Page with all filled Info. I know how to do all those including the print Button using JS. But I wanted to add a Download button on that page which will download that page As PDF. Is it possible ? If anybody can help me that will be very helpful.
Thanks in advance.

I've been looking at doing this with one of my sites and found this code helpful.
https://codepen.io/AshikNesin/pen/KzgeYX
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});

Well, I think it is very "simple".
You can use some libraries or classes like this:
https://parall.ax/products/jspdf
Example:
Extract div from you current webpage:
// pick you DOM element and extract HTML as String
const html = document.querySelector("#element").innerHTML;
const pdf = new jsPDF('p', 'en', 'letter');
const handlers = {audio: () => false};
const config = {top: 80, bottom: 60, left: 40, width: 522};
pdf.fromHTML(
html,
config.left,
config.top,
{config.width, handlers},
(dispose) => pdf.save('example.pdf'),
config
);

Related

How to add a Custom Font to Dynamic data in PDF document by using jsPDF?

I've tried to convert dynamic webpage to PDF by using jsPDF it worked for me and now I wants to change the font family of PDF by using jsPDF. Is there any option. Please let me know. Thanks!
Below my code
<div id="#preview-details">dynamic data goes here..</div>
<button id="downloadPDF">Print</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script>
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#downloadPDF').click(function () {
doc.fromHTML($('#preview-details').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('pdfdoc.pdf');
});
</script>
As I know you have to download the font as a ttf format, then you need to add it into your code like the following code:
 // add custom font to file
doc.addFont("ConsolasHex.ttf", "ConsolasHex", "Bold");
doc.setFont("ConsolasHex","Bold");
doc.setFontSize(12);
The page in this URL has explain it enter link description here

Html to pdf Jspdf

When I'm converting my html div to pdf using Jspdf library the generated pdf
is not showing the whole content of mydiv.It only shows little html but not complete div. What I am missing in this ?
<button id="b2">Export to pdf</button>
<script>
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#b2').click(function () {
doc.fromHTML($('#mydiv').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
</script>
Things you can do:
Check if your IDs are correct: #editor for the specialElementHandlers and #mydiv in the click function?
Check the Javascript console for errors
Check examples like this or questions like this to find any errors

How to make jsPDF convert big text?

I'm using jsPDF to convert html to pdf. When a page has a lot of text I just got a blank pdf or a gray page with no contentsanf data: in url
I have no errors in console.
How can I make it print pdf correctly?
To convert to pdf I use this code:
$(document).ready(function(){
var specialElementHandlers = {
'#editor': function (element,renderer) {
return true;
}
};
$('#topdf').click(function () {
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function(element, renderer){
return true;
}
};
doc.fromHTML($('.post-content p').get(0), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.output("dataurlnewwindow");
});
});
The problem is in length of URL limit 2000 chars (more here: What is the maximum length of a URL in different browsers?), so I suggest you to use doc.output('save', 'filename.pdf') but this have limitation (more: How to open generated pdf using jspdf in new window)

Adding PDF pages depending on element in jsPDF

I have a need to create a pdf straight from the source of my html page, which is does successfully, but now I need to get the formatting right. What I want, is to be able to add a new page every time a <p class="form-control-static"></p> pops up in the source.
I have checked the documentation and some other stack overflow answers but these are all for adding pages when the content is static and you can create it yourself. My content is changing all the time.
I am using jsPDF to achieve all of this. I am aware of the pdf.addPage() command yet I am not sure how to add pages depending on a condition. My current code as follows:
$('#downloadPDF').click(function () {
$('#report').width(522);
$('.img-thumbnail').width(522).height(348);
var pdf = new jsPDF('p', 'pt', 'letter')
, source = $('#report')[0]
, specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true
}
}
margins = {
top: 20,
bottom: 20,
left: 40,
width: 550
};
pdf.fromHTML(
source
, margins.left
, margins.top
, {
'width': margins.width
, 'elementHandlers': specialElementHandlers
},
function (dispose) {
pdf.save('Job Report - ' + #ViewData["jobid"] + '.pdf');
},
margins
)
});
Obviously it has something to do with the source variable containing the html or am I mistaken?

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