jsPDF - practical example for a fit-to-width shopping cart HTML page? - jspdf

I'm trying to implement jsPDF pdf saving in a Vue app and I'm finding it overwhelming and nearly impossible to affect any visual change in the output.
The current results are: gigantic text and huge images.
Is there a way to get it to respect any of my CSS, #mediap print or otherwise, particularly for div borders?
The docs are very deep so I'd love an example of how to take a div-based table-like layout—e.g. a shopping cart—and fit it to width. I'd also love tips on avoid content bleeding across page breaks.
I've tried doc.setFont, doc.setFontSize and other methods and nothing changes the output.
this.doc.html(document.getElementById("pdfList"), {
callback: function (doc) {
doc.save("Cycad Inventory");
},
x: 40,
y: 40,
});

exportPDF = () => {
const unit = "pt";
const size = "A4"; // Use A1, A2, A3 or A4
const orientation = "portrait"; // portrait or landscape
const marginLeft = 30;
const doc = new jsPDF(orientation, unit, size);
doc.setFontSize(14);
const title = "Report";
const headers = [["Time", "Source", "Destination", "Protocol", "Length"]];
const data = this.state.ipData.map(elt => [elt.time, elt.source, elt.destination, elt.protocol, elt.length]);
let content = {
startY: 50,
head: headers,
body: data,
}
doc.text(title, marginLeft, 40);
doc.autoTable(content);
doc.save(this.state.ipData.fileName);
}
This is a code I used in reactJS. I hope this will help you to do changes to your code. Here I have declared the height, width, font sizes margins.

Related

Can I have a chart automatically size the height (rather than using 400px) using the Highcharts .NET Wrapper?

There is another similar question, but that seems to be focused on the js library, not Highsoft.Highcharts (and I'm using v8.1.1.1) I tried some of these solutions, but they didn't seem to work.
Try to use those CSS options:
body, html {
height: 100%;
}
#container {
height: 100%;
}
Not the most elegant when you're working with a .NET wrapper, but this seemed to work (from a colleague of mine). When using the wrapper, "chart" comes from the Id of the Highcharts object. So you will need to change that if you use something else for Id.
var chart = new Highcharts { Id = "chart" };
And then this script in the .cshtml file:
<script>
$(window).load(function () {
// "chart" is the Id of the Highcharts container
var chart = $('#chart').highcharts();
var width = $('#chart').width();
// 100 is an approximation for the hight of the navbar + margin for panel. Removing that from the entire height of the window.
var height = $(window).innerHeight() - 100;
$('panel-body').height = height;
// setsize will trigger the graph redraw
chart.setSize(width, height, false);
});
$(window).resize(function () {
// "chart" is the Id of the Highcharts container
var chart = $('#chart').highcharts();
var width = $('#chart').width();
// 100 is an approximation for the hight of the navbar + margin for panel. Removing that from the entire height of the window.
var height = $(window).innerHeight() - 100;
// setsize will trigger the graph redraw
chart.setSize(width, height, false);
});
</script>

jsPDF fromHTML image (to large) and page margin-bottom (not working)

I just implemented jspdf in a page, where users work with an editor and then want to be able to print the result. When I tested some example content, I run in to that problem the images are not displayed in there orignial size. They are scaled/displayed so large, that they are lager then the width of the page.
Also I had a problem with the page height/margin-bottom. If the content is to large for a page, then there will be no margin at the bottom of the page. So if for what ever reason an elemtent seems to be too large for a page, this element goes until the end of the page.
I googled a lod, but I couldn't find a solution to avoid that too large elements go until the border of the page.
And I also could not find something, for how to set an image to it's original or max-size when I don't know the content of the page.
Here is js code and an example page: jsfiddle-example
$(".printPdf").click(function () {
var pdfdoc = new jsPDF("portrait");
var getPageTitle = $("#page-title");
var pageTitle = (getPageTitle != "")? getPageTitle : "Document";
var contentClass = ".page-content";
var $pageContent = $(contentClass);
var margins = {
top: 10,
bottom: 20,
left: 15,
width: 180
};
pdfdoc.setDisplayMode('original');
pdfdoc.fromHTML($pageContent.get(0), margins.left, margins.top, {
"width": margins.width,
"text-align": "unset"
}, function () { pdfdoc.save(pdfdoc.pageTitle + ".pdf") }, margins);
});

