search

Home  >  Q&A  >  body text

Method to generate PDF files: Use Node.js to connect to MySQL database

<p>I'm trying to generate a PDF file using Node js, Pdfkit and pdfkit-table using data stored in a Mysql database. I need to print records from a database to a table in a PDF document. </p> <p>The following code generates an empty PDF file. Please help me solve the problem why it is not generating PDF file with data. </p> <p>This is the index.js file.</p> <pre class="brush:php;toolbar:false;">var express = require('express'); var router = express.Router(); var PDFDocument = require('pdfkit'); var orm = require('orm'); var PDFDoc = require("pdfkit-table"); router.use(orm.express("mysql://root:@localhost:/kirula_fashion", { define: function (db, models, next) { models.news = db.define("ledger", { id : String, date : String, description : String, debit : String, credit : String, }); next(); } })); router.get('/', function(req, res, next) { var result = req.models.news.find({ }, function(error, news){ if(error) throw error; res.render('index', { news:news, title: '使用NodeJS生成PDF' }); }); }); router.get('/pdf', function(req, res, next) { var id = req.query.id; const doc = new PDFDocument(); const docTable = new PDFDoc(); var result = req.models.news.find({id: id}, function(error, newspost){ if(error) throw error; else{ if(newspost.length>0){ for(var i=0; i<newspost.length;i ){ var date = newspost[0]['date']; var description = newspost[0]['description']; var debit = newspost[0]['debit']; var credit = newspost[0]['credit']; var table = { title: "账簿记录", subtitle: "2020年5月", headers: [ { "label":"日期", "property":"date", "width":100 }, { "label":"描述", "property":"description", "width":100 }, { "label":"借方", "property":"debit", "width":100 }, { "label":"贷方", "property":"credit", "width":100 } ], datas: [ { "date":date, "description":description, "debit":debit, "credit":credit}, { "renderer": "function(value, i, irow){ return value `(${(1 irow)})`; }" } ], }; docTable.table( table, { width: 300, }); } } } var title = "2020年5月账簿"; var filename = encodeURIComponent(title) '.pdf'; res.setHeader('Content-disposition', 'attachment; filename="' filename '"'); res.setHeader('Content-type', 'application/pdf'); doc.pipe(res); doc.end(); }); }); module.exports = router;</pre></p>
P粉154798196P粉154798196455 days ago648

reply all(1)I'll reply

  • P粉924915787

    P粉9249157872023-08-26 00:56:45

    I had the same problem with the data options, but for the row options, pdfkit-table worked just fine, maybe mapping [{..},{...}] to [[..],[ ...]] and then use line options

    reply
    0
  • Cancelreply