Generate pdf from HTML in div using Javascript
jsPDF is able to use plugins. In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:
- Go to https://github.com/MrRio/jsPDF and download the latest Version.
- Include the following Scripts in your project:
- jspdf.js
- jspdf.plugin.from_html.js
- jspdf.plugin.split_text_to_size.js
- jspdf.plugin.standard_fonts_metrics.js
If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this:
<!DOCTYPE html>
<html>
<body>
<p id="ignorePDF">don't print this to pdf</p>
<div>
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>
Then you use the following JavaScript code to open the created PDF in a PopUp:
var doc = new jsPDF();
var elementHandler = {
'#ignorePDF': function (element, renderer) {
return true;
}
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
source,
15,
15,
{
'width': 180,'elementHandlers': elementHandler
});
doc.output("dataurlnewwindow");
For me this created a nice and tidy PDF that only included the line 'print this to pdf'.
Please note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue. It states:
Because the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported.
Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like:
var elementHandler = {
'#ignoreElement': function (element, renderer) {
return true;
},
'#anotherIdToBeIgnored': function (element, renderer) {
return true;
}
};
From the examples it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit to unrestrictive for the most usecases though:
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.
One very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3 etc., which was enough for my purposes. Additionally it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example:
<body>
<ul>
<!-- This is printed as the element contains a textnode -->
<li>Print me!</li>
</ul>
<div>
<!-- This is not printed because jsPDF doesn't deal with the value attribute -->
<input type="textarea" value="Please print me, too!">
</div>
</body>
Download a div in a HTML page as pdf using javascript
You can do it using jsPDF
HTML:
<div id="content">
<h3>Hello, this is a H3 tag</h3>
<p>A paragraph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>
JavaScript:
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');
});
JavaScript Export Div to PDF
You can't set param jsPDF() fucntion as data object. a4 is default format. No need to set. You can visit this link to refer more: https://micropyramid.com/blog/export-html-web-page-to-pdf-using-jspdf/
<script language="javascript">
var cache_width = $('#renderPDF').width(); //Criado um cache do CSS
var a4 = [595.28, 841.89]; // Widht e Height de uma folha a4
$(document).on("click", '#btnPrint', function () {
// Setar o width da div no formato a4
$("#renderPDF").width((a4[0] * 1.33333) - 80).css('max-width', 'none');
// Aqui ele cria a imagem e cria o pdf
html2canvas($('#renderPDF'), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/jpeg", 1.0);
//var doc = new jsPDF({ unit: 'px', format: 'a4' });//this line error
var doc = new jsPDF('landscape'); // default is portrait
doc.addImage(img, 'JPEG', 20, 20);
doc.save('NOME-DO-PDF.pdf');
//Retorna ao CSS normal
$('#renderPDF').width(cache_width);
}
});
});
</script>
Generating PDF from a HTML page
Just combine both previous answers, the page button to invoke "save as PDF" OR other user choice of printout, will not show in the print media as shown here.
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Fetch using MySQL and Node.js</title>
<style>
@media print {
#button {
display: none;
}
}
table {
border-collapse: collapse;
width: 50%;
align-self: center;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even) {background-color: #f2f2f2;}
th {
background-color: #04AA6D;
color: white;
}
</style>
</head>
<body>
<div class="table-data" id="makepdf">
<h2>Display Data using Node.js & MySQL</h2>
<button id="button" onclick="window.print();">Generate PDF</button>
<table>
<tr>
<th>Date</th>
<th>Description</th>
<th>Debit</th>
<th>Credit</th>
</tr>
<%
if(userData.length!=0){
var i=1;
userData.forEach(function(data){
%>
<tr>
<td><%=data.date %></td>
<td><%=data.description %></td>
<td><%=data.debit %></td>
<td><%=data.credit %></td>
</tr>
<% i++; }) %>
<% } else{ %>
<tr>
<td colspan="7">No Data Found</td>
</tr>
<% } %>
</table>
</div>
</body>
</html>
Export div to pdf in js
jspdf is the right library to begin with. What you can do is to manipulate your data before you put it inside the pdf. I think your best choose is to replace the inputs with or or what ever element you want. Then you can build your pdf. My choose is to put it inside wrapper
$('#pdf').click(function () { $('#PDFWrapper').find('input').each(function(){ $(this).hide(); $(this).after('<span>' + $(this).val() + '</span>'); }); $('#PDFWrapper').find('button').hide(); var doc = new jsPDF(); doc.fromHTML($('#PDFWrapper').html(), 10, 10, { 'elementHandlers': {} }); doc.save('download.pdf'); $('#PDFWrapper').find('input').each(function(){ $(this).show(); $(this).next().remove(); }); $('#PDFWrapper').find('button').show();});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script><div id="PDFWrapper"> <div id="element1"> Enter your name: <input><br> Enter your class: <input> </div>
<button>Click on the button</button>
<div id="element2"> <table> <tr> <td>Name</td> <td>Class</td> </tr> <tr> <td><input></td> <td><input></td> </tr> </table> </div></div>
<button id="pdf">Create pdf</button>
Related Topics
Onclick Button Get from Database and Display on a Input Field Live
Localstorage Values Get Reset After Refreshing Page and Inserting New Values
How to Set a Value to a File Input in HTML
Using JavaScript to Detect Whether the Url Exists Before Display in Iframe
Check If Second String Is Rotation of Another String
Regular Expression to Get a String Between Two Strings in JavaScript
Convert Date/Time in Gmt to Est in JavaScript
How to Specify Multiple Conditions in an If Statement in JavaScript
Is There Any Memory Limit for Google Chrome Browser
How to Automatic Click a Button on a Webpage
Automatically Force Mobile Browser to Desktop View
Creating a Json Dynamically With Each Input Value Using Jquery
Prevent a White Space in the Beginning of a Input
How Get Total Sum from Input Box Values Using JavaScript
Instead of Downloading, Files Are Opening in Browser
Javascript: Location.Href to Open in New Window/Tab
Show Base64 Pdf Data Using Window.Open on Chrome New Version