jsPDF and jsPDF auto table - height issue

I have the below code to retrieve the array list of elements to a pdf doc.
I am using A4 size. Since the number of columns are more , I am getting all the data in an ellipsis format.
Is there anyway I can download the doc as a landscape view instead of portrait view, so that I can avoid the ellipsis and I can see all the datas properly ?
As an alternate option I tried to use A1 size, it looks fine as a PDF , but the problem comes when i take a print out of the document as a A4 sheet. The font size is very small after taking the print out. So I want to achieve all the datas to be visible properly without any ellipsis in landscape view with A1. ( This way I will not have any issues in viewing the pdf and also when I take pritnout of the same )
convert() {
const doc = new jsPDF('p', 'pt', 'A4');
const col = ['Discharge Date', 'Case Number', 'Patient', 'Hospital', 'Payee', 'Total Doctor Fee', 'To be Collected', 'Payor', 'Remarks', 'Paid', 'Unpaid'];
const rows = [];
/* The following array of object as response from the API req */
const itemNew = this.finalArList;
itemNew.forEach(element => {
const temp = [element.dischargeDate, element.caseNo, element.patientName, element.instName, element.clinicName, element.formattedTotalDrFee, element.formattedUnpaidAmounr, element.payor, element.remark, element.formattedTotalDrFee, element.formattedUnpaidAmounr];
rows.push(temp);
doc.autoTable(col, rows, {margin: {top: 10}, height: 'auto' });
});
doc.save('MyReport.pdf');
}
Use
new jsPDF('l', 'mm', 'a4');
or
var doc = new jsPDF('landscape');
instead of
new jsPDF('p', 'pt', 'A4');
and then pls chk

Add content before and after table (jsPDF autotable)

i have a question to jsPDF autotable.
My Code:
$('#printBtn').on('click', function() {
var pdf = new jsPDF('p', 'pt', 'a4');
var res = pdf.autoTableHtmlToJson(document.getElementById("tablePrint"));
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';
}
}
});
pdf.save("test.pdf");
});
I want add Text before and after the Table from a div.
I have found this Code Snippet in jsPDF autotable examples:
var before = "text before";
pdf.text(before, 14, 30);
This code works good. I have insert that before pdf.autoTable(...});.
But i dont know what the number 14 and 30 for?
Then i have the code insert after the pdf.autoTable function call and the Text printed on the last page of pdf but on the top of the page, not on the end, why?
Sorry for my bad englisch.
Thanks for help.
If what you want is to add something before you must first move the table that you are adding with autotable, you achieve this by adding a startY: 150 attribute within doc.autotable:
pdf.autoTable(res.columns, res.data, {
theme : 'plain',
styles: {
fontSize: 12
},
startY: 150,
showHeader: 'never',
createdCell: function(cell, data) {
var tdElement = cell.raw;
if (tdElement.classList.contains('hrow')) {
cell.styles.fontStyle = 'bold';
}
}
});
150 is the value in pixels you want to move. Above this you can place the text you want with the code you placed.
var before = "text before";
pdf.text(before, 14, 30);
Now the values of 14 (Value in Y) and 30 (Value in Y) are the values that you want the text to move in pixels.
In order for you to add text after the table you must first obtain in which number of pixels your table ended and from there enter the text you want.
let finalY = pdf.previousAutoTable.finalY; //this gives you the value of the end-y-axis-position of the previous autotable.
pdf.text("Text to be shown relative to the table", 12, finalY + 10); //you use the variable and add the number of pixels you want it to move.
Here's my stab at an answer:
So this is your Autotable's function call:
var pdf = new jsPDF('p', 'pt', 'a4');
Since jsPDF Autotables is based on jsPDF, you'll have to go here:
pt is a unit of measurement called points, so 14 and 30 are points. At the first position, 14, moves elements left and right. The second position, 30, moves elements down and up. I'm guessing they're like pixels(px). Seems like you have to move your text to your desired locations by using points.
An idea that helped me is to placing a Table with no content on the position where you would like to add the new table.
autoTable(doc, {
body: [],
startY: finalY + bias
});

