Подтвердить что ты не робот

Есть ли способ центрировать текст с помощью jsPDF?

Я пытаюсь создать простой pdf-документ с помощью javascript. Я нашел jsPDF, но я не понимаю, как центрировать текст. Возможно ли это?

4b9b3361

Ответ 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 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 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);

Ответ 2

Это работает на блокноте домашняя страница 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);
}

Ответ 3

WootWoot, на всякий случай, если вам нужно больше вариантов макета, вы также можете взглянуть на мою pdfmake библиотеку

Он поддерживает:

  • выравнивание текста, списки, поля
  • стиль (с наследованием стиля)
  • таблицы с авто/фиксированными/звездными столбцами, авто-повторными заголовками, интервалами между столбцами и строками
  • верхние и нижние колонтитулы страницы
  • вставка шрифта и несколько других опций

Он работает на стороне клиента (чистый JS) или на стороне сервера (модуль npm)

Посмотрите игровая площадка, чтобы увидеть, что возможно

Удачи.

Ответ 4

У меня была такая же проблема и много других при создании PDF файлов (например, auto-pagebreak, total-pageCount). Поэтому я начал писать небольшую библиотеку, которая зависит от jsPDF, но дает вам множество функций так, как вы их знаете (форма HTML/CSS и jQuery). Вы можете найти его на GitHub. Надеюсь, это упростит PDF-создание... =)

Ответ 5

На основе ответа @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 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

Я обнаружил, что текущая версия 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

Тот, кто ищет это, в один прекрасный день вы сможете использовать его, чтобы упростить центрирование текста.

Ответ 7

doc.text(текст, левый, верхний, "центр" ) можно использовать для центрирования текста. Его также можно использовать с массивом строк, но когда он используется с массивом, центр не работает правильно, поэтому я использовал его в цикле для каждого объекта в массиве.

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 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 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 plenty more that 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');