Git Product home page Git Product logo

jspdf-autotable's Introduction

jsPDF-AutoTable - Table plugin for jsPDF

Generate PDF tables with Javascript

This jsPDF plugin adds the ability to generate PDF tables either by parsing HTML tables or by using Javascript data directly. Check out the demo or examples.

sample javascript table pdf

Installation

Get jsPDF and this plugin by doing one of these things:

Usage

import jsPDF from 'jspdf'
import autoTable from 'jspdf-autotable'

const doc = new jsPDF()

// It can parse html:
// <table id="my-table"><!-- ... --></table>
autoTable(doc, { html: '#my-table' })

// Or use javascript directly:
autoTable(doc, {
  head: [['Name', 'Email', 'Country']],
  body: [
    ['David', '[email protected]', 'Sweden'],
    ['Castille', '[email protected]', 'Spain'],
    // ...
  ],
})

// Sometimes you might have to call the default function on the export (for example in Deno)
autoTable.default(doc, { html: '#my-table' })

doc.save('table.pdf')

You can also use the plugin methods directly on the jsPDF documents:

import jsPDF from 'jspdf'
import 'jspdf-autotable'

const doc = new jsPDF()
doc.autoTable({ html: '#my-table' })
doc.save('table.pdf')

The third usage option is with downloaded or CDN dist files

<script src="jspdf.min.js"></script>
<script src="jspdf.plugin.autotable.min.js"></script>
<script>
  var doc = new jsPDF()
  doc.autoTable({ html: '#my-table' })
  doc.save('table.pdf')
</script>

Checkout more examples in examples.js which is also the source code for the demo documents.

Options

Below is a list of all options supported in the plugin. All of them are used in the examples.

Content options

The only thing required is either the html or body option. If you want more control over the columns you can specify the columns property. If columns are not set they will be automatically computed based on the content of the html content or head, body and foot.

  • html: string|HTMLTableElement A css selector (for example "#table") or an html table element.
  • head: CellDef[][] For example [['ID', 'Name', 'Country']]
  • body: CellDef[][] For example [['1', 'Simon', 'Sweden'], ['2', 'Karl', 'Norway']]
  • foot: CellDef[][] For example [['ID', 'Name', 'Country']]
  • columns: ColumnDef[] For example [{header: 'ID', dataKey: 'id'}, {header: 'Name', dataKey: 'name'}]. Only use this option if you want more control over the columns. If not specified the columns will be automatically generated based on the content in html or head/body/foot
  • includeHiddenHtml: boolean = false If hidden html with display: none should be included or not when the content comes from an html table

CellDef: string|{content: string, rowSpan: number, colSpan: number, styles: StyleDef} Note that cell styles can also be set dynamically with hooks.

ColumnDef: string|{header?: string, dataKey: string} The header property is optional and the values of any content in head will be used if not set. Normally it's easier to use the html or head/body/foot style of initiating a table, but columns can be useful if your body content comes directly from an api or if you would like to specify a dataKey on each column to make it more readable to style specific columns in the hooks or columnStyles.

Usage with colspan, rowspan and inline cell styles:

autoTable(doc, {
  body: [
    [{ content: 'Text', colSpan: 2, rowSpan: 2, styles: { halign: 'center' } }],
  ],
})

Styling options

  • theme: 'striped'|'grid'|'plain' = 'striped'
  • styles: StyleDef
  • headStyles: StyleDef
  • bodyStyles: StyleDef
  • footStyles: StyleDef
  • alternateRowStyles: StyleDef
  • columnStyles: {&columnDataKey: StyleDef} Note that the columnDataKey is normally the index of the column, but could also be the dataKey of a column if content initialized with the columns property

StyleDef:

  • font: 'helvetica'|'times'|'courier' = 'helvetica'
  • fontStyle: 'normal'|'bold'|'italic'|'bolditalic' = 'normal'
  • overflow: 'linebreak'|'ellipsize'|'visible'|'hidden' = 'linebreak'
  • fillColor: Color? = null
  • textColor: Color? = 20
  • cellWidth: 'auto'|'wrap'|number = 'auto'
  • minCellWidth: number? = 10
  • minCellHeight: number = 0
  • halign: 'left'|'center'|'right' = 'left'
  • valign: 'top'|'middle'|'bottom' = 'top'
  • fontSize: number = 10
  • cellPadding: Padding = 10
  • lineColor: Color = 10
  • lineWidth: border = 0 // If 0, no border is drawn

Color: Either false for transparent, hex string, gray level 0-255 or rbg array e.g. [255, 0, 0] false|string|number|[number, number, number]

Padding: Either a number or object {top: number, right: number, bottom: number, left: number}

border: Either a number or object {top: number, right: number, bottom: number, left: number}

Styles work similar to css and can be overridden by more specific styles. Overriding order:

  1. Theme styles
  2. styles
  3. headStyles, bodyStyles and footStyles
  4. alternateRowStyles
  5. columnStyles

