我正在尝试使用javascript创建一个简单的pdf文档.我找到了jsPDF,但我不知道如何居中文本.可能吗?
小智 60
是的,这是可能的.您可以编写一个jsPDF插件方法来使用.
一个简单的例子就是:
(function(API){
API.myText = function(txt, options, x, y) {
options = options ||{};
/* Use the options align property to specify desired text alignment
* Param x will be ignored if desired text alignment is 'center'.
* Usage of options can easily extend the function to apply different text
* styles and sizes
*/
if( options.align == "center" ){
// Get current font size
var fontSize = this.internal.getFontSize();
// Get page width
var pageWidth = this.internal.pageSize.width;
// Get the actual text's width
/* You multiply the unit width of your string by your font size and divide
* by the internal scale factor. The division is necessary
* for the case where you use units other than 'pt' in the constructor
* of jsPDF.
*/
txtWidth = this.getStringUnitWidth(txt)*fontSize/this.internal.scaleFactor;
// Calculate text's x coordinate
x = ( pageWidth - txtWidth ) / 2;
}
// Draw text at x,y
this.text(txt,x,y);
}
})(jsPDF.API);
Run Code Online (Sandbox Code Playgroud)
你就这样使用它
var doc = new jsPDF('p','in');
doc.text("Left aligned text",0.5,0.5);
doc.myText("Centered text",{align: "center"},0,1);
Run Code Online (Sandbox Code Playgroud)
sjy*_*sjy 26
这适用于jsPdf主页上的暂存器:
var centeredText = function(text, y) {
var textWidth = doc.getStringUnitWidth(text) * doc.internal.getFontSize() / doc.internal.scaleFactor;
var textOffset = (doc.internal.pageSize.width - textWidth) / 2;
doc.text(textOffset, y, text);
}
Run Code Online (Sandbox Code Playgroud)
我发现当前版本的jsPdf支持带有函数签名的参数'align',如下所示:
API.text = function (text, x, y, flags, angle, align)
Run Code Online (Sandbox Code Playgroud)
因此,以下内容应该为您提供中心对齐的文本:
doc.text('The text', doc.internal.pageSize.width, 50, null, null, 'center');
Run Code Online (Sandbox Code Playgroud)
但是,在当前时间点,当启用严格模式时,库中会抛出错误,因为缺少"var".有一个问题和拉取请求,但修复程序没有进入:https: //github.com/MrRio/jsPDF/issues/575
无论是谁在寻找这个,有一天,你可能能够使用它来更容易中心文本.
归档时间: |
|
查看次数: |
37904 次 |
最近记录: |