vivek11pune / jspdf

Automatically exported from code.google.com/p/jspdf
0 stars 0 forks source link

Need ability to center text horizontally between two coordinates (x1, x2) #28

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
It is very often necessary to center text horizontally within an area on a 
page.  Right now this does not seem possible.  One possibilty is for the 
programmer to calculate the starting x themselves which would require us to 
know the printed length of a text string before it is output which I do not 
currently see a way to do.

There are two ways to implement this:

1. Add an overload to doc.text that includes an x1 and x2 coordinate and then 
center the given text string between those coordinates.

e.g.  doc.text(x1, x2, y, "Center this");

This brings up another issue.  What if you want text to be printed 
left-justified between x1 and x2, having each new line begin again at x1.  So 
an additional method for text justification might be handy:

e.g  

doc.textJustify("left");
doc.text(100, 200, 10, "left justify this long line of text);

output: text would be start at (100,10) and then when the x coordinate passes x 
= 200, a new line would begin back at x = 100 and the remainder of the text 
would be printed (if the line was very long then obviously the text would take 
multiple vertical lines)

e.g.

doc.textJustify("center");
doc.text(100, 200, 10, "Center horizontally");

output: text would be centered horizontally between (100,10) and (200,10)

2. Implement a method that will return the printed length of a text string 
before it is output (based on the current font settings).  For example:
   var width = doc.textWidth("This text is to be centered");
With this width we could manually calculate the proper starting x coordinate 
for the doc.text() statement.

What version of the product are you using? On what operating system?

jsPDF 0.9.0rc2, windows 7

Please provide any additional information below.

Original issue reported on code.google.com by courtney...@gmail.com on 21 Aug 2013 at 12:42

GoogleCodeExporter commented 9 years ago
I am not able to make text align, could you please provide add the feature to 
have alignment for the text.

Original comment by madhu...@motorola.com on 11 Mar 2015 at 2:35

GoogleCodeExporter commented 9 years ago
Hey, 
I did this way,

var txtWidth = 
doc.getStringUnitWidth(inputString)*fontsize/doc.internal.scaleFactor;
var singleCharWidth = doc.getStringUnitWidth(" 
")*fontsize/doc.internal.scaleFactor
var marginFromLeft = ((totalWidth - txtWidth)/2);
doc.text(x+marginFromLeft, y, inputString);

Hope this may help you. 

Regards
Amit Gajjar

Original comment by gajjar...@gmail.com on 23 Apr 2015 at 4:44