Styles for specific cells can also be applied using either the hooks (see hooks section above) or the styles property on the cell definition object (see content section above).

Example usage of column styles (note that the 0 in the columnStyles below should be dataKey if columns option used)

// Example usage with columnStyles,
autoTable(doc, {
  styles: { fillColor: [255, 0, 0] },
  columnStyles: { 0: { halign: 'center', fillColor: [0, 255, 0] } }, // Cells in first column centered and green
  margin: { top: 10 },
  body: [
    ['Sweden', 'Japan', 'Canada'],
    ['Norway', 'China', 'USA'],
    ['Denmark', 'China', 'Mexico'],
  ],
})

// Example usage of columns property. Note that America will not be included even though it exist in the body since there is no column specified for it.
autoTable(doc, {
  columnStyles: { europe: { halign: 'center' } }, // European countries centered
  body: [
    { europe: 'Sweden', america: 'Canada', asia: 'China' },
    { europe: 'Norway', america: 'Mexico', asia: 'Japan' },
  ],
  columns: [
    { header: 'Europe', dataKey: 'europe' },
    { header: 'Asia', dataKey: 'asia' },
  ],
})

Other options

  • useCss: boolean = false
  • startY: number = null Where the table should start to be printed (basically a margin top value only for the first page)
  • margin: Margin = 40
  • pageBreak: 'auto'|'avoid'|'always' If set to avoid the plugin will only split a table onto multiple pages if table height is larger than page height.
  • rowPageBreak: 'auto'|'avoid' = 'auto' If set to avoid the plugin will only split a row onto multiple pages if row height is larger than page height.
  • tableWidth: 'auto'|'wrap'|number = 'auto'
  • showHead: 'everyPage'|'firstPage'|'never' = 'everyPage''
  • showFoot: 'everyPage'|'lastPage'|'never' = 'everyPage''
  • tableLineWidth: number = 0
  • tableLineColor: Color = 200 The table line/border color
  • horizontalPageBreak: boolean = false To split/break the table into multiple pages if the given table width exceeds the page width
  • horizontalPageBreakRepeat: string|number|string[]|number[] To repeat the given column in the split pages, works when horizontalPageBreak = true. The accepted values are column dataKeys, such as 'id', recordId or column indexes, such as 0, 1 or array for multiple columns.
  • horizontalPageBreakBehaviour: 'immediately'|'afterAllRows' = 'afterAllRows' How the horizontal page breaks behave, works when horizontalPageBreak = true

Margin: Either a number or object {top: number, right: number, bottom: number, left: number}

Hooks

You can customize the content and styling of the table by using the hooks. See the custom styles example for usage of the hooks.

  • didParseCell: (HookData) => {} - Called when the plugin finished parsing cell content. Can be used to override content or styles for a specific cell.
  • willDrawCell: (HookData) => {} - Called before a cell or row is drawn. Can be used to call native jspdf styling functions such as doc.setTextColor or change position of text etc before it is drawn.
  • didDrawCell: (HookData) => {} - Called after a cell has been added to the page. Can be used to draw additional cell content such as images with doc.addImage, additional text with doc.addText or other jspdf shapes.
  • willDrawPage: (HookData) => {} - Called before starting to draw on a page. Can be used to add headers or any other content that you want on each page there is an autotable.
  • didDrawPage: (HookData) => {} - Called after the plugin has finished drawing everything on a page. Can be used to add footers with page numbers or any other content that you want on each page there is an autotable.

All hooks functions get passed an HookData object with information about the state of the table and cell. For example the position on the page, which page it is on etc.

HookData:

  • table: Table
  • pageNumber: number The page number specific to this table
  • settings: object Parsed user supplied options
  • doc The jsPDF document instance of this table
  • cursor: { x: number, y: number } To draw each table this plugin keeps a cursor state where the next cell/row should be drawn. You can assign new values to this cursor to dynamically change how the cells and rows are drawn.

For cell hooks these properties are also passed:

  • cell: Cell
  • row: Row
  • column: Column
  • section: 'head'|'body'|'foot'

To see what is included in the Table, Row, Column and Cell types, either log them to the console or take a look at src/models.ts

// Example with an image drawn in each cell in the first column
autoTable(doc, {
  didDrawCell: (data) => {
    if (data.section === 'body' && data.column.index === 0) {
      var base64Img = 'data:image/jpeg;base64,iVBORw0KGgoAAAANS...'
      doc.addImage(base64Img, 'JPEG', data.cell.x + 2, data.cell.y + 2, 10, 10)
    }
  },
})

API

  • doc.autoTable({ /* options */ })
  • autoTable(doc, { /* options */ })
  • jsPDF.autoTableSetDefaults({ /* ... */ }) Use for setting global defaults which will be applied for all tables

If you want to know something about the last table that was drawn you can use doc.lastAutoTable. It has a doc.lastAutoTable.finalY property among other things that has the value of the last printed y coordinate on a page. This can be used to draw text, multiple tables or other content after a table.

