I have used jspdf and jspdfAutoTable in my code to generate pdf.
It works fine on a single page, with upto 23 rows. As soon as I add 24th row (i.e the row to be present on second page), everything is distorted.
page-1 pdf screenshot
I have used below code to generate the PDF
generatePdf(){
const { jsPDF } = window.jspdf;
const { jsPDFAutotable } = window.jspdfautotable;
const doc = new jsPDF('landscape');//
var totalPagesExp = doc.internal.getNumberOfPages();// '{total_pages_count_string}' ==> the output becomes Page 1 of '{total_pages_count_string}' and page 2 of '{total_pages_count_string}'
let head = [['ID', 'Country', 'Rank', 'Capital', 'Name', 'TelephoneNumber', 'Email', 'SomeText']];
let body = [
[1, 'Denmark', 7.526, 'Cp', 'Alex', 9876543.210123456789, 'alex#example.com', 'a!£$%^&*()~#¬,.<>?asdfgQWERTY#asdfgh11222333344444'],
.
.
.
[23, 'Iceland', 7.501, 'Reykjavík', 'John', 2321, 'john#example.com', 'asdfgQWERTY'],
];
doc.autoTable({
head: head,
body: body,
tableWidth: 'auto',
styles: {
cellWidth: 'wrap',
fontSize: 8
},
columnStyles: {
ID: {cellWidth: 'auto'},
Country: {cellWidth: 'auto'},
Rank: {cellWidth: 'auto'}
},
theme: 'striped',
pageBreak: 'auto',
showHead: 'everyPage',
showFoot: 'everyPage',
margin: { top: 30 },
didDrawPage: function (data) {
doc.setFontSize(20);
doc.setTextColor(40);
//doc.setFontStyle('normal');
doc.text("Equipment Out On Jobs", 14, 22);
doc.setFontSize(20);
doc.setTextColor(40);
//doc.setFontStyle('normal');
doc.text("Job Numbers: 104319419,104319136", 14, 30);
// Footer
var str = "Page " + doc.internal.getCurrentPageInfo().pageNumber;
// Total page number plugin only available in jspdf v1.0+
if (typeof doc.putTotalPages === 'function') {
str = str + " of " + totalPagesExp;
}
doc.setFontSize(8);
doc.setTextColor(40);
//doc.setFontStyle('normal');
var pageSize = doc.internal.pageSize;
var pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
doc.text(str, 14, pageHeight - 10);
},
});
// Total page number plugin only available in jspdf v1.0+
if (typeof doc.putTotalPages === 'function') {
doc.putTotalPages(totalPagesExp);
}
doc.save('table.pdf');
}
The entire page gets distorted.
Please help.
UPDATE codepen where it is working perfectly fine. Only in LWC, something is causing problem.
Related
Below is my Code where the html contents (input) are downloaded into pdf
i have a page in which my html controls are present and I'm trying to download the same html file on button click. the page download but some contents get cut off at bottom of the page while converting the html to pdf. I have used jspdf and html2canvas for this implementation.
const input = document.getElementById('print');
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'pt',
format: 'a4',
compress:true,
});
//check for Screen dimensions
let srcwidth = document.getElementById('print').scrollWidth;
pdf
.html(input, {
margin: [55, 0, 40, -2],
autoPaging: 'text',
html2canvas: {
scale: 595.26 / srcwidth, //595.26 is the width of A4 page
scrollY: 0,
},
})
.then(() => {
const pageCount = pdf.internal.getNumberOfPages();
const pageWidth = pdf.internal.pageSize.getWidth();
var pageHeight = pdf.internal.pageSize.getHeight();
//loop to set header/ footer, style, alignment, text style to the page
for (let i = 1; i <= pageCount; i++) {
pdf.rect(
5,
5,
pdf.internal.pageSize.width - 13,
pdf.internal.pageSize.height - 13,
'S',
);
pdf.setPage(i);
pdf.viewerPreferences({"FitWindow":true,"ViewArea":"MediaBox","ViewClip":"MediaBox" });
var header = 'CSMM 5A - Vessel Cyber Security Self Assessment';
var headerLine =
'_________________________________________________________________________________';
const footer = `Page ${i} of ${pageCount}`;
var submitedDate =
'Date Last Edited: ' +
this.formatDateTime(this.state.vesselAssesementData.editedOn);
// if (i > 1) {
pdf
.setFont('sans-serif', '', 'bold')
.setFontSize(14)
.text(header, 20, 25, { baseline: 'top' });
pdf.addImage(kline, 'PNG', 530, 12, 35, 35);
pdf.text(headerLine, 10, 38, { baseline: 'top' });
// }
pdf
.setFont('Arial, sans-serif', '', 'normal')
.setFontSize(9)
.text(
submitedDate,
pageWidth / 6.5 - pdf.getTextWidth(submitedDate) / 2,
pageHeight - 18,
{ baseline: 'bottom' },
);
pdf
.setFont('Arial, sans-serif', '', 'normal')
.setFontSize(9)
.text(
footer,
pageWidth / 1.08 - pdf.getTextWidth(footer) / 2,
pageHeight - 18,
{ baseline: 'bottom|right' },
);
}
pdf.save(
`${
'VesselCyberSecuritySelfAssessmentReport_' +
this.state.vesselAssesementData.uniqueId
}.pdf`,
);
Below is image attached where the issue occurs.
this is multiple page which is created where the content alignment issue occurs
Solution for this ASAP will be very helpful.
Hi I have the below code to achieve print functionality . The code works fine in Chrome, but doesnt work in Edge. Getting the follwing error in edge.I am building the layout in javascript in generatePDF function.
Below is my JS code:
$scope.printRepayment = function() {
var documentDefinition = generatePDF(); pdfMake.createPdf(documentDefinition).print();
}
var generatePDF = function() {
var repayments = $scope.repayments;
var rows = [
[
{ text: "Payment No", style: "tableHeader" },
{ text: "Installment", style: "tableHeader" },
]
];
for (var i = 0; i < repayments.length; i++) {
rows.push([
{ text: i + 1, style: "tablefirst" },
{
text:
"AED " +
numberWithCommas(
parseFloat(repayments[i].installment).toFixed(2)
),
style: "tableOther"
},
]);
}
return {
content: [
{ text: "Repayment schedule", style: "subheader" },
{
style: "tableExample",
table: {
widths: ["*", "*", "*", "*", "*"],
body: rows
},
layout: {
vLineColor: function(i, node) {
return "#ECF3FE";
}
}
}
],
styles: {
tabletop: {
margin: [10, 0, 0, 10]
},
tabletopHeader: {
fontSize: 16,
bold: true
}
}
};
};
With refer to this article, we can see that the pdfMake print() method doesn't support Edge browser. So, as a workaround, I think you could create a web page which contains the display the pdf content, then, calling the window.print(); method to print this page. Otherwise, as Master Po said, you could download the pdf file first, then, print the pdf content.
Thanks a ton #Zhi Lv - MSFT, for giving the solution in plain english and then after having discovered how to do, this is what worked for me
var pdf = pdfMake.createPdf(doc);
pdf.getBuffer(function (buffer) {
var file = new Blob([buffer], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.location.href = fileURL;
}); // {autoPrint: true});
the pdf file generated is converted into a blob and the url of that file is then opened up as a new window, shows the pdf doc and can be printed
Yet not sure how autoPrint works, will need to work a bit more
I have to place the heading of the pdf in the center. I have tried many ways but could not find a possible way that worked.
I am using the jspdf and jspdf-autotable package to form the pdf using reactjs.
var options = {
didDrawPage: function (data) {
// Header
doc.text(heading, 20, 10,{
halign: 'center',
valign: 'middle'
});
}
};
doc.autoTable(columns, rows, options);
doc.save('table.pdf');
The above code is not working for me.
To align specific header column:
you must add column name in head definition
add function to hook didParseCell
const head = [
{
code: 'Code',// <- here
qty: 'Qty',
}
];
const doc = new jsPDF();
autoTable(doc, {
head: head,
body: someData,
didParseCell: (hookData) => {
if (hookData.section === 'head') {
if (hookData.column.dataKey === 'qty') {
hookData.cell.styles.halign = 'right';
}
}
}
});
doc.save('fileName.pdf');
Try this.
var columns = [...];
var rows = [...];
var options = {
headStyles:{
valign: 'middle',
halign : 'center'
}
};
doc.autoTable(columns, rows, options);
doc.save('table.pdf');
I am adding a plugin which insert twitter embed code. the problem is that I can see the tweet on the editor but not in the source code and preview. And I can't save it. I saw in forum that I have to add 'http:' to '//platform.twitter.com/widgets.js' and put it before , unfortunately, it's not working. This is the code I put:
tinymce.PluginManager.add('twitter', function(editor, url) {
editor.on('init', function (args) {
editor_id = args.target.id;
});
editor.addButton('twitter', {
text: 'Twitter',
icon: false,
onclick: function () {
editor.windowManager.open({
title: 'Twitter Embed',
body: [
{ type: 'textbox',
size: 40,
height: '100px',
name: 'twitter',
label: 'twitter'
}
],
onsubmit: function(e) {
var embedCode = e.data.twitter;
var script = embedCode.match(/<script.*<\/script>/)[0];
var scriptSrc = script.match(/".*\.js/)[0].split("\"")[1];
console.log(script);
var sc = document.createElement("script");
sc.setAttribute("src", "https:"+scriptSrc);
sc.setAttribute("type", "text/javascript");
var iframe = document.getElementById(editor_id + "_ifr");
var iframeHead = iframe.contentWindow.document.getElementsByTagName('head')[0];
var iframeBody = iframe.contentWindow.document.getElementsByTagName('body')[0];
embedCode1 = embedCode.replace('//platform.twitter.com/widgets.js','https://platform.twitter.com/widgets.js');
iframeBody.appendChild(sc);
editor.insertContent(embedCode1);
iframeHead.appendChild(sc);
// setTimeout(function() {
// iframe.contentWindow.twttr.widgets.load();
// }, 1000)
}
});
}
});
});
I wrote this code to create chart, table and toolbar.
google.load("visualization", "1", { packages: ["corechart"] });
google.load('visualization', '1', { packages: ['table'] });
//google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "GET",
url: '#Url.Action("GunlukOkumalar", "Enerji")',
data: "startDate=" + $('#start_date').val() + "&endDate=" + $('#end_date').val() + "&sayac_id=" + $("#sayaclar").val(), //belirli aralıklardaki veriyi cekmek için
success: function (result) {
if (result.success) {
var evalledData = eval("(" + result.chartData + ")");
var opts = { curveType: "function", width: '100%', height: 500, pointSize: 5 };
new google.visualization.LineChart($("#chart_div").get(0)).draw(new google.visualization.DataTable(evalledData, 0.5), opts);
$('#chart_div').show();
var visualization;
var data;
var options = { 'showRowNumber': true };
data = new google.visualization.DataTable(evalledData, 0.5);
// Set paging configuration options
// Note: these options are changed by the UI controls in the example.
options['page'] = 'enable';
options['pageSize'] = 10;
options['pagingSymbols'] = { prev: 'prev', next: 'next' };
options['pagingButtonsConfiguration'] = 'auto';
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, options);
var components = [
{ type: 'html', datasource: data },
{ type: 'csv', datasource: data }
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
return false;
}
else {
$('#chart_div').html('<span style="color:red;"><b>' + result.Error + '</b></span>');
$('#chart_div').show();
$('#table').html('<span style="color:red;"><b>' + result.Error + '</b></span>');
$('#table').show();
return false;
}
}
});
}
Google example
function drawToolbar() {
var components = [
{type: 'igoogle', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA',
gadget: 'https://www.google.com/ig/modules/pie-chart.xml',
userprefs: {'3d': 1}},
{type: 'html', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA'},
{type: 'csv', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA'},
{type: 'htmlcode', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA',
gadget: 'https://www.google.com/ig/modules/pie-chart.xml',
userprefs: {'3d': 1},
style: 'width: 800px; height: 700px; border: 3px solid purple;'}
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
};
Google get dataSource from url, but I get dataSource dynamicly from controller. When I try to export It forwards page to another page like this:
http://localhost:49972/Enerji/%5Bobject%20Object%5D?tqx=out%3Acsv%3B
How can I use exporting toolbar for dynamic Json data? Is there any example about this topic?
I also had this problem and after a lot of trawling I found this!
https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
I haven't implemented it yet but I reckon it's the way to go.