当前位置: > > > JS - PDF文件生成库jsPDF使用详解2(修改文字样式)

JS - PDF文件生成库jsPDF使用详解2(修改文字样式)

三、修改文字样式

1,修改字体大小

var doc = new jsPDF();
//字体大小1(默认样式)
doc.text(20, 20, '1: Welcome to hangge.com');

//字体大小2
doc.setFontSize(18);
doc.text(20, 30, '2: Welcome to hangge.com');

//字体大小3
doc.setFontSize(22);
doc.text(20, 40, '3: Welcome to hangge.com');

doc.save('Test.pdf');

2,修改文字颜色

var doc = new jsPDF();
//文字颜色1(默认样式)
doc.text(20, 20, '1: Welcome to hangge.com');

//文字颜色2
doc.setTextColor(150);
doc.text(20, 30, '2: Welcome to hangge.com');

//文字颜色3
doc.setTextColor(0,0,255);
doc.text(20, 40, '3: Welcome to hangge.com');

doc.save('Test.pdf');

3,修改字体样式

var doc = new jsPDF();
//字体样式1(默认样式)
doc.text(20, 20, '1: Welcome to hangge.com');

//字体样式2
doc.setFont("courier");
doc.setFontType("normal");
doc.text(20, 30, '2: Welcome to hangge.com');

//字体样式3
doc.setFont("times");
doc.setFontType("italic");
doc.text(20, 40, '3: Welcome to hangge.com');

//字体样式4
doc.setFont("helvetica");
doc.setFontType("bold");
doc.text(20, 50, '4: Welcome to hangge.com');

//字体样式5
doc.setFont("courier");
doc.setFontType("bolditalic");
doc.text(20, 60, '5: Welcome to hangge.com');

doc.save('Test.pdf');

4,文字旋转

var doc = new jsPDF();
//默认样式不选旋转
doc.text(20, 20, '1: Welcome to hangge.com');

//旋转45度
doc.text(20, 80, '2: Welcome to hangge.com', 45);

//旋转90度
doc.text(120, 80, '3: Welcome to hangge.com', 90);

doc.save('Test.pdf');

5,文字换行显示

(1)我们使用换行符(\r)可以手动让文字换行。
var doc = new jsPDF();
doc.text(20, 20, 'Welcome to hangge.com.\rWelcome to hangge.com.\rWelcome to hangge.com.');
doc.save('Test.pdf');

(2)默认情况下,文字超过页面宽度时默认是不会自动换行的,我们可以通过其内置的方法将文字自动拆成多行再渲染。
var doc = new jsPDF('p','in','letter');
var sizes = [12, 16, 20];
var fonts = [['Times','Roman'],['Helvetica',''], ['Times','Italic']];
var verticalOffset = 0.5;
var words = 'Welcome to hangge.com. Welcome to hangge.com. Welcome to hangge.com.'

for (var i in fonts){
    if (fonts.hasOwnProperty(i)) {
        var font = fonts[i]
        var size = sizes[i]

        //将文字自动换行显示
        lines = doc.setFont(font[0], font[1])
                    .setFontSize(size)
                    .splitTextToSize(words, 7.5)
        doc.text(0.5, verticalOffset + size / 72, lines)

        verticalOffset += (lines.length + 0.5) * size / 72
    }
}

doc.save('Test.pdf');

6,文字对齐方式

var doc = new jsPDF('p', 'pt', 'letter');

doc.text( '1: This text is normally\raligned.', 140, 50 );

doc.text( '2: This text is centered\raround\rthis point.', 140, 120, 'center' );

doc.text( '3: This text is rotated\rand centered around\rthis point.', 140, 300, 45, 'center' );

doc.text( '4: This text is\raligned to the\rright.', 140, 400, 'right' );

doc.text( '5: This text is\raligned to the\rright.', 140, 550, 45, 'right' );

doc.text( '6: This single line is centered', 460, 50, 'center' );

doc.text( '7: This right aligned text\r\rhas an empty line.', 460, 200, 'right' );

doc.save('Test.pdf');
评论0