web-dev-qa-db-fra.com

Existe-t-il un moyen de centrer le texte avec jsPDF?

J'essaie de créer un document pdf simple en utilisant javascript. J'ai trouvé jsPDF mais je ne sais pas comment centrer le texte. C'est possible?

32
Dev01

Oui c'est possible. Vous pouvez écrire une méthode de plugin jsPDF à utiliser.

Un exemple rapide est le suivant:

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

Et vous l'utilisez comme ça

var doc = new jsPDF('p','in');
doc.text("Left aligned text",0.5,0.5);
doc.myText("Centered text",{align: "center"},0,1);
59
Tsilis

Cela fonctionne dans le bloc-notes sur la page d'accueil 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);
}
26
sjy

J'ai trouvé que la version actuelle de jsPdf prend en charge un paramètre 'align' avec la signature de fonction comme ceci:

API.text = function (text, x, y, flags, angle, align)

Donc, ce qui suit devrait vous donner un texte aligné au centre:

doc.text('The text', doc.internal.pageSize.width, 50, null, null, 'center');

Cependant, à l'heure actuelle, une erreur est lancée dans la bibliothèque lorsque le mode strict est activé car un "var" est manquant. Il existe un problème et une demande d'extraction, mais le correctif ne l'a pas fait dans: https://github.com/MrRio/jsPDF/issues/575

Quiconque le recherche, un jour, vous pourrez peut-être l'utiliser pour faciliter le centrage du texte.

8
Ben

WootWoot, juste au cas où vous auriez besoin de plus d'options de mise en page, vous pouvez également jeter un œil à ma bibliothèque pdfmake

Ça supporte:

  • alignements de texte, listes, marges
  • style (avec héritage de style)
  • tables avec colonnes de taille auto/fixe/étoile, en-têtes à répétition automatique, étendues col/ligne
  • en-têtes et pieds de page
  • incorporation de polices et quelques autres options

Il fonctionne côté client (JS pur) ou côté serveur (un module npm)

Jetez un oeil à le terrain de je pour voir ce qui est possible

Bonne chance

7
bartekp

J'ai eu le même problème et beaucoup d'autres lors de la création de fichiers PDF (par exemple, auto-pagebreak, total-pageCount). J'ai donc commencé à écrire une petite lib, qui dépend de jsPDF mais vous donne beaucoup de fonctionnalités d'une manière que vous les connaissez (formulaire HTML/CSS et jQuery). Vous pouvez le trouver sur GitHub . J'espère que cela facilite la création de PDF ... =)

3
platdesign

Sur la base de la réponse de @Tsilis, j'ai extrait un plugin ici https://Gist.github.com/Purush0th/7fe8665bbb04482a0d8 qui peut aligner le texte gauche, droite et centre dans la largeur de conteneur de texte donnée.

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

Utilisation

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});
3
Purushoth

doc.text (text, left, top, 'center') peut être utilisé pour centrer le texte. Il peut également être utilisé avec un tableau de lignes, mais lorsqu'il est utilisé avec un tableau, le centre ne fonctionne pas correctement, je l'ai donc utilisé en boucle pour chaque objet du tableau.

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