How to align text in center using jspdf

How to align text center using jsPDF.
var doc = new jsPDF();
doc.text(40, 250, 'Hi How are you');
If you are using the latest version (1.1.135) the api has changed some for the text function. It now reads as:
API.text = function(text, x, y, flags, angle, align);
If you don't need to use the flags or angle though, you can simply use:
var doc = new jsPDF();
doc.text('Hi How are you', 40, 250, 'center');
Keep in mind that the center call uses the x parameter now as the center of the text string, and not the left most border as it does when rendering left aligned.
Link to source
Edit:
Alternately you can calculate the proper x offset to just use the text function normally like so:
var text = "Hi How are you",
xOffset = (doc.internal.pageSize.width / 2) - (doc.getStringUnitWidth(text) * doc.internal.getFontSize() / 2);
doc.text(text, xOffset, 250);
Angular 6.
Footer align to horizontally center
var doc = new jsPDF();
var pageHeight = doc.internal.pageSize.height || doc.internal.pageSize.getHeight();
var pageWidth = doc.internal.pageSize.width || doc.internal.pageSize.getWidth();
// FOOTER
let str = "Your footer text";
doc.setTextColor(100);
doc.setFontSize(10);
doc.text(str, pageWidth / 2, pageHeight - 10, {align: 'center'});
doc.save("example.pdf");
Above answers didn't work for me, I ended up doing the following to center the text
let textX = (doc.internal.pageSize.getWidth() - doc.getTextWidth(text))/2
doc.text(text, textX, textY);
this worked:
var xOffset = doc.internal.pageSize.width / 2
doc.text('hello world', xOffset, 8, {align: 'center'});
2022: this works assuming your page width is 210 (default A4).
doc.text("This is centred text.", 105, 80, null, null, "center");
Here's a link to their live demo per the README:
http://raw.githack.com/MrRio/jsPDF/master/index.html
2022: I'm finding that JSPDF is buggy. It took a while to figure out how to install the advertised 'runs in a browser' implementation for a PHP app instead of a JS front end framework. There's a line that's required window.jsPDF = window.jspdf.jsPDF; that isn't mentioned anywhere in the documentation, I had to go through a downloaded example piece by piece to find it. Now I'm finding that the center text function doesn't work. In 2 different local environments and a JSFiddle, on multiple browsers, it sends the text off the left side of the page when the align:center option is implemented. While the above solution works, it breaks down if text is longer than one line, which, incidentally, is another out of the box bug - the text runs out of the document instead of wrapping, and there is no wrap option. So, it seems after all these hours I'm out of luck and I'll have to go a different route. Plugin is not maintained and this should be noted in documentation. Recommend to not waste your time.
This works somewhat, but isn't precise, if you know please tell me why.
I calculate the width of my text in order to center it myself.
For this, I used the getTextDimensions() method on my jsPDF object
var pdf = new jsPDF({
orientation : 'p',
unit: 'px',
format: [500, 750],
putOnlyUsedFonts:true
});
var textDimensions = pdf.getTextDimensions('MyText');
You can now use textDimensions.w to get text-width and textDimensions.h for height
Then use this to center your text.
var textWidth = textDimensions.w;
pdf.text('MyText', (pdfWidth / 2) - (textWidth / 2), 100);
BUT: You need to know your PDF's width to do this.
I 'solved' this by defining height and width myself, but you can easily find height and width of common formats online.
Like A4: 210mm*297mm.
Just remember to set unit: 'mm' when creating your jsPDF.
var doc = new jsPDF();
// set midPage for variable use
var midPage = doc.internal.pageSize.getWidth()/2
// Default is 210 mm so default midway by value is 105
doc.setFontSize(40);
doc.text("Octonyan loves jsPDF", 105, 15, null, null, "center");
// Better to use a variable "midPage" (from above)
doc.setFontSize(30);
doc.text("Centered (USA), Centred (UK)", midPage , 30, null, null, "center");

Resources