In addition to the exported autoTable(doc, options) method you can also use applyPlugin to add the autoTable api to any jsPDF instance.

import jsPDF from 'jspdf/dist/jspdf.node.debug'
import { applyPlugin } from 'jspdf-autotable'
applyPlugin(jsPDF)

Contributions

Contributions are always welcome, especially on open issues. If you have something major you want to add or change, please post an issue about it first to discuss it further. The workflow for contributing would be something like this:

  • Start watcher with npm start
  • Make code changes
  • Make sure all examples works
  • Commit and submit pull request

If you don't use Prettier on autosave, please run yarn run format-all before opening your PR

Release workflow

Pull requests locally

  • PR=472 npm run checkout-pr

Release prerelease

  • npm version prerelease
  • git push && git push --tags && npm publish --tag alpha

jspdf-autotable's People

Contributors

alanhilal avatar apancutt avatar arunlalkp avatar chip avatar dependabot[bot] avatar elkhorn360 avatar gitmycode avatar gordianschuda avatar kuzdogan avatar longzheng avatar martin-robot avatar mcshaz avatar micksp avatar mikedabrowski avatar mmghv avatar naorpeled avatar npgeomap avatar ocadoret avatar pmstss avatar probablykasper avatar prpateldev avatar qlum avatar rarysson avatar rileydavidson-evans avatar robinsone avatar rong4188 avatar simonbengtsson avatar singhinderpal avatar tarekis avatar z3ntu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jspdf-autotable's Issues

Double table in a PDF file

Hello, I need to enter two tables in a PDF file, and I wrote the following code, only it does not work very well. Why Writes the second table, between the second and the last line of the first table
document-0
document-1

Why?
My code:

        function generatefromtable(intestazione) {
            try{
                var $ret=true;
                var totalPagesExp = "{total_pages_count_string}";
                //var doc = new jsPDF('p', 'pt');
                var doc = new jsPDF('l', 'pt', 'a4', true); 
                var header = function (doc, pageCount, options) {
                doc.setFontSize(20);
                doc.text(intestazione, options.margins.horizontal, 60);
                doc.setFontSize(options.fontSize);
                };

                var footer = function (doc, lastCellPos, pageCount, options) {
                var str = " " + pageCount + "/" + totalPagesExp;
                doc.text(str, options.margins.horizontal, doc.internal.pageSize.height - 30);
                };
                var options = {renderHeader: header, renderFooter: footer, margins: {horizontal: 40, top: 80, bottom: 50}};    

                // Be sure to set the second parameter (indexBased option) to true
                // It will be the default behavior in v2.0, but are now behind an option for compatibility
                var res = doc.autoTableHtmlToJson(document.getElementById("tbl"), true);
                doc.autoTable(res.columns, res.data, options);

                var res2 = doc.autoTableHtmlToJson(document.getElementById("tbl_resoconto"), true);
                doc.autoTable(res2.columns, res2.data, options);

                doc.putTotalPages(totalPagesExp);

                doc.output("dataurlnewwindow");

            }catch(err) {
                    //err.message per avere il testo del messaggio
                ret=false;
            }

            return ret;
        }

beforeRenderHeader hook

not an issue but wanted to comment on something. the page split works beautifully but in my scenario i have to write some text before the table and in order to include this extra text in the page split i created a beforeRenderHeader method which takes in the doc and lastColPos.

could be handy!

Table header is wrapping the text, but its not the word wrap

In my table in the PDF, The Table header does wrap the text after version 1.3.2 but still it is not the complete word wrap. I would really appreciate if some assistance can be provided for this at the earliest.

For example the problem is , If Table column is "Record No." , Its shows Reco in one line and the rest in other. If "Manufacturer" is the text than it show Manufac in one line, rest in other line.

Word wrap in cell

Hi,
How can i implement wrapping in long sentences. Line height is not a problem.

For Ionic App

Hello,

I have problem when making an ionic app with jspdf plugin to generate a PDF file. Before I use this plugin, could this plugin support custom table like my concept?

Thanks before

columns data trucated html table to pdf

Hi,

I could not get overflow: linebreak to work for me. I have data as HTML, I convert it to json using autoTableHtmlToJson and then use autoTable to generate the PDF.

For example:

var res = doc.autoTableHtmlToJson(document.getElementById("basic-table"), true);

doc.autoTable(res.columns, res.data, {margins: {horizontal: 10, top: 40, bottom: 40}, startY: 370, overflow: 'linebreak', overflowColumns: false});

publish(doc.output('datauristring'));

But the column data gets truncated instead of getting word wrapped. How to achieve it?

Respect HTML cell width

Hi,

I recently ran by this project which looked like it would fit my needs, but now i hit a wall when I am trying to generate a tabel from HTML code.

I'm generating a table from a list of materials and at the bottom I would like a total-line, which sums it all up. Every element consists of a type, descrtiption, unit, amount, price and I would like the sum to lokke like this:

