I am using JsPDF and want to create pdf from content inside a Section tag.
i have tryed alot of guides but noone seam to work, and due to lack of demo code, i see no other alternative than try my luck here.
After implemented code, i manage to generate pdf but its all white, and i would like to get the "save" options after generate to.
My code:
<section id="content" class="printable">
my data
</section>
Pdf
<script>
function demoFromHTML() {
var doc = new jsPDF('p', 'in', 'letter');
var source = $('.printable').first();
var specialElementHandlers = {
'#bypassme': function(element, renderer) {
return true;
}
};
doc.fromHTML(
$('.printable').get(0), // [Refer Exact code tutorial][2]HTML string or DOM elem ref.
0.5, // x coord
0.5, // y coord
{
'width': 7.5, // max width of content on PDF
'elementHandlers': specialElementHandlers
});
doc.output('dataurl');
}
</script>
included script:
<script src="//mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script>
Try this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js">
</script>
<script>
var lMargin = 15; //left margin in mm
var rMargin = 15; //right margin in mm
var pdfInMM = 210; // width of A4 in mm
function getPDF() {
var doc = new jsPDF("p", "mm", "a4");
var tavern = document.querySelector(".printable").innerText;
var lines = doc.splitTextToSize(tavern, pdfInMM - lMargin - rMargin);
doc.text(lMargin, 20, lines);
doc.save("Generated.pdf");
}
</script>
And your markup:
Run Code
<section id="content" class="printable">
my data
</section>
Related
I can't get the problem fixed that my image is always cut off in the PDF file. The PDF size seems to be correct but I can't see my entire page as an image.
I have been trying for hours but without success.
Code:
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
function addWaterMark(pdf) {
var totalPages = pdf.internal.getNumberOfPages();
for (i = 1; i <= totalPages; i++) {
pdf.setPage(i);
pdf.addImage("data:image/png;base64,......", "JPEG", 20, 40, 130, 30);
}
return pdf;
}
function getPDF(){
var HTML_Width = $("div#mycontent").width();
var HTML_Height = $("div#mycontent").height();
var top_left_margin = 100;
var PDF_Width = HTML_Width+(top_left_margin*2);
var PDF_Height = $("div#mycontent").height();
var canvas_image_width = HTML_Width;
var canvas_image_height = HTML_Height/1.1;
var totalPDFPages = Math.ceil(HTML_Height/PDF_Height)-1;
html2canvas($("div#mycontent")[0],{allowTaint:true},{pagesplit: false},{scrollY: -window.scrollY}).then(function(canvas) {
canvas.getContext('2d');
console.log(canvas.height+" "+canvas.width);
var imgData = canvas.toDataURL("image/jpeg", 0.99);
var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
pdf.addImage(imgData, 'JPEG', top_left_margin, top_left_margin,canvas_image_width,canvas_image_height);
pdf = addWaterMark(pdf);
pdf.save("test.pdf");
});
};
</script>
Now:
Image Now
What i want:
Image what i want
In Developer Tool the Content Height is: 20887
Any Solution for this?
You could try changing to portrait or landscape according to width-height of the image. I was getting some cut images and it got fixed this way.
If width > height use landscape "l", if height > width use portrit "p":
html2canvas(document.getElementById(id_div)).then(canvas => {
var w = document.getElementById(id_div).offsetWidth;
var h = document.getElementById(id_div).offsetHeight;
var img = canvas.toDataURL("image/jpeg", 1);
if(w > h){
var doc = new jsPDF('l', 'mm', [w+100, h+50]);
}
else{
var doc = new jsPDF('p', 'mm', [h+100, w+50]);
}
doc.addImage(img, 'JPEG', 10, 10);
doc.save('chart.pdf');
}).catch(function(e) {
console.log(e.message);
});
I am using jspdf to capture the content of Hichchart which generating dynamically with dynamic id onclick. Here when I click submit1 button different highchart will generate with dynamic id.Again when I click download button it will download the dynamically created chart content in pdf.I can able to download but same chart is downloading again instead different chart on the page. I have updated the code to demo here
http://plnkr.co/edit/Z3hJcC8pgzZxXPLWpfBw?p=preview ,Can anyone please help me, I am just putting the html and javascript code here.
html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="jspdf.debug.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://github.com/devongovett/pdfkit/releases/download/v0.6.2/pdfkit.js"></script>
<script src="rgbcolor.js"></script>
<script src="canvg.js"></script>
<script src="script.js"></script>
<input type="button" id="download" value="download" /> click to console
<div><button id="button1" class="button1">submit1</button></div>
script.js
$(document).ready(function() {
var index = 0;
var id = [];
$('#button1').on('click', function() {
$('body').append($("<div id='chart" + index + "'></div>"));
Highcharts.chart('chart' + index, {
title: {
text: 'Chart-'+index+''
},
series: [{
data: [1, 2, 3]
}]
});
var temp = "chart" + index + "";
console.log(temp);
id.push(temp);
index++;
});
$('#download').on('click', function() {
console.log(id);
var doc = new jsPDF('portrait', 'pt', 'a4', true);
var elementHandler = {
'#ignorePDF': function(element, renderer) {
return true;
}
};
var source = document.getElementById("top-content");
doc.fromHTML(source, 15, 15, {
'width': 560,
'elementHandlers': elementHandler
});
var DOMURL = window.URL || window.webkitURL || window;
var elements = id;
// console.log(xx);
for (let i in elements) {
console.log(elements[i]);
var svg = document.querySelector('svg');
var canvas = document.createElement('canvas');
var canvasIE = document.createElement('canvas');
var context = canvas.getContext('2d');
var data1 = (new XMLSerializer()).serializeToString(svg);
canvg(canvas, data1);
var svgBlob = new Blob([data1], {
type: 'image/svg+xml;charset=utf-8'
});
var url = DOMURL.createObjectURL(svgBlob);
var img = new Image();
img.onload = function() {
context.canvas.width = $("#"+elements[i]).find('svg').width();
context.canvas.height = $("#"+elements[i]).find('svg').height();
context.drawImage(img, 0, 0);
// freeing up the memory as image is drawn to canvas
DOMURL.revokeObjectURL(url);
var dataUrl;
if (isIEBrowser()) { // Check of IE browser
var svg = $(elements[i]).highcharts().container.innerHTML;
canvg(canvasIE, svg);
dataUrl = canvasIE.toDataURL('image/JPEG');
} else {
dataUrl = canvas.toDataURL('image/jpeg');
}
doc.addImage(dataUrl, 'JPEG', 20, 150, 560, 350);
var bottomContent = document.getElementById("bottom-content");
doc.fromHTML(bottomContent, 15, 700, {
'width': 560,
'elementHandlers': elementHandler
});
doc.fromHTML(source, 15, 15, {
'width': 560,
'elementHandlers': elementHandler
});
doc.addPage();
};
img.src = url;
}
setTimeout(function() {
doc.save('TestChart.pdf');
}, 2000);
});
});
function isIEBrowser() {
var ieBrowser;
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // Internet Explorer
{
ieBrowser = true;
} else //Other browser
{
console.log('Other Browser');
ieBrowser = false;
}
return ieBrowser;
};
I found two problems in your code.
First, you use document.querySelector('svg'); which return only first svg element - you should use document.querySelectorAll('svg'); and then get the right element svg[i].
Second, it looks like that you have problem with asynchronous in your code - helped change all declarations var to let.
Live demo: http://plnkr.co/edit/epHnjnPhWFUdtic97jNA?p=preview
May i ask how to save the whole webpage as PDF file. I already have a script for saving webpage as PDF file but it can't capture the whole webpage. here's the script: My expectation is to save the whole details of webpage
<script>
function wa(){
genPDF(0,0);
}
function genPDF(x,y){
var doc = new jsPDF();
//alert(document.getElementById("paper").clientWidth);//100.26
var paperwidth = 8.5;
var paperheight = 11;
var ppi = parseFloat(document.getElementById("paper").clientWidth)/paperwidth;
var height = ppi.toFixed(2)*paperheight;//instead of 11 inches
var numpages = Math.ceil(parseFloat(document.getElementById("paper").clientHeight)/height.toFixed(2));
window.scrollTo(0,0);
html2canvas(document.getElementById("paper"),{
onrendered:function (canvas){
var x=0;
while (x<numpages)
{
var y = x*height;
window.scrollTo(0,y);
var img = canvas.toDataURL("image/png");
doc.addImage(img,'JPEG',5,5);
doc.addPage();
x=x+1;
}
doc.save('test.pdf');
}
});`enter code here`
}
</script>
Thank you
try to this man
var pdf = new jsPDF('l', 'mm', [canvas.width, canvas.height]);
var width = pdf.internal.pageSize.width;
var height = pdf.internal.pageSize.height;
pdf.addImage(imgData, 'JPEG', 0, 0, width, height);
pdf.save("download.pdf");
I am currently working on a school management software that usually requires exporting of html contents that contains data tables and div tag.
I have tried all possible means to write a code that will be able to export my html data in a good way, with css preferably. After checking some question and answers here, I tried using spdf, but no luck.
It keeps destroying my table alignment, then I read about html2canvas but to implement it with jspdf was my problem, i would like to capture the content if a div tag with html2canvas then send the canvas to jspdf to export the canvas as pdf.
Here is my code below:
<script src="assets/js/pdfconvert/jspdf.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.from_html.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.split_text_to_size.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.standard_fonts_metrics.js"> </script>
<script src="assets/js/pdfconvert/jspdf.plugin.addhtml.js"></script>
<script src="assets/js/pdfconvert/filesaver.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.cell.js"></script>
<script src="assets/js/pdfconvert/html2canvas.js"></script>
<script src="assets/js/pdfconvert/jspdf.plugin.addimage.js"></script>
here is the js code
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.addHTML($('#ElementYouWantToConvertToPdf')[0], function () {
pdf.save('Test.pdf');
});
I have made a jsfiddle for you.
<canvas id="canvas" width="480" height="320"></canvas>
<button id="download">Download Pdf</button>
'
html2canvas($("#canvas"), {
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');
}
});
jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/
Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.
This one shows how to print only selected element on the page with dpi/resolution adjustments
HTML:
<html>
<body>
<header>This is the header</header>
<div id="content">
This is the element you only want to capture
</div>
<button id="print">Download Pdf</button>
<footer>This is the footer</footer>
</body>
</html>
CSS:
body {
background: beige;
}
header {
background: red;
}
footer {
background: blue;
}
#content {
background: yellow;
width: 70%;
height: 100px;
margin: 50px auto;
border: 1px solid orange;
padding: 20px;
}
JS:
$('#print').click(function() {
var w = document.getElementById("content").offsetWidth;
var h = document.getElementById("content").offsetHeight;
html2canvas(document.getElementById("content"), {
dpi: 300, // Set to 300 DPI
scale: 3, // Adjusts your resolution
onrendered: function(canvas) {
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'px', [w, h]);
doc.addImage(img, 'JPEG', 0, 0, w, h);
doc.save('sample-file.pdf');
}
});
});
jsfiddle: https://jsfiddle.net/marksalvania/dum8bfco/
Changing this line:
var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);
To fix the dimensions.
This worked when you add "useCORS: true".
Grabs google map as it is rendered on the screen and puts it in a pdf
function create_pdf() {
return html2canvas($('#map'), {
useCORS: true,
background: "#ffffff",
onrendered: function(canvas) {
var myImage = canvas.toDataURL("image/jpeg,1.0");
// Adjust width and height
var imgWidth = (canvas.width * 60) / 240;
var imgHeight = (canvas.height * 70) / 240;
// jspdf changes
var pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(myImage, 'png', 15, 2, imgWidth, imgHeight); // 2: 19
pdf.save(`Budgeting ${$('.pdf-title').text()}.pdf`);
}
});
I have created an appliction for downloading a html table to pdf using javascript i used jsPDF plugin. The application is working fine but the problem is that the table is not proper. The width of the table as well as the header is not properly alligned. I am using angularjs for creating the table.
Can anyone please give me some suggestion for this problem
JSFiddle
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
source = $('#customers')[0];
specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true
}
};
margins = {
top: 4,
bottom: 4,
left: 4,
width: 522
};
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) {
pdf.save('Test.pdf');
}, margins);
}
I guess you currently have to do that manually (fiddle):
function demoFromHTML() {
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.cellInitialize();
pdf.setFontSize(10);
$.each( $('#customers tr'), function (i, row){
$.each( $(row).find("td, th"), function(j, cell){
var txt = $(cell).text().trim() || " ";
var width = (j==4) ? 40 : 70; //make 4th column smaller
pdf.cell(10, 50, width, 30, txt, i);
});
});
pdf.save('sample-file.pdf');
}
try "jspdf" instead of "jsPDF"