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"
Related
how can I fix this header and data not to stick together? I am using jsPDF
generatePdf(){
var doc = new jsPDF('p', 'pt', 'A4');
margins = {
top: 80,
bottom: 80,
left: 40,
width: 542
};
doc.fromHTML(this.$refs.testHtml, margins.left, margins.top,{
'width' : margins.width
});
doc.save('test.pdf');
}
Source code
I am generating a pdf from some HTML and on button click triggering my download function which creates a pdf. It opens fine in chrome but gives an error [110] when opened by Acrobat. Anyone knows what causes the error?
function pdfd() {
document.getElementById("bbasbb").style.display = "none";
document.getElementById("pdfaspdf").style.display = "none";
document.getElementById("bannerg").style.display = "block";
html2canvas(document.querySelector("#asm")).then(canvas => {
var imgData = canvas.toDataURL('image/png');
document.getElementById("pdfgi").src = imgData;
var pdf = new jsPDF('p', 'pt', 'a2');
var source = "<br><Br>" + document.getElementById("pdfg").innerHTML;
specialElementHandlers = {
'#elementH': function(element, renderer) {
return true
}
};
margins = {
top: 50,
bottom: 60,
left: 100,
width: 522
};
pdf.fromHTML(source, margins.left, margins.top, {
'width': margins.width,
'elementHandlers': specialElementHandlers
},
function(dispose) {
pdf.save("<?php echo date('Y-m-d'); ?>");
document.getElementById("bbasbb").style.display = "block";
document.getElementById("pdfaspdf").style.display = "block";
document.getElementById("bannerg").style.display = "none";
document.getElementById("pdfgi").src = "";
}, margins);
});
}
I'm using jsPDF and svg_to_pdf to export both an SVG and a table to a PDF. This is my code:
function svg_to_pdf(svg, callback) {
console.log("svgtopdf.js");
svgAsDataUri(svg, {}, function(svg_uri) {
var image = document.createElement('img');
image.src = svg_uri;
image.onload = function() {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var doc = new jsPDF('portrait', 'pt', 'a4', true);
var dataUrl;
source = $('#datos_alumnos')[0];
specialElementHandlers = {
'#bypassme' : function(element, renderer){
return true;
}
};
margins = {
top: 40,
bottom: 60,
left: 40,
width: 270
};
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);
dataUrl = canvas.toDataURL('image/jpeg');
doc.addImage(dataUrl, 'JPEG', 0, 0, 500, 263);
doc.fromHTML(
source,
40,
270, {
'width': 550,
'elementHandlers': specialElementHandlers
},
function(dispose){
//doc.save('SVG.pdf');
}
, margins);
callback(doc);
}
});
}
The result is a PDF with the image at the top and the table next. The problem comes when it enters the second page as the headers of the table overlap with the first row and it looks like this.
http://i.imgur.com/vlfm4Fv.png
Is it possible to remove the headers on the second page?
Ok so I've found a possible solution for this, if you are using this script for jsPDF
https://raw.githubusercontent.com/MrRio/jsPDF/master/dist/jspdf.debug.js
you can download it, and modify line 5201 to have a negative value, for example;
this.margins.top = -50;
With this there is no header on the second page of the PDF.
I've tried playing around with the code without much success, if I find a better way I will update this answer (don't know if I'm allowed to do that).
When you draw table, just use:
startY: doc.internal.getNumberOfPages() > 1 ? doc.autoTableEndPosY() + 20 : 200,
Try adding css classes like -
thead {
display: table-header-group
}
tfoot {
display: table-row-group
}
tr {
page-break-inside: avoid
}
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>
I am using jspdf.debug.js to export pdf data from html page.Here is the function of controller that I am using. I made a string as html table that I want to export.
$scope.exportReport = function (fileName, fileType) {
objReport.count = 0; // for getting all records
ReportService.getSaleDetail(objReport).then(function (result) {
var strTable = "<table id='tableReport'><tr><td style='width:400px'>Date</td><td style='width:50px'>Order Id</td><td style='width:130px'>Product</td><td style='width:120px'>Gorss Price</td><td style='width:160px'>Currency</td><td style='width:50px'>Order Status</td><td style='width:150px'>Assigned To</td><td style='width:150px'>Assigned User Email</td><td style='width:150px'>Country</td></tr>";
var strRow = '';
if (result.data.totalRecords > 0) {
var totalRecords = parseInt(result.data.totalRecords);
var saleDataJson = result.data.saleDetail;
for (var i = 0; i < totalRecords; i++) {
strRow = '<tr><td>' + saleDataJson[i].date + '</td>' + '<td>' + saleDataJson[i].orderId + '</td>' + '<td>' + saleDataJson[i].product + '</td>' + '<td>' + (1 * saleDataJson[i].grossPrice).toFixed(2) + '</td>' + '<td>' + saleDataJson[i].currency + '</td>' + '<td>' + saleDataJson[i].orderStatus + '</td>' + '<td>' + saleDataJson[i].assignedTo + '</td><td>' + saleDataJson[i].assignedUserEmail + '</td><td>' + saleDataJson[i].country + '</td></tr>';
strTable += strRow;
}
strTable += "</table>";
}
if (fileType === 'pdf') {
var pdf = new jsPDF('p', 'pt', 'letter') // jsPDF(orientation, unit, format)
, source = strTable
, specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme': function (element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true;
}
},
margins = {
top: 30,
bottom: 40,
left: 35,
width: 600
};
pdf.setFontSize(12);
pdf.text(200, 30, fileName);
pdf.setFontSize(8);
pdf.setFontStyle('italic');
pdf.text(420, 35, 'Total Records : ' + totalRecords);
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(fileName + '.pdf');
},
margins
)
}
});
};
and this method is exporting pdf file like this
I tried style with tang but it is not working
How can lower the font size so that i can export pdf file properly ?
pdf.setFont("helvetica");
pdf.setFontType("bold");
pdf.setFontSize(9);
it seems that pdf.fromHTML on tables ignores styling, or even jsPdf settings, such as pdf.setFont("helvetica"); etc.
so you can make changes to the original jspdf.debug.js file:
a) default autoSize is false, so you may change it.
b) default fontSize is 12 - you should senthe d smaller value (add your value to the last argument).
/*** TABLE RENDERING ***/
} else if (cn.nodeName === "TABLE") {
table2json = tableToJson(cn, renderer);
renderer.y += 10;
renderer.pdf.table(renderer.x, renderer.y, table2json.rows, table2json.headers, {
autoSize : true,
printHeaders : true,
margins : renderer.pdf.margins_doc,
fontSize : 9
});
}
I give you an example that works for me:
function imprimirPdf() {
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.setFont("arial", "bold");
pdf.setFontSize(14);
pdf.text(20, 20, 'Consulta');
$("#idTablaDatos").css("font-size", "10px");// change property value
$("#idTablaDetalle").css("font-size", "10px");// change property value
source = $('#div_pdf').html();//div_pdf contains idTablaDatos and idTablaDetalle
$("#idTablaDatos").css("font-size","14px");// original value
$("#idTablaDetalle").css("font-size","14px");// original value
specialElementHandlers = {
'#bypassme': function (element, renderer) {
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);
}
This works for me:
table.style.fontSize = '5px';
Try AutoTable - Table plugin for jsPDF
<a class="pull-right btn btn-warning btn-large" href="#" onclick="generate();"><i class="fa fa-file-excel-o"></i> PDF Data</a>
<table class="table table-bordered table-striped" id="basic-table">
<script src='https://cdn.rawgit.com/simonbengtsson/jsPDF/requirejs-fix-dist/dist/jspdf.debug.js'></script>
<script src='https://unpkg.com/jspdf-autotable#2.3.2'></script>
<script src="<?php echo base_url();?>assets/bower_components/jspdf/dist/index.js"></script>
<script>
function generate() {
var doc = new jsPDF('l', 'pt', 'a4');
doc.setFontSize(12);
var res = doc.autoTableHtmlToJson(document.getElementById("basic-table"));
doc.autoTable(res.columns, res.data, {margin: {top: 80}});
var header = function(data) {
doc.setFontSize(18);
doc.setTextColor(40);
doc.setFontStyle('normal');
//doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50);
doc.text("Country List", data.settings.margin.left, 50);
};
var options = {
beforePageContent: header,
margin: {
top: 80
},
startY: doc.autoTableEndPosY() + 20
};
doc.autoTable(res.columns, res.data, options);
doc.save("Test.pdf");
}
</script>
Simple and direct:
var doc = new jspdf.jsPDF();
doc.autoTable({ html: '#tabelaDadosExtrato' });
doc.save('extrato-cliente-bet.pdf');
Based on example in https://github.com/simonbengtsson/jsPDF-AutoTable