使用jsPDF将文本右对齐

15
我正在使用jsPDF在客户端创建PDF,我发现有一些属性可以更改文本的颜色、大小和字体,但我需要将文本对齐到右侧。这样它就会对齐到右侧坐标。有点像CSS中的text-align:right;。我该如何做呢?
谢谢。
6个回答

23

前一段时间我写了一个扩展jsPDF的程序,可以进行文本对齐(默认情况下,它使用顶部左对齐,而不是jsPDF' .text函数随机的对齐方式)。

这段代码是用TypeScript编写的(添加了一些类型注释),这应该会让您非常清楚有哪些参数。

更新:由于Kaddath的贡献(请参见他们的评论/此帖子的编辑历史记录以获取详细信息),这些片段已经被更正,可以在最新版本中正常工作,日期为2019/07/17。

var splitRegex = /\r\n|\r|\n/g;
jsPDF.API.textEx = function (text: any, x: number, y: number, hAlign?: string, vAlign?: string) {
    var fontSize = this.internal.getFontSize()
        / this.internal.scaleFactor;

    // As defined in jsPDF source code
    var lineHeightProportion = 1.15;

    var splittedText: string[];
    var lineCount: number = 1;
    if (vAlign === 'middle' || vAlign === 'bottom'
        || hAlign === 'center' || hAlign === 'right') {

        splittedText = typeof text === 'string'
        ? text.split(splitRegex)
        : text;

        lineCount = splittedText.length || 1;
    }

    // Align the top
    y += fontSize * (2 - lineHeightProportion);

    if (vAlign === 'middle') y -= (lineCount / 2) * fontSize;
    else if (vAlign === 'bottom') y -= lineCount * fontSize;


    if (hAlign === 'center'
        || hAlign === 'right') {

        var alignSize = fontSize;
        if (hAlign === 'center') alignSize *= 0.5;

        if (lineCount > 1) {
            for (var iLine = 0; iLine < splittedText.length; iLine++) {
                this.text(splittedText[iLine],
                    x - this.getStringUnitWidth(splittedText[iLine]) * alignSize,
                    y);
                y += fontSize * lineHeightProportion;
            }
            return this;
        }
        x -= this.getStringUnitWidth(text) * alignSize;
    }

    this.text(text, x, y);
    return this;
};

纯JavaScript:

var splitRegex = /\r\n|\r|\n/g;
jsPDF.API.textEx = function (text, x, y, hAlign, vAlign) {
    var fontSize = this.internal.getFontSize() / this.internal.scaleFactor;

    // As defined in jsPDF source code
    var lineHeightProportion = 1.15;

    var splittedText = null;
    var lineCount = 1;
    if (vAlign === 'middle' || vAlign === 'bottom' || hAlign === 'center' || hAlign === 'right') {
        splittedText = typeof text === 'string' ? text.split(splitRegex) : text;

        lineCount = splittedText.length || 1;
    }

    // Align the top
    y += fontSize * (2 - lineHeightProportion);

    if (vAlign === 'middle')
        y -= (lineCount / 2) * fontSize;
    else if (vAlign === 'bottom')
        y -= lineCount * fontSize;

    if (hAlign === 'center' || hAlign === 'right') {
        var alignSize = fontSize;
        if (hAlign === 'center')
            alignSize *= 0.5;

        if (lineCount > 1) {
            for (var iLine = 0; iLine < splittedText.length; iLine++) {
                this.text(splittedText[iLine], x - this.getStringUnitWidth(splittedText[iLine]) * alignSize, y);
                y += fontSize * lineHeightProportion;
            }
            return this;
        }
        x -= this.getStringUnitWidth(text) * alignSize;
    }

    this.text(text, x, y);
    return this;
};
使用它就像这样简单:
pdf.textEx('Example text', xPosition, yPosition, 'right', 'middle');

打印一段文本,其中右侧中间位于(xPosition, yPosition)。


好的,我尝试了并且它工作得很好。良好的,Aidiakapi先生。 - Sakthi Karthik
2
干得好!现在在 jspdf-autotable 插件中使用它。 - Simon Bengtsson
1
很酷,那看起来是个不错的插件,我实际上也用了这段代码来创建一个表格。 - Aidiakapi
1
能否提供一个 JSFiddle 的示例呢? - Ronald
1
太好了!但是我发现一个小矛盾:当多行文本居中或右对齐时,行之间添加的高度不足,导致文本比常规文本(左对齐)更加紧凑。应该使用 y += fontSize * lineHeightProportion; 而不是 y += fontSize; - Kaddath
显示剩余2条评论

13

截至2021年3月,您不能简单地将字符串作为对齐方式传递,您需要传递一个TextOptionsLight对象。

doc.text('My Text', 190, 20, {
    align: 'right',
});

截至[date]有点奇怪...为什么不引用一个版本呢?无论如何,我尝试了一下,对我来说不起作用。没有错误,只是对齐不好。 - Jeach
@Jeach 对齐是基于 x 坐标,y 是距离顶部的距离。例如,doc.text("Test", 200, 10, "right"); 将右对齐文本。而 doc.text("Test", 10, 10, "left"); 则左对齐文本。 - Zahir Masoodi

8

从jspdf 2.3.1版本开始,我们可以使用

doc.text("Test", 105, 10, "center"); // center align => pageWidth / 2 

//doct.text(string , x , y, alignment);

OR

doc.text("Test", 105, 10, { align : "center" }); // center align => pageWidth / 2 

排列方式是基于 x 坐标,y 坐标则表示距顶部的距离。

例如,doc.text("Test", 200, 10, "right"); 会将文本右对齐, 而 doc.text("Test", 10, 10, "left"); 则会将文本左对齐。


0

2022(版本 2.5.1)

可以看到一些有意的错误,以突出当前语法的怪异之处。

我使用 aBox = width 来设置右边距,然后任何放置在右对齐的语言文本都将是内联的。

然而,作为非阿拉伯人,我写反了,所以上面的“右边”文本显示 R2L(false),但 R2L(true) 明显不是“你好,世界”或真正的“مرحبا بالعالم”。

enter image description here


0

我正在使用 jspdf: "^1.3.5" 和 jspdf-autotable: "^2.3.2"

我遇到了麻烦,因为 jspdf 文档和 jspdf 插件源 js 文件之间存在同步问题。在我的情况下,由于按照文档没有任何作用,我进行了反向工程,并按照源文件编写了以下可行代码:

    doc.autoTable(
          ['Date', 'Particulars', 'Company','Quantity', 'Rate', 'Debit', 'Credit', 'Balance']
        , 
        jsonArray ,
        {
          styles: {
            fontSize: 10
          },
          startY: 15,
          columnStyles: [
            {halign: "left" },
            {halign: "left" },
            {halign: "left" },
            {halign: "center" },
            {halign: "right" },
            {halign: "right" },
            {halign: "right" },
            {halign: "right" },
           
          ]
        }
        ) 

我必须为每一列设置样式。


0

对于 TypeScript / Angular,可以将其用作模型:

import { Font, jsPDF } from 'jspdf';


                    /**
                     * PDF text alignment test
                     */
export function pdfTest() {
                    // the pdfDocCfg base object
  const pdfDocCfg: PDFdocCfg_I = {
    jsPdfHtmlOptions: {},
    jsPdfOptions:     {
      unit: 'pt'
    },
    jsPdfDocProps:    {},
    autoTableOpt:     {},
    dataRowInfo:      {},
    margins_pt:       {top:   36,  // 36 pt = 0.5 in = 1.27 cm
                      bottom: 36,
                      left:   36,
                      right:  36},
    pageHeight: 0,
    lastRowPos: 0
  }
                    // create new jsPDF API object instance
                    // that we use to generate the PDF doc.
  const docPdf: jsPDF = new jsPDF(pdfDocCfg.jsPdfOptions);

  const pageLeft: number   = 10;
  const pageWidth: number  = docPdf.internal.pageSize.width;
  const pageHorizCenter: number = pageWidth / 2;

  // docPdf.setFont('times');
  // docPdf.setFontType('normal');
  let row: number        = 20;
  let nextRowPos: number =  0;

  docPdf.text('This is centred text 1.',                 pageHorizCenter, (nextRowPos += row),  {align: 'center'});
  docPdf.text('This is centred text 2.',                 pageHorizCenter, (nextRowPos += row),  {align: 'center'});
  docPdf.text('This is right aligned text 1',            pageWidth,       (nextRowPos += row),  {align: 'right'});
  docPdf.text('This is right aligned text 2',            pageWidth,       (nextRowPos += row),  {align: 'right'});
  docPdf.text('This is left aligned text 1 - default',   pageLeft,        (nextRowPos += row));
  docPdf.text('This is left aligned text 2 - explicit',  pageLeft,        (nextRowPos += row),  {align: 'left'});

  docPdf.save();

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接