【发布时间】:2014-01-30 09:41:15
【问题描述】:
我正在尝试使用 javascript 创建一个简单的 pdf 文档。我找到了 jsPDF,但我不知道如何使文本居中。有可能吗?
【问题讨论】:
-
Tsilis 的回答应该被接受,因为它解决了 OP 的问题并且是最佳答案
-
@HaithamMaaieh 完成。
标签: javascript jspdf
我正在尝试使用 javascript 创建一个简单的 pdf 文档。我找到了 jsPDF,但我不知道如何使文本居中。有可能吗?
【问题讨论】:
标签: javascript jspdf
是的,这是可能的。您可以编写一个 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);
然后你就这样使用它
var doc = new jsPDF('p','in');
doc.text("Left aligned text",0.5,0.5);
doc.myText("Centered text",{align: "center"},0,1);
【讨论】:
x = (typeof x != "undefined" ? (( pageWidth - txtWidth ) - x) : ( pageWidth - txtWidth ) );
x = ( pageWidth - txtWidth ) / 2; 替换为我提供的代码。
这适用于jsPdf homepage 的暂存器:
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);
}
【讨论】:
我发现当前版本的 jsPdf 支持参数 'align' 与函数签名如下:
API.text = function (text, x, y, flags, angle, align)
所以下面应该给你一个居中对齐的文本:
doc.text('The text', doc.internal.pageSize.width, 50, null, null, 'center');
但是,在当前时间点,当严格模式打开时,库中会抛出错误,因为缺少“var”。 有一个问题和拉取请求,但修复尚未解决: https://github.com/MrRio/jsPDF/issues/575
无论谁在寻找这个,总有一天,你也许可以使用它来使文本更容易居中。
【讨论】:
jspdf 的当前版本描述的不一样,但它确实为我指明了正确的方向。唯一的区别是需要使用doc.internal.pageSize.getWidth() / 2 而不是doc.internal.pageSize.width。
WootWoot,以防万一您需要更多布局选项,您也可以看看我的 pdfmake 库
它支持:
它适用于客户端(纯 JS)或服务器端(一个 npm 模块)
看看the playground 看看有什么可能
祝你好运
【讨论】:
在创建 PDF 文件(例如 auto-pagebreak、total-pageCount)时,我遇到了同样的问题以及很多其他问题。所以我开始编写一个小库,它依赖于 jsPDF,但以你知道的方式(从 HTML/CSS 和 jQuery)为你提供了很多特性。您可以在GitHub 上找到它。我希望它使 PDF 创建更容易... =)
【讨论】:
根据@Tsilis 的回答,我在https://gist.github.com/Purush0th/7fe8665bbb04482a0d80 有一个插件,它可以在给定的文本容器宽度中对齐文本左、右和居中。
(function (api, $) {
'use strict';
api.writeText = function (x, y, text, options) {
options = options || {};
var defaults = {
align: 'left',
width: this.internal.pageSize.width
}
var settings = $.extend({}, defaults, options);
// Get current font size
var fontSize = this.internal.getFontSize();
// 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.
*/
var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
if (settings.align === 'center')
x += (settings.width - txtWidth) / 2;
else if (settings.align === 'right')
x += (settings.width - txtWidth);
//default is 'left' alignment
this.text(text, x, y);
}
})(jsPDF.API, jQuery);
用法
var doc = new jsPDF('p', 'pt', 'a4');
//Alignment based on page width
doc.writeText(0, 40 ,'align - center ', { align: 'center' });
doc.writeText(0, 80 ,'align - right ', { align: 'right' });
//Alignment based on text container width
doc.writeText(0, 120 ,'align - center : inside container',{align:'center',width:100});
【讨论】:
doc.text(text,left,top,'center') 可用于使文本居中。它也可以与行数组一起使用,但是当它与数组一起使用时,中心不能正常工作,所以我在循环中为数组中的每个对象使用了它。
var lMargin=15; //left margin in mm
var rMargin=15; //right margin in mm
var pdfInMM=210; // width of A4 in mm
var pageCenter=pdfInMM/2;
var doc = new jsPDF("p","mm","a4");
var paragraph="Apple's iPhone 7 is officially upon us. After a week of pre-orders, the latest in the iPhone lineup officially launches today.\n\nEager Apple fans will be lining up out the door at Apple and carrier stores around the country to grab up the iPhone 7 and iPhone 7 Plus, while Android owners look on bemusedly.\n\nDuring the Apple Event last week, the tech giant revealed a number of big, positive changes coming to the iPhone 7. It's thinner. The camera is better. And, perhaps best of all, the iPhone 7 is finally water resistant.\n\nStill, while there may be plenty to like about the new iPhone, there's plenty more that's left us disappointed. Enough, at least, to make smartphone shoppers consider waiting until 2017, when Apple is reportedly going to let loose on all cylinders with an all-glass chassis design.";
var lines =doc.splitTextToSize(paragraph, (pdfInMM-lMargin-rMargin));
var dim = doc.getTextDimensions('Text');
var lineHeight = dim.h
for(var i=0;i<lines.length;i++){
lineTop = (lineHeight/2)*i
doc.text(lines[i],pageCenter,20+lineTop,'center'); //see this line
}
doc.save('Generated.pdf');
【讨论】:
首先获取页面宽度,获取页面宽度的一半并将其用作 x 值,使用您选择的 y 值并将 center 作为第三个参数传递以使文本居中。 Read more from documentation
let doc = new jsPDF();
let pageWidth = doc.internal.pageSize.getWidth();
doc.text("My centered text",pageWidth / 2, 20, 'center');
【讨论】:
也许...只是为了方便,您可以阅读此jsPdf text api doc
doc.text(text, x, y, optionsopt, transform)
optionspot 是一个对象,所以你可以这样做
{align:"center"}
即:
doc.text("Hello Sun", doc.internal.pageSize.getWidth()/2, 10, { align: "center" })
其中:doc.internal.pageSize.getWidth() 是 pdf 表格的页面宽度
【讨论】:
doc.internal.pageSize.getWidth()/2做的吗?为什么要使用{ align: "center" }?