37

我正在尝试使用 javascript 创建一个简单的 pdf 文档。我找到了 jsPDF,但我不知道如何使文本居中。是否可以?

4

9 回答 9

68

是的,这是可能的。您可以编写一个 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);
于 2014-01-31T18:11:54.493 回答
40

这适用于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);
}
于 2014-01-31T03:25:43.583 回答
12

我发现当前版本的 jsPdf 支持带有函数签名的参数“对齐”,如下所示:

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

无论谁正在寻找这个,总有一天,你也许可以使用它来更容易地将文本居中。

于 2016-07-07T12:21:57.787 回答
8

WootWoot,以防万一您需要更多布局选项,您还可以查看我的pdfmake

它支持:

  • 文本对齐、列表、边距
  • 样式(带有样式继承)
  • 具有自动/固定/星号大小的列、自动重复标题、列/行跨度的表
  • 页眉和页脚
  • 字体嵌入和其他几个选项

它适用于客户端(纯 JS)或服务器端(一个 npm 模块)

看看操场,看看有什么可能

祝你好运

于 2014-05-15T00:09:43.620 回答
4

在创建 PDF 文件(例如自动分页符、总页数)时,我遇到了同样的问题和很多其他问题。所以我开始编写一个小库,它依赖于 jsPDF,但以你知道的方式(从 HTML/CSS 和 jQuery)为你提供了很多特性。你可以在GitHub 上找到它。我希望它使 PDF 创建更容易... =)

于 2014-05-09T00:23:16.933 回答
4

根据@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});
于 2016-03-07T09:39:34.680 回答
2

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');
于 2017-09-16T08:31:09.147 回答
2

做这个:

首先获取页面宽度,获取页面宽度的一半并将其用作 x 值,使用您选择的 y 值并将 center 作为第三个参数传递给您的文本居中。 从文档中阅读更多信息

let doc = new jsPDF();
let pageWidth = doc.internal.pageSize.getWidth();
doc.text("My centered text",pageWidth / 2, 20, 'center');
于 2020-12-29T18:35:23.303 回答
1

也许......只是为了简单起见,您可以阅读这个jsPdf text api doc

doc.text(text, x, y, optionsopt, transform) 

其中 optionspot 是一个对象,所以你可以这样做

{align:"center"}

IE:

doc.text("Hello Sun", doc.internal.pageSize.getWidth()/2, 10, { align: "center" })

其中:doc.internal.pageSize.getWidth()是 pdf 表的页面宽度

于 2019-12-17T15:46:18.703 回答