http://puu.sh/j7oAi/2c864c7e5a.png

But end up with:

http://puu.sh/j7oBM/e97d392266.png

Is it possible for it to respect the widths specified in the HTML code, or some other way aorund this?

Thanks

Specific column format

Hello!

I'm wondering if there is a simple way to give a specific format to only one column of the table (apply bold font for example or add red background) ?

And keep the good work! Lovin' this plugin the more I use it!

Problem with long json

Hi
i've a problem with long json text who render strange table

for example:
example file example.js on Overflow 'linebreak'
in line 315 if you change var sentence = faker.lorem.words(52); -> var sentence = faker.lorem.words(252);
you will have a table with a empty at the beginning
and sometime data in cell are desynchronise.
any ideas?
thanks

How to add page header with addHTML ?

I tried to add header in PDF pages with the addHTML() jsPDF function, but this not works, this is my code:

        var totalPagesExp = "{total_pages_count_string}";
    var doc = new jsPDF('p', 'pt');

    var htmlHeader = $(".report-container header")[0];

    var header = function (docPage, pageCount, options) {

        docPage.addHTML(htmlHeader, null, function(){

        });
    };

    var footer = function (doc, lastCellPos, pageCount, options) {
        var str = "Page " + pageCount;
        // Total page number plugin only available in jspdf v1.0+
        if (typeof doc.putTotalPages === 'function') {
            str = str + " of " + totalPagesExp;
        }
        doc.text(str, options.margins.horizontal, doc.internal.pageSize.height - 30);
    };
    var options = {renderHeader: header, renderFooter: footer, margins: {horizontal: 40, top: 80, bottom: 50}};


    doc.autoTable(columns, data, options);

    // Total page number plugin only available in jspdf v1.0+
    if (typeof doc.putTotalPages === 'function') {
         doc.putTotalPages(totalPagesExp);
    }

    doc.save('table.pdf');

Right aligned columns and display some contents in full

Hello I wanted to know two things, I have a column that I will always display its contents in full, see the attached file in column 2.

I also want that the columns with the numbers with commas are aligned right. See column 6 of the attached file.

thanks
document

Meteor integration

After publishing your package for Meteor on Atmosphere recently, I've noticed a push by other developers in the Meteor community to get Official Integration.

This would more than likely require me to issue a PR that only includes a package.js and package.json file suitable for the Meteor community. Since I am considering doing this for a number of repos, I wanted to create an issue for this and see which repo maintainers would consider merging this work.

Thanks for creating this library. It's been a huge help on my projects and others have benefitted from it as well.

Please let me know if you're interested in having me move forward with this effort.

Thanks again,
Chip

/cc @splendido @dandv

doc.getStringUnitWidth is not a function

Line 352 calls for doc.getStringUnitWidth but this does not appear to be a method of the doc object?

var strWidth = doc.getStringUnitWidth(txt) * doc.internal.getFontSize();

If I console.log the doc object here's what I get:

jspdf

I'm using jsPDF 0.9.0rc2 downloaded from the jsPDF site, but there is no getStringUnitWidth method in their source either. Am I missing some other plugin dependency? I've included this in my html head but I doubt this affects my problem:

<script src="/vendor/jspdf.js"></script>
<script src="/vendor/jspdf.plugin.autotable.js"></script>

I could add in a single module to the jspdf object, but I'm not sure where to find the getStringUnitWidth method. Any advice?

Linebreak not working

Hi, I'm trying to use overflow linebreak, but the long text are appearing as ellipsized

var options = {
            renderHeader: function (doc, pageCount, options) {
                doc.setFontSize(12);
                doc.setTextColor(51, 51, 51);
                doc.text('Reporte de Fichas de Diagnóstico y Organización', options.margins.horizontal, 45);
            },
            renderHeaderCell: function (x, y, width, height, key, value, settings) {
                doc.setFontSize(10);
                doc.setLineWidth(0.1);
                doc.setDrawColor(240);
                doc.setFillColor(245,245,245);
                doc.setTextColor(21, 21, 21);
                doc.rect(x, y, width, height, 'B');
                y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2;
                doc.text('' + value, x + settings.padding, y);
            },
            renderCell: function (x, y, width, height, key, value, row, settings) {
                doc.setFontSize(9);
                doc.setLineWidth(0.1);
                doc.setDrawColor(240);
                // Colspan
                if (row === 13) {
                    if (value == 'GRUPO') {
                        doc.setFontSize(10);
                        doc.setFillColor(245,245,245);
                        doc.setTextColor(21, 21, 21);
                        doc.rect(x, y, doc.internal.pageSize.width - settings.margins.horizontal * 2, height, 'F');
                        y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2 - 2.5;
                        doc.text('INDICADORES DE LA ORGANIZACIÓN', x + settings.padding, y);
                    }
                } else {
                    doc.setTextColor(51, 51, 51);
                    doc.rect(x, y, width, height, 'S');
                    y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2 - 2.5;
                    doc.text('' + value, x + settings.padding, y);
                }
            },
            margins: {horizontal: 40, top: 60, bottom: 40},
            overflow: 'linebreak',
            overflowColumns: overFlowColumns
        };
        doc.autoTable(columns, data, options);

