i want to add content after a table in a pdf file that was created with jsPDF autotable.
My Code:
$('#printBtn').on('click', function() {
var pdf = new jsPDF('p', 'pt', 'a4');
var res = pdf.autoTableHtmlToJson(document.getElementById("tablePrint"));
var anfang = "Anfang";
pdf.text(anfang, 14, 30);
pdf.autoTable(res.columns, res.data, {
theme : 'plain',
styles: {
fontSize: 12
},
showHeader: 'never',
createdCell: function(cell, data) {
var tdElement = cell.raw;
if (tdElement.classList.contains('hrow')) {
cell.styles.fontStyle = 'bold';
}
}
});
var ende = $('#ende_text').text();
pdf.text(ende, 0, 12);
pdf.save("test.pdf");
});
My Problem is that the code isn't formatted. The tags and everything else was ignored by jsPDF.
How can i fix that or what can i do that the text has line breaks and not overflow?
Thanks for help!
margins={
top=50,
left=30,
bottom=50,
width=520
}
var pdf = new jsPDF("p", "pt","a4");
var res = pdf.autoTableHtmlToJson(document.getElementById("table2"));
pdf.autoTable(res.columns, res.data,{
margin: { left: 30,bottom:100},
startY: 30, pageBreak: 'always',
styles: {overflow: 'linebreak', columnWidth: 'wrap', font: 'arial',
cellPadding: 8, overflowColumns: 'linebreak'}
});
pdf.fromHTML($("#editor1").get(0), 30, pdf.autoTableEndPosY() + 20, {
'width': margins.width
},function(dispose)
{
var iframe = document.createElement('iframe');
iframe.setAttribute('style','position:absolute;right:0; top:0; bottom:0; height:100%; width:40%; padding:20px;');
document.body.appendChild(iframe);
iframe.src = pdf.output('datauristring');
//pdf.save('name.pdf');
},
margins);
iam using the latest version of jspdf.min.js and jspdf.autotable.js
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.3.5/jspdf.plugin.autotable.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>
Related
The text of a column in my table is required to render as HTML but the table can't render it, the following code is the way I'm generating the PDF:
var doc = new jsPDF({ format: 'a4', unit: 'px' });
doc.setFontSize(10);
var alignOption: any = { align: 'left' };
if (company) doc.text(`Company: ${company}`, 10, 15, alignOption);
if (division) doc.text(`Division: ${division}`, 10, 30, alignOption);
autoTable(doc, {
styles: { fontSize: 5 },
columnStyles: { 5: { cellWidth: 200 } },
margin: { top: 40, bottom: 40 },
head: [Object.keys(data[0])],
body: formatedData,
foot: [['total', '500']],
});
doc.save('hourlyReport.pdf');
The following image is the result I get:
Is there a way I can render the marked information as HTML?
I have a need to print a large table with 20+ columns. Is there a way to achieve this without distorting the view.
I have tried setting font size based on the number of columns of the table but unable to achieve that:
doc.autoTable({
styles: {
cellPadding: 0.5,
overflow: 'visible',
cellWidth: 'wrap'
},
columnStyles: {
columnWidth: 'auto'
},
margin: {
left: 5,
right: 5
},
tableLineWidth: 0.5,
head: headers as any,
body: body,
didDrawCell: (data) => {
if (this.length > 5) { // Number of columns
doc.autoTable({
styles: {
fontSize: 1
}
});
}
},
didDrawPage: (data) => {
console.log(data);
}
});
Or is there any other better way to achieve that because currently whatever I try my view is distorted if I show all the columns and if I wrap the columnWidth and cellWidth then only contained element within specified width are shown.
For now I am able to do it by calculating fontSize upFront and passing it as a value in styles object
exportAsPDF(data: Array<any>, fileName: string) {
const headers: Array<Array<string>> = this.setPDFHeader(data);
const fontSize: number = this.calculateFontSize(headers[0].length);
const body: Array<Array<string>> = this.setPDFBody(data);
const doc = new jsPDF();
doc.autoTable({
styles: {
cellPadding: 0.5,
fontSize: fontSize
},
headStyles: {
fillColor: '#3f51b5',
textColor: '#fff',
halign: 'center'
},
bodyStyles: {
halign: 'center'
},
margin: {
left: 5,
right: 5
},
tableLineWidth: 1,
head: headers as any,
body: body
});
doc.save(fileName);
}
setPDFHeader(data: Array<any>): Array<Array<string>> {
return [
Object.keys(data[data.length - 1]).map(
(item) => `${item.charAt(0).toUpperCase()}${item.substr(1, item.length)}`
)
];
}
setPDFBody(data: Array<any>): Array<Array<string>> {
return data.map((item) => {
const keys = Object.keys(item);
const values = [];
keys.forEach((key) => {
values.push(item[key]);
});
return values;
});
}
calculateFontSize(count: number): number {
return count ? tableWidth / count : count;
}
I have added this jspdf script on my website to download pdf. However I get this error.
Uncaught TypeError: Cannot read property '1' of undefined
at f.renderParagraph (jspdf.min.js:202)
at f.setBlockBoundary (jspdf.min.js:202)
at k (jspdf.min.js:202)
at k (jspdf.min.js:202)
at k (jspdf.min.js:202)
at jspdf.min.js:202
at l (jspdf.min.js:202)
at Image.i.onerror.i.onload (jspdf.min.js:202)
This happens on certain pages while others work fine.I have added the code I am using below. I am not sure if it is anything to do with my code or the jspdf.
//Code I am using:
<script type="text/javascript">
function HTMLtoPDF(){
var pdf = new jsPDF('p', 'pt', 'letter');
source = $('#HTMLtoPDF')[0];
specialElementHandlers = {
'#bypassme': function(element, renderer){
return true
}
}
margins = {
top: 50,
left: 60,
right:60,
width: 545
};
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('Download.pdf');
}
)
}
</script>
<button type="button" onclick="HTMLtoPDF()" style=" height: 40px; width: 154px; background-color: #008800; color: #ffffff; font-size: 150%;">Download PDF </button>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"> </script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var str_pdf = $("#HTMLtoPDF").html();
var regex = /<br\s*[\/]?>/gi;
$("#HTMLtoPDF").html(str_pdf.replace(regex, '<p data-empty="true"><br></p>'));
});
function HTMLtoPDF(){
var pdf = new jsPDF('p', 'pt', 'a4');
source = $('#HTMLtoPDF')[0];
specialElementHandlers = {
'#bypassme': function (element, renderer) {
return true
}
};
margins = {
top: 30,
bottom: 30,
left: 40,
width: 522
};
pdf.fromHTML(
source,
margins.left,
margins.top, {
'width': margins.width,
'elementHandlers': specialElementHandlers
},
function (dispose) {
pdf.save('Download.pdf');
}, margins);
}
</script>
<!-- these js files are used for making PDF -->
I have followed the steps to some answers on this topic already, but none of them are working. I have the following text which needs to display in a red text:
<table id="heading1">
<tr>
<td class="hrow"><h4>1. DETAILS</h4></td>
</tr>
</table>
Here is the code I have written for the PDF:
<script>
exportGraph = function () {
var pdfsize = 'a4';
var pdf = new jsPDF('l', 'mm', pdfsize);
var totalPagesExp = "{total_pages_count_string}";
var res2 = pdf.autoTableHtmlToJson(document.getElementById("heading1"));
pdf.autoTable(res2.columns, res2.data, {
createdCell: function(cell, data) {
var tdElement = cell.raw;
if (tdElement.classList.contains("hrow")) {
cell.styles.textColor = "[255,72,72]";
}
},
startY: 10,
margin: {left: 5 },
styles: { halign: 'left', fontsize: 12 }
});
pdf.save('Submission-Printout.pdf');
}
</script>
As you can see, what I have done SHOULD in theory work, but the text still appears as not red. Does anyone know why it's not appearing in red text colour?
What about this example ?
function generate() {
var doc = new jsPDF('p', 'pt', 'a4');
var elem = document.getElementById('example');
var data = doc.autoTableHtmlToJson(elem);
doc.autoTable(data.columns, data.rows, {
createdCell: function (cell, data) {
if ($(cell.raw).hasClass("demo1")) {
cell.styles.textColor = [200, 0, 0];
cell.styles.fontStyle = 'bolditalic';
};
if ($(cell.raw).hasClass("demo2")) {
cell.styles.textColor = [0, 0, 205];
cell.styles.fontStyle = 'bold';
};
return false;
}
});
doc.save("table.pdf");
}
I'm not a developer and i'm trying to learn javascript step by step. Now, I need to add a simple infobox in the gmaps that I'm working on. The problem is that, I add the code as explained in the google reference but it doesn't work: in the beginning i was using infowindow wich worked well but wasn't so customized. I also put the infobox.js link in that page and it is the last release.
This is test page: http://www.squassabia.com/aree_espositive_prova2.asp
What i need to do is to display the message you see in the code (boxText.innerHTML), just to understand it step by step and to keep things simple. After that I'm going to style it and add data from xml (which I think is not going to be that difficult).
As i didn't fint any solution in any of the old posts, if anyone of you can give me a clue on how to solve the problem, would be very appreciated, I've tried everything and put infobox stuff pretty much everywhere :(
Cheers
I give you the initialize() code:
//icone custom
var customIcons = {
negozio: {icon: '/images/gmaps/mc.png'},
outlet: {icon: '/images/gmaps/pin_fuc_outlet.png'},
sede: {icon: '/images/gmaps/pin_fuc_home.png'}
};
var clusterStyles = [
{
textColor: 'white',
url: '/images/gmaps/mc.png',
height: 48,
width: 48
}];
function initialize() {
//creo una istanza della mappa
var map = new google.maps.Map(document.getElementById("mapp"), {
center: new google.maps.LatLng(45.405, 9.867),
zoom: 9,
mapTypeId: 'roadmap',
saturation: 20, //scrollwheel: false
});
//stile della mappa
var pinkroad = [ //creo un array di proprietà
{
featureType: "all", //seleziono la feature
stylers: [{gamma: 0.8 },{ lightness: 50 },{ saturation: -100}]
},
{
featureType: "road.highway.controlled_access",
stylers: [{ hue: "#FF3366" },{ saturation: 50 },{ lightness: -5 }]
}
];
map.setOptions({styles: pinkroad});
var name;
//Creates content and style
var boxText = document.createElement("div");
boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
boxText.innerHTML = "Prova Infobox<br >Successo!!Test Text";
var myOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 0
,pixelOffset: new google.maps.Size(-140, 0)
,zIndex: null
,boxStyle: {background: "url('tipbox.gif') no-repeat", opacity: 0.75, width: "280px"}
,closeBoxMargin: "10px 2px 2px 2px"
,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,enableEventPropagation: false
};
var ib = new InfoBox(myOptions);
//creo il marker
downloadUrl("xml/negozi.xml", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++)
{
var type = markers[i].getAttribute("tipo");
var address = markers[i].getElementsByTagName("indirizzo")[0].childNodes[0].nodeValue;
var city = markers[i].getElementsByTagName("citta")[0].childNodes[0].nodeValue;
var phone = markers[i].getElementsByTagName("telefono")[0].childNodes[0].nodeValue;
name = markers[i].getElementsByTagName("nome")[0].childNodes[0].nodeValue;
var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
var html = name + '<br />' + address + '<br />' + city + '<br />' + phone;
var icon = '/images/gmaps/pin_fuc.png';
var marker = new google.maps.Marker({map: map, position: point, icon :'/images/gmaps/pin_fuc.png'});
/*google.maps.event.addListener(marker,"click", function(){
map.panTo(this.position);
});*/
createMarkerButton(marker);
google.maps.event.addListener(marker, "click", function (e) {
ib.open(map);
});
}
});
function createMarkerButton(marker) {
//Creates a sidebar button
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(name));
ul.appendChild(li);
//Trigger a click event to marker when the button is clicked.
google.maps.event.addDomListener(li, "mouseover", function(){
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout (function (){marker.setAnimation(null);}, 750);
});
google.maps.event.addDomListener(li, "mouseout", function(){
google.maps.event.trigger(marker, "mouseout");
});
}
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}