How to set pdf font size for table content using jspdf? - jspdf

How to set pdf font size for table content using jspdf?
setFontSize doesn't work in my case.

Setting font size for text in a table using jspdf-autotable looks like this:
var doc = new jsPDF();
doc.autoTable({html: '#table', styles: {fontSize: 20}})
doc.save("table.pdf");

Edit this: jspdf.plugin.autotable.min.js
Find this part and edit fontSize: textColor:20,halign:"left",valign:"top",fontSize:10,cellPadding:5
the default size is 10 and I change it to 7:
textColor:20,halign:"left",valign:"top",fontSize:7,cellPadding:5

Before printing, make a copy of the table object.
Let's say:
let temporalTable = document.getElementsByClassName("table")[0];
Then apply a style to this object. You can use plain JS functions.
And finally:
html2canvas(temporalTableWithNewStyles)
.then((canvas: any) => {
doc.addImage(canvas.toDataURL("image/jpeg"), "JPEG", 0, 50, doc.internal.pageSize.width, element.offsetHeight / 5 );
doc.save(`Report-${Date.now()}.pdf`);
})

Related

tcpdf module on Silverstripe Framework

I am trying to use the tcpdf module on silverstripe but it doesn't seem to generate the pdf file.
Below is the class that has the method that should be generating the pdf. The $url_handler part is commented because am not sure how to re-route the request from link $PDFLink to this class.
Any kind of help will be greatly appreciated.
class RaaOrders Extends ReportsModule {
public static $allowed_actions = array (
'pdf'
);
public static $url_handlers = array (
// 'get_pdf' => 'pdf'
);
public function pdf(){
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 001');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING, array(0,64,255), array(0,64,128));
$pdf->setFooterData(array(0,64,0), array(0,64,128));
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (#file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set default font subsetting mode
$pdf->setFontSubsetting(true);
// Set font
// dejavusans is a UTF-8 Unicode font, if you only need to
// print standard ASCII chars, you can use core fonts like
// helvetica or times to reduce file size.
$pdf->SetFont('dejavusans', '', 14, '', true);
// Add a page
// This method has several options, check the source code documentation for more information.
$pdf->AddPage();
// set text shadow effect
$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
// Print a text
$html = '<span style="background-color:yellow;color:blue;"> PAGE 1 </span>
<p stroke="0.2" fill="true" strokecolor="yellow" color="blue" style="font-family:helvetica;font-weight:bold;font-size:26pt;">You can set a full page background.</p>';
$pdf->writeHTML($html, true, false, true, false, '');
// Close and output PDF document
// This method has several options, check the source code documentation for more information.
$pdf->Output('example_001.pdf', 'I');
}
}
I found out that the issue was exactly what I thought it was. Dependencies were not well taken care of because I was doing a manual install.
So I used composer and everything works fine. And you can actually use SS templating to populate the pdf with data, by returning your Objects to the template as shown below.
$pdf = new TCPDF();
$pdf->AddPage();
$vd = new ViewableData();
$str = $vd->customise(ArrayData::create(array('MyVariable'=>'MyValue')))->renderWith('MyTemplateName');
$pdf->writeHTMLCell(0, 0, '', '', $str, 0, 1, 0, true, '', true);
$strContent = $pdf->Output(BASE_PATH.'/tmp/tmp.pdf', 'S');
Call exit when you're done. That's probably the easiest way.
As with most frameworks the output is done elsewhere, after your logic is implemented. Since you are not returning anything, it may give an empty response, or set an error code, etc. Likely interfering with what the pdf library is trying to do. You can avoid that by prematurely exiting (after the pdf library has output a valid response directly to the browser).

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");

Set dynamically height for entire Prawn PDF Document

I'm stuck with a problem when trying to generate a document using Prawn gem for Rails
What I'm trying to do is to set a variable height for my pdf, so depending on some queries in the database, the PDF height will change. I'm doing this because I need a single page PDF document.
Currently, my code looks like this:
pdf = Prawn::Document.new(page_size: [297.64, 419.53], margin: 0)
....
data = [ ["Header1", "Header2", "Header3", "Header4", "Header5", "Header6"] ]
// here is the variable data
cart.cart_products.each do |cp|
arr = [
cp.product_code,
cp.product_description,
cp.amount,
cp.product_metric,
cp.product_unit_value,
cp.total_value
]
data.push(arr)
end
// populating the table with data
pdf.table(data, :cell_style => {:border_width => 0}, :column_widths => [45, 80, 30, 42.36, 50, 50]) do |table|
table.row(0).border_width = 0.1.mm
table.row(0).font_style = :bold
table.row(0).borders = [:bottom]
end
....
pdf.render_file("path/to/dir/document.pdf")
Can anyone help me with this? Thanks.
Without knowing what exactly you're adjusting for, I'll have to makes some guesses here.
So I would establish some sort of line height for your returned data and a min document height.
line_height = 14
min_height = 419.53
Then I would run the queries and count the results. Then I would figure out what the variable height would be and add it to the min height.
variable_height = results.length * line_height
height = min_height + variable_height
Finally:
pdf = Prawn::Document.new(page_size: [297.64, height], margin: 0)
Something like this should work with tweaks for your specific needs.
Thomas Leitner suggested a better option in a GitHub issue comment (https://github.com/prawnpdf/prawn/issues/974#issuecomment-239751947):
Just what I wanted to post 😄 - so here it goes:
You could probably use a a very large height for your document so that prawn doesn't automatically create a new one. And once you are finished with everything, use Prawn::Document#y to determine your current vertical position.
Then you can use Prawn::Document#page (a PDF::Core::Page object) to adjust the MediaBox for the page, something like:
require 'prawn'
Prawn::Document.generate("test.pdf", page_size: [100, 2000], margin: 10) do |doc|
rand(100).times do
doc.text("some text")
end
doc.page.dictionary.data[:MediaBox] = [0, doc.y - 10, 100, 2000]
end
Credits to Thomas Leitner (https://github.com/gettalong)

Responsive Image, Bootstrap 3 and Umbraco 7.2.1

While I'm using Umbraco 7.2.1, I want the image I insert to be responsive (img-responsive) of bootstrap.
How can i do that?
I'm not sure how you are adding the images to your pages but I had this problem when I started using the new grid layout in Umbraco 7.2.
So if you are also using the grid layout what you need to do is open the view "Partial Views\Grid\Editors\Media.cshtml" and add the class there.
...
<img src="#url" class="img-responsive" alt="#Model.value.caption">
...
This will add the class to ALL images added to the grid layout with the standard "Image" grid editor.
You can add your own custom class to to images in
~/umbraco_client/tinymce3/plugins/umbracoimg/img/image.js
Look for where it says tinymce.extend(). It should end up looking something like this:
tinymce.extend(args, {
src: nl.src.value,
width: nl.width.value,
height: nl.height.value,
alt: nl.alt.value,
title: nl.alt.value,
rel: nl.orgWidth.value + ',' + nl.orgHeight.value,
class: 'img-responsive'
});
I've only done this in Umbraco 6, so hopefully the answer is still the same in Umbraco 7.
I don't advise altering anything in the /umbraco/ or /umbraco_client/ folders since any future updates will undo your changes, forcing you to reapply them.
Assuming you want to add a responsive class to images entered in the rich text editor, I would recommend creating a new css rule for img elements that adds the relevant properties from .img-responsive.
For example:
You add a rich text data type called bodyText to a document type in Umbraco. In your template for this document, wrap the rendering call in an element with the class .bodyText.
<div class="bodyText">
#Umbraco.Field("bodyText")
</div>
In your stylesheet, create a new rule for .bodyText img that inherits the properties from the .img-responsive class.
.bodyText img {
max-width: 100%;
height: auto !important;
}
Note !important on the height property. This is added to ensure that the inline-style added for height are overridden. When an editor changes the dimensions of an image in the rich text editor, tinyMCE will add the new dimensions to the image's inline style attribute, thus killing the responsive height.
I did it very easily in Umbraco 7.5.5, change /Umbraco/Js/umbraco.services.js:
$timeout(function () {
var imgElm = editor.dom.get('__mcenew');
var size = editor.dom.getSize(imgElm);
if (editor.settings.maxImageSize && editor.settings.maxImageSize !== 0) {
var newSize = imageHelper.scaleToMaxSize(editor.settings.maxImageSize, size.w, size.h);
// images must be responsive: commented 3 lines of code, added addClass with img-responsive,
// var s = "width: " + newSize.width + "px; height:" + newSize.height + "px;";
// editor.dom.setAttrib(imgElm, 'style', s);
editor.dom.addClass(imgElm, 'img-responsive');
editor.dom.setAttrib(imgElm, 'id', null);
if (img.url) {
//var src = img.url + "?width=" + newSize.width + "&height=" + newSize.height;
var src = img.url;
editor.dom.setAttrib(imgElm, 'data-mce-src', src);
}
}
}, 500);

How to change the look of a textbox

I want to have a multiline textbox of max of 3 rows and I also want to modify it`s width and height size. How can I do that in mvc?
The following code is not working
#Html.TextBox("myTextBox", String.Empty, new { #style = "width: 150px; ,height : 80px; multiline = true", #MAXLENGTH = "2000" })
A html-textbox is always single-line. Use a TextArea instead:
#Html.TextArea("myTextArea", String.Empty, 10, 40, new { style=""})
You can alter the 10 (rows) and 40 (columns) for another width/height, or set it directly with width and height in the style.
#Html.TextArea("Foo", new { row = 3, style = "width:300px;height:30px;" })
Edit:
First of all, there is nothing called textbox on html spec. ASP.NET MVC ain't Web Forms. It is input element whose type attribute is set to text.
Second, show me how you do it. The multiline version of a text input is textarea.

Resources