Support for custom column width

Hi
It would be nice to add support for custom column width.

like below

doc.autoTable( 
[ 
  { title : "ID", key : "id" , width: 30} ,
  { title : " Name" , key : "name"}
] , data , {});

This way I can define the width of some columns and let the plugin use the rest of the space dynamically

And thanks for the great plugin 👍 :-)

Right align few columns

Hi,

Can we right align any column header and data. Please respond asap. need it very urgently if it is possible

Thanks

Font Name and Style in PDF

How can i set font family and font style in the PDF table i created using jsPDF Autotable Plugin? I am able to set the font size but not sure about setting font family and type.

Sub header colspan

Hi, I want to add a sub header to my table but instead of adding a new row, the row where I want to add the sub header it's being replaced. I noticed that in the example is doing the same. Is there any way to add the sub header without replacing any row?

Cannot use a recursive method to print a table from a data source

hello

I tried to implement de generation o a pdf table recursively from a data base using a a controller and twig template.
i dont know if i am doing it wrong

but it does not work:

Sample:

<script> $(document).ready(function() { var doc = new jsPDF('p', 'pt'); var columns = new Array(); var data = new Array(); {% for iteraProducto in listaProducto %} var id ="{{ iteraProducto.id }}"; var nombre ="{{ iteraProducto.nombre }}"; var fechaCreacion ="{{ iteraProducto.fechaCreacion|date('Y M d H s') }}"; var descripcion ="{{ iteraProducto.descripcion }}"; var valor ="{{ iteraProducto.valor }}"; var iva ="{{ iteraProducto.iva }}"; var fechaVencimiento =" {{ iteraProducto.fechaVencimiento|date('Y M d') }}"; columns.push([ {title: "ID", key: "id"}, {title: "Nombre", key: "nombre"}, {title: "Fecha Creacion", key: "fechaCreacion"}, {title: "Descripcion", key: "descripcion"}, {title: "Valor", key: "valor"}, {title: "Iva", key: "iva"}, {title: "Fecha Vencimiento", key: "fechaVencimiento"}] ); data.push([ {"id": id, "nombre": nombre, "fechaCreacion": fechaCreacion, "descripcion": descripcion, "valor":valor, "iva": iva, "fechaVencimiento": fechaVencimiento}] ); {% endfor %} //TODO reemplazar por líneas que vengan desde el controlador doc.text(35, 25, "PRODUCTOS EN INVENTARIO"); doc.autoTable(columns, data, {}); //doc.save('table.pdf'); var jIframe = $('#prueba'); jIframe.attr('src', doc.output('dataurlstring')); }) </script> <iframe id="prueba" style="width: 500px; height: 800px;"></iframe>

How can I break lines instead of "ellipsise" them

I have very long text that can't fit into one line (even in landscapte).
Is there a way to allow line breaks, increasing the height of the row to display full content ?

Would be a great addition (if it's not already included) in this great plugin.

doc.internal.getLineHeight() is not a function.

I am getting this error "TypeError: doc.internal.getLineHeight is not a function" when creating a PDF. I've tried just setting the line height to a number, 10 , etc., but the pdf does not show anything and an error message that the PDF was created incorrectly pops up.

One of the lines that uses doc.internal.getLineHeight() is line 39 in jspdf.plugin.autotable.js:
y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2;

Has anyone else come across this as well?
Thanks.

Stack trace:
TypeError: doc.internal.getLineHeight is not a function
at Object.defaultOptions.renderHeaderCell (http://localhost:9081/us/r/libs/jsPDF-AutoTable-master/jspdf.plugin.autotable.js:39:61)
at http://localhost:9081/us/r/libs/jsPDF-AutoTable-master/jspdf.plugin.autotable.js:267:22
at Array.forEach (native)
at printHeader (http://localhost:9081/us/r/libs/jsPDF-AutoTable-master/jspdf.plugin.autotable.js:264:17)
at Object.API.autoTable (http://localhost:9081/us/r/libs/jsPDF-AutoTable-master/jspdf.plugin.autotable.js:89:9)
at k.$scope.createPDF2 (http://localhost:9081/us/r/controllers.js:1937:11)
at eb.functionCall (http://localhost:9081/us/r/libs/angular-1.3.2/angular.min.js:198:17)
at http://localhost:9081/us/r/libs/angular-1.3.2/angular-touch.min.js:12:197
at k.$get.k.$eval (http://localhost:9081/us/r/libs/angular-1.3.2/angular.min.js:124:250)
at k.$get.k.$apply (http://localhost:9081/us/r/libs/angular-1.3.2/angular.min.js:124:465)

Uncaught TypeError

Using google chrome I tried to run he script and recieved the following error pointing at line 12 of jspd.plugin.autotable.js
Uncaught TypeError: Cannot read property 'events' of undefined. And because of this the autoTable function in unrecognised. How do I fix this?

colspan issue

Hi!, i have a problem with table heads, when there is a colspan included, then there will not print all columns. Thanks for your help !

publish / savedAs is not defined.

Hi! Ive stumbled across a problem, that i'm struggeling to figure out.
I keep getting told that publish / savedAs is not defined(tryed both obviously).

code:

var doc = new jsPDF('p', 'pt');
doc.autoTable(addedAttributes, exportData, {});
doc.save('table.pdf');

this is wrapped inside a click event.

JS files( jsPDF files only)

                    "~/Scripts/jsPDF2/jspdf.js",
                    "~/Scripts/jsPDF2/jspdf.plugin.standard_fonts_metrics.js",
                    "~/Scripts/jsPDF2/jspdf.plugin.split_text_to_size.js",
                    "~/Scripts/jsPDF2/jspdf.plugin.from_html.js",
                    "~/Scripts/jsPDF2/jspdf.plugin.cell.js",
                    "~/Scripts/jsPDF2/jspdf.plugin.autotable.js",
                    "~/Scripts/jsPDF2/jspdf.plugin.annotations.js",
                    "~/Scripts/jsPDF2/jspdf.plugin.addimage.js",
                    "~/Scripts/jsPDF2/jspdf.autoprint.js",

Is there any special dependacies appart from these files?

Column Styles

I couldn't get column widths working so had a quick dig through your plugin. Looks like you have a dodgy line left in at line number 327. Set col.styles to empty object and then check if empty object contains a columnWidths member:

        var col = new Column(dataKey);
        col.styles = {};
        if (typeof col.styles.columnWidth === 'undefined') col.styles.columnWidth = 'auto';
        table.columns.push(col);

Passing function to format data

More of a question/request, but is there a way to pass a function to the column definitions to format data, for example:

{
title: 'Year',
key: 'date',
function: function(date.getFullYear())
}

Existing Column omission

I generate some tables using SQL INNER JOIN from different tables on my DB. I have noticed that the plugin omits columns that already exist?
Original Table
table_real

Pdf Table

pdf_table

Notice only 12 columns on the pdf table instead of 14 as the columns type and outcomeId_fk have only been printed once. How can I fix this?

"ReferenceError: jsPDF is not defined" with Meteor

Hi - Really nice work on the docs for this repo. 👍

Do you know if anyone has gotten this to work within a Meteor project?

I'm currently getting "ReferenceError: jsPDF is not defined"

=> Modified -- restarting.
W20150407-11:48:14.168(-5)? (STDERR)          
W20150407-11:48:14.169(-5)? (STDERR) /Users/chip/.meteor/packages/meteor-tool/.1.0.45.1bea6ne++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:245
W20150407-11:48:14.169(-5)? (STDERR)                                            throw(ex);
W20150407-11:48:14.169(-5)? (STDERR)                                                  ^
W20150407-11:48:14.172(-5)? (STDERR) ReferenceError: jsPDF is not defined
W20150407-11:48:14.172(-5)? (STDERR)     at app/lib/jspdf.plugin.autotable.js:287:4
W20150407-11:48:14.172(-5)? (STDERR)     at app/lib/jspdf.plugin.autotable.js:289:3
W20150407-11:48:14.172(-5)? (STDERR)     at /Users/chip/code/invoicethat.com/.meteor/local/build/programs/server/boot.js:222:10
W20150407-11:48:14.172(-5)? (STDERR)     at Array.forEach (native)
W20150407-11:48:14.172(-5)? (STDERR)     at Function._.each._.forEach (/Users/chip/.meteor/packages/meteor-tool/.1.0.45.1bea6ne++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
W20150407-11:48:14.172(-5)? (STDERR)     at /Users/chip/code/invoicethat.com/.meteor/local/build/programs/server/boot.js:117:5
=> Exited with code: 8

It appears that it is failing on line 284 of this plugin due to doc being undefined:

283     function getStringWidth(txt) {
284         return doc.getStringUnitWidth(txt) * doc.internal.getFontSize();                       
285     }

Here's the code I'm using as an example:

client/lib/PDF.coffee

class PDF
  columns: ->
    [
      {
        title: 'ID'
        key: 'id'
      }
      {
        title: 'Name'
        key: 'name'
      }
      {
        title: 'Country'
        key: 'country'
      }
      {
        title: 'IP-address'
        key: 'ip_address'
      }
      {
        title: 'Email'
        key: 'email'
      }
    ]

  data: ->
    [
      {
        'id': 1
        'name': 'Shaw'
        'country': 'Tanzania'
        'ip_address': '92.44.246.31'
        'email': '[email protected]'
      }
      {
        'id': 2
        'name': 'Nelson'
        'country': 'Kazakhstan'
        'ip_address': '112.238.42.121'
        'email': '[email protected]'
      }
    ]

  generate: ->
    doc = new jsPDF('p', 'pt')
    doc.autoTable @columns(), @data()
    uri = doc.output 'datauristring'
    console.log "uri ", uri

module?.PDF = PDF
window?.PDF = PDF

When I comment out the doc.autoTable it calls doc.output successfully, so it appears that jsPDF is loaded properly.

Any suggestions would be helpful. Thank you.

Sub header colspan

Hi, I want to add a sub header to my table but instead of adding a new row, the row where I want to put the sub header it's being replaced. I noticed that in the example is doing the same. Is there any way to add the sub header without replacing any row?

Linebreaks in header working but height of header not increasing

Linebreak is allowing Headers to break in the next line but height of the header does not increase. Please let me know the urgent fix. If it requires much time to fix, then please let me know how can i set the width of each column. I am using HTML table to export it into pdf. Please assist as soon as possible.

Thanks

Column width wrong when values contain new line characters

Hi!
I wanted a column 'textarea' with breaklines. but the width of the column was computed on the all the char like it was on one line.

badwidth

i had to quick fix it with this code

 function getStringWidth(txt) {
        var isBold = doc.internal.getFont().fontStyle === 'bold';

        var textWithBreakLine = txt.split("\n");
        if (textWithBreakLine.length > 1) {
            var widest = 0;
            textWithBreakLine.forEach(function(line) {
                var lineWidth = doc.getStringUnitWidth(line) * doc.internal.getFontSize() + (isBold ? 5 : 0);
                widest = (lineWidth > widest) ? lineWidth : widest;
            });
            return widest;
        } else {
            return doc.getStringUnitWidth(txt) * doc.internal.getFontSize() + (isBold ? 5 : 0);
        }
    }

The result is this

whatiwant

I just wanted to mention it and i suppose it wouldn't be a problem with the feature of a custom column width #20

Alignment for table cells

I'd like to right-justify some currency amounts and cannot figure out how to get it to work. I tried your example, but altered the columns to have an align key like so:

var columns = [
    {title: "ID", key: "id", align: "right"}, 
    {title: "Name", key: "name", align: "right"}, 
    {title: "Country", key: "country", align: "right"}, 
    {title: "Email", key: "email", align: "right"}
];

The PDF was generated successfully, but unfortunately the cell contents were not aligned like I specified. Is this possible, and if so, how should I configure the options or column keys?

Cell wrapping two pages with overflow linebreak behaves strange

Bro, im not sure if im making a mistake using your plugin, but, i was looking for days about the options and can't found something about this.

When you insert with jsPDF an image before the autotable, the auto sizing of table lost the control of the page, putting the last row (if the content of the column is extence) in the next page, but.. not the complete last row, only the content of the extence column and the columns after that. i found the solution putting top/bottom margins and adding footer to force the pluging to add the content in the right way, if only im doing it wrong, tell me please.

Thanks for your work, its a good plugin bro.

Saludos Desde México!

Saving to server

 var doc = new jsPDF('p', 'pt');
        var res = doc.autoTableHtmlToJson(table, true);
        doc.autoTable(res.columns, res.data);
        var pdf =doc.output();
        console.log(pdf)
        var data = new FormData();
        data.append("data" , pdf);
        var xhr = new XMLHttpRequest();
        xhr.open( 'post', 'upload.php', true );
        xhr.send(data);

Works.

overflow: 'linebreak' option makes text overlap instead of breaking the line

I configured an autoTable with option overflow: 'linebreak', so that it would break the line when the text is wider than the column width, but instead of breaking the line, the text became overlaped, as can be seen in the image below:

image

This is my JavaScript code to generate the PDF with jsPDF-AutoTable:

exportToPDF: function (title, columns, records, orientation) {
            var doc = new jsPDF(orientation, 'pt');

            var header = function (doc, pageCount, options) {
                doc.setFontSize(20);
                doc.text(title, options.margins.horizontal, 30);
                doc.setFontSize(options.fontSize);
            };

            var cell = function (x, y, width, height, key, value, row, settings) {
                var style = 'S';

                doc.setLineWidth(0.1);
                doc.setDrawColor(240);

                doc.rect(x, y, width, height, style);

                y += settings.lineHeight / 2 + doc.internal.getLineHeight() / 2 - 2.5;

                doc.text('' + value, x + settings.padding, y);

                doc.setTextColor(50);
            };

            var totalPagesExpression = "{total_pages_count_string}"

            var footer = function (doc, lastCellPos, pageCount, options) {
                var footerText = "Página " + pageCount + " de " + totalPagesExpression;
                doc.text(footerText, options.margins.horizontal, doc.internal.pageSize.height - 10);
            };

            doc.autoTable(columns, records, { renderHeader: header, renderCell: cell, renderFooter: footer, lineHeight: 12, fontSize: 8, overflow: 'linebreak' });
            doc.putTotalPages(totalPagesExpression);
            doc.save(title + '.pdf');
        }
    };

Maybe this is not a bug. In that case, what is wrong with my code?

Any help will be appreciated.

Generate report with header and footer and image in body

Hi,

I am looking for generating a report.

The report will typically contain:

  • A header and a header logo image
  • A graph image in document body
  • Then a tabular data , using jsPDF autoTable plugin already
  • Then the page footer with page number

For now, I have the png file for body image and header logo and i have the pdf already generating with tabular data using auto Table plugin.

What am i supposed to do ti add graph image, header or details text data and footer as page number in the pdf report generated?

Multiple Tables

i am trying to print out multiple tables but only the first one is showing. do you see anything wrong with the following code?

angular.forEach($scope.selectedDay.sets, function (set) {
angular.forEach(set.meals, function (meal) {
var rows = [];
angular.forEach(meal.items, function (item) {
rows.push({
"food": item.food.name,
"amount": item.amount,
"servingSize": "cup",
"protein": "0",
"carbs": "0",
"fat": "0",
"calories": "0"
});
});
doc.autoTable(cols, rows, { margins: { horizontal: 40, top: 60, bottom: 40 }});
});
});

doc.save('table.pdf');

Not working in IE11

Hi,

I am not able to download the file in IE11. It gives the prompt to download but. Then comes it couldn;t download. this is just not happening with your plugin but with normal jspdf as well. It seems file download problem exists with IE 11. Please let me know the solution.

Thanks
Ankur Garg

linebreaks not working in metoer project

Hi,
I like what you did here.
For some reason, no matter what I do, I always get the 'ellipsize' behavior. Also, when I set overflow to false and look at the text passed to renderCell, I get the ellipsized text.

Min width for pdf width

I have a lot of columns and it's being cut off.. How can I fix that? Is there something like min width option for this?

Issue with Header Rendering

hey buddy

every couple prints my output has a bug gap between the header and the table. do you see anything goofy going on in my code? like i said it works most of the time

var doc = new jsPDF('p', 'pt');
var cols = [
{ title: "Food", key: "food" },
{ title: "Amount", key: "amount" },
{ title: "Serving Size", key: "servingSize" },
{ title: "Protein", key: "protein" },
{ title: "Carbs", key: "carbs" },
{ title: "Fat", key: "fat" },
{ title: "Calories", key: "calories" }
];

    doc.setFontSize(22);
    doc.text(day.name, 40, 40);
    doc.setFontSize(12);

    angular.forEach(day.sets, function (set) {
        angular.forEach(set.meals, function (meal) {
            var rows = [];
            angular.forEach(meal.items, function (item) {
                var uom = _.find($scope.uomCache, function (uom) {
                    return uom.id === item.measurementId;
                });
                rows.push({
                    "food": item.food.name,
                    "amount": item.amount,
                    "servingSize": uom.name,
                    "protein": $filter('number')($scope.stats.forItem(item).protein.amount, 2),
                    "carbs": $filter('number')($scope.stats.forItem(item).carbohydrate.amount, 2),
                    "fat": $filter('number')($scope.stats.forItem(item).fat.amount, 2),
                    "calories": $filter('number')($scope.stats.forItem(item).totalCalories, 2),
                });
            });
            rows.push({
                "food": "Totals",
                "amount": "",
                "servingSize": "",
                "protein": $filter('number')($scope.stats.forMeal(meal).protein.amount, 2),
                "carbs": $filter('number')($scope.stats.forMeal(meal).carbohydrate.amount, 2),
                "fat": $filter('number')($scope.stats.forMeal(meal).fat.amount, 2),
                "calories": $filter('number')($scope.stats.forMeal(meal).totalCalories, 2),
            });

            if (angular.equals(meal, _.last(set.meals))) {
                rows.push({
                    "food": "Grand Totals",
                    "amount": "",
                    "servingSize": "",
                    "protein": $filter('number')($scope.stats.forMealPlan().protein.amount, 2),
                    "carbs": $filter('number')($scope.stats.forMealPlan().carbohydrate.amount, 2),
                    "fat": $filter('number')($scope.stats.forMealPlan().fat.amount, 2),
                    "calories": $filter('number')($scope.stats.forMealPlan().totalCalories, 2),
                });
            };

            var header = function (doc, pageCount, options) {
                doc.setFontSize(12);
                doc.text($scope.getSetOrdinalPdf(set, meal), 40, doc.autoTableEndPos().y - 5);
                doc.setFontSize(options.fontSize);
            };

            var endPos = doc.autoTableEndPos();
            doc.autoTable(cols, rows, {
                renderHeader: header,
                startY: endPos ? endPos.y + 25 : 75,    //firstStartY
                avoidPageSplit: true,
                margins: { horizontal: 40, top: 40, bottom: 40 }
            });
        });
    });

    doc.save($scope.mealplan.name + ' (' + day.name + ').pdf');

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.