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

Dev*_*v01 33 javascript jspdf

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

小智 60

是的,这是可能的.您可以编写一个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);
Run Code Online (Sandbox Code Playgroud)

你就这样使用它

var doc = new jsPDF('p','in');
doc.text("Left aligned text",0.5,0.5);
doc.myText("Centered text",{align: "center"},0,1);
Run Code Online (Sandbox Code Playgroud)


sjy*_*sjy 26

这适用于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);
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 8

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

API.text = function (text, x, y, flags, angle, align)
Run Code Online (Sandbox Code Playgroud)

因此,以下内容应该为您提供中心对齐的文本:

doc.text('The text', doc.internal.pageSize.width, 50, null, null, 'center');
Run Code Online (Sandbox Code Playgroud)

但是,在当前时间点,当启用严格模式时,库中会抛出错误,因为缺少"var".有一个问题和拉取请求,但修复程序没有进入:https: //github.com/MrRio/jsPDF/issues/575

无论是谁在寻找这个,有一天,你可能能够使用它来更容易中心文本.

  • 尽管这个答案没有像当前版本的`jspdf`所描述的那样有效,但它确实指出了我正确的方向.唯一的区别是需要使用`doc.internal.pageSize.getWidth()/ 2`而不是`doc.internal.pageSize.width`. (4认同)

小智 7

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

它支持:

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

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

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

祝好运