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

j'essaie de créer un simple pdf doc en utilisant javascript. J'ai trouvé jsPDF mais je ne trouve pas comment centrer le texte. Est-il possible?

27
demandé sur sjy 2014-01-11 13:55:14

7 réponses

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

Un exemple rapide est ceci:

    (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 ceci

var doc = new jsPDF('p','in');
doc.text("Left aligned text",0.5,0.5);
doc.myText("Centered text",{align: "center"},0,1);
50
répondu Tsilis 2014-02-24 03:27:14

Cela fonctionne dans le pavé sur le page d'accueil du 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);
}
22
répondu sjy 2014-06-03 21:09:38

WootWoot, juste au cas où vous avez besoin de plus d'options de mise en page, vous pouvez également prendre un coup d'oeil à mon pdfmake bibliothèque

Il prend en charge:

  • alignements de texte, listes, marges
  • style (le style de l'héritage)
  • tables avec auto/fixe/étoile de la taille des colonnes, des auto-répété-têtes, col/ligne s'étend sur
  • page les en-têtes et pieds de page
  • intégration de la police, et quelques autres options

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

regardez l'aire de jeux pour voir ce qui est possible

Bonne chance

6
répondu bartekp 2014-05-15 00:09:43

j'ai trouvé que la version actuelle de jsPdf supporte un paramètre' align ' avec la fonction signature comme ceci:

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

ainsi, le texte suivant 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 quand le mode strict est activé parce qu'il manque un 'var'. Il ya un problème et tirer la demande pour elle, mais le correctif n'a pas fait dans: https://github.com/MrRio/jsPDF/issues/575

qui que ce soit qui cherche cela, un jour, vous pourrez peut-être vous en servir pour faciliter le centrage du texte.

4
répondu Ben 2016-07-07 12:21:57

j'ai eu le même problème et beaucoup d'autres en créant des fichiers PDF (par exemple auto-pagebreak, total-pageCount). J'ai donc commencé à écrire un petit lib, qui dépend de jsPDF mais qui vous donne beaucoup de fonctionnalités d'une façon que vous connaissez (forme HTML/CSS et jQuery). Vous pouvez le trouver sur GitHub. J'espère que cela facilitera la création de PDF... =)

3
répondu platdesign 2014-05-09 00:23:16

@Tsilis réponse que j'ai extrait d'un plugin ici https://gist.github.com/Purush0th/7fe8665bbb04482a0d80 qui peut aligner le texte gauche, droite et centre dans le texte donné largeur du conteneur.

(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
répondu Purushoth 2016-03-07 09:39:34

doc.texte(texte,à gauche,en haut,'centre') peut être utilisé pour centrer le texte. Il peut être utilisé avec un tableau de lignes, mais lorsqu'il est utilisé avec le tableau le centre ne fonctionne pas donc je l'ai utilisée dans une boucle pour chaque objet dans le 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');
1
répondu Saifee 2017-09-16 08:31:09