lib example descargar carta align javascript jspdf

javascript - example - jspdf table



¿Hay alguna manera de centrar el texto con jsPDF? (7)

Basado en la respuesta de @Tsilis, tengo un fragmento aquí https://gist.github.com/Purush0th/7fe8665bbb04482a0d80 que puede alinear el texto a la izquierda, a la derecha y al centro en el ancho del contenedor de texto dado.

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

Uso

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

Estoy tratando de crear un documento pdf simple usando javascript. Encontré jsPDF pero no entiendo cómo centrar el texto. ¿Es posible?


Descubrí que la versión actual de jsPdf admite un parámetro ''alinear'' con la firma de función como esta:

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

Así que lo siguiente debería darle un texto alineado en el centro:

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

Sin embargo, en el momento actual, se produce un error en la biblioteca cuando el modo estricto está activado porque falta una ''var''. Hay un problema y una solicitud de extracción, pero la solución no se ha realizado en: https://github.com/MrRio/jsPDF/issues/575

Quienquiera que esté buscando esto, un día, podrías usarlo para que sea más fácil centrar el texto.


Esto funciona en el bloc de notas en la página de inicio de 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); }


Se puede usar doc.text (texto, izquierda, arriba, ''centro'') para centrar el texto. También se puede usar con una matriz de líneas, pero cuando se usa con una matriz, el centro no funciona bien, así que lo he usado en un bucle para cada objeto de la matriz.

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


Si es posible. Podrías escribir un método de plugin jsPDF para usar.

Un ejemplo rápido es este:

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

Y lo usas asi

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


Tuve el mismo problema y muchos otros al crear archivos PDF (p. Ej., Salto de página automático, cuenta total de páginas). Así que empecé a escribir un poco de lib, que depende de jsPDF pero te da muchas características de una manera que las conoces (formulario HTML / CSS y jQuery). Lo puedes encontrar en GitHub . Espero que facilite la creación de PDF ... =)


WootWoot, en caso de que necesite más opciones de diseño, también puede echar un vistazo a mi biblioteca de pdfmake

Es compatible con:

  • Alineaciones de texto, listas, márgenes.
  • estilismo (con herencia de estilo)
  • tablas con columnas automáticas / fijas / de tamaño estrella, encabezados repetidos automáticamente, col / row spans
  • encabezados y pies de página
  • incrustación de fuentes, y un par de otras opciones

Funciona en el lado del cliente (JS puro) o en el lado del servidor (un módulo npm)

Echa un vistazo al patio de recreo para ver qué es posible.

Buena suerte