有没有办法用jsPDF居中文本?

时间:2014-01-11 09:55:14

标签: javascript jspdf

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

9 个答案:

答案 0 :(得分:58)

是的,这是可能的。您可以编写一个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);

答案 1 :(得分:25)

这适用于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);
}

答案 2 :(得分:7)

WootWoot,如果您需要更多布局选项,还可以查看我的pdfmake

它支持:

  • 文字对齐,列表,边距
  • 样式(具有样式继承)
  • 包含自动/固定/星号大小的列,自动重复标题,col / row spans
  • 的表格
  • 页眉和页脚
  • 字体嵌入,以及其他几个选项

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

查看the playground以查看可能的内容

祝你好运

答案 3 :(得分:6)

我发现当前版本的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

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

答案 4 :(得分:3)

创建PDF文件时我遇到了同样的问题和很多其他问题(例如auto-pagebreak,total-pageCount)。所以我开始编写一个小lib,它依赖于jsPDF,但以你熟悉它们的方式(形式HTML / CSS和jQuery)为你提供了很多功能。您可以在GitHub找到它。我希望它能让PDF创建变得更容易...... =)

答案 5 :(得分:3)

根据@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});

答案 6 :(得分: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');

答案 7 :(得分:1)

这样做:

首先获取页面宽度,获取页面宽度的一半并将其用作 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');

答案 8 :(得分:0)

也许...只是为了简便,您可以阅读此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表格的页面宽度