【问题标题】:Is there any way to center text with jsPDF?有没有办法用 jsPDF 使文本居中?
【发布时间】:2014-01-30 09:41:15
【问题描述】:

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

【问题讨论】:

  • Tsilis 的回答应该被接受,因为它解决了 OP 的问题并且是最佳答案
  • @HaithamMaaieh 完成。

标签: javascript jspdf


【解决方案1】:

是的,这是可能的。您可以编写一个 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 ) );
  • @MrHunter 你能告诉我右对齐文本的完整代码吗
  • @AshokShah 与上面的代码完全相同,只是将x = ( pageWidth - txtWidth ) / 2; 替换为我提供的代码。
  • 非常感谢您提供的方法,但如果 txtWidth 与 pageWidth 相似,则该等式并不总是有效。正确的公式是 x = pageWidth - (txtWidth / 2),顺便说一下,您可以将 pageWidth 替换为任何给定的 x 偏移量。
【解决方案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);
}

【讨论】:

  • 感谢您的回答,Tsilis 的那个稍微好一点。
【解决方案3】:

我发现当前版本的 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
  • @JakeHolzinger 的评论确实对我有用。我使用了 doc.internal.pageSize.getWidth() + {align: 'center'} 效果很好
【解决方案4】:

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

它支持:

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

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

看看the playground 看看有什么可能

祝你好运

【讨论】:

  • 所以没有 CSS 支持?
  • 虽然不是对 OP 的回答,但这是一个更易于使用的库,并提供了大多数人想要的功能。
【解决方案5】:

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

【讨论】:

  • 谢谢!看起来很棒!我不得不把我项目的 PDF 部分放在一边,我现在才回到它。我只是看了你的例子jsfiddle.net/GE6QV/6,它看起来真的很容易使用。谢谢!
  • 谢谢。 =) 它确实处于早期阶段,但它会获得更多功能,因为我自己需要它;) 如果您有任何问题或建议,请告诉我。 :)
【解决方案6】:

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

【讨论】:

  • 像魅力一样工作。谢谢:)
  • 当你在Angular中使用jsPDF时如何使用这个插件?我需要在某处创建一个 *.js 文件吗?我没有找到关于 jsPDF 插件的任何信息。
【解决方案7】:

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');

【讨论】:

    【解决方案8】:

    这样做:

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

    【讨论】:

    • 你好@7guyo 请避免发布原始代码 sn-ps 作为问题的答案。至少添加一些解释。
    【解决方案9】:

    也许...只是为了方便,您可以阅读此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" }
    • @BorisBELLOC 我认为文本将从宽度的中心开始向右。在这种情况下,文本仍然没有居中。它只从中心开始向右移动。
    猜你喜欢
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2016-05-05
    • 2018-05-16
    • 1970-01-01
    • 2012-02-06
    相关资源
    最近更新 更多