简体   繁体   中英

How to Generate a PDF using NodeJs, EJS and MySQL

I'm doing a web project and I need to generate a PDF with data from MySQL, I got the connection and trough a Res.Render('Myview.ejs', data: data) I can see the data, but I want a pdf with the data.

Where i got the DB Conection and SQL Query

var mysql = require('mysql');

exports.proyectosHome =  (req, res) => {  
// Parámetros de conexión a la base de datos.
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database : 'tasker'
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  con.query("select * from proyectos", function (err, result) {
    if (err) throw err; 
    res.render('index.ejs',
    {
      datos :result
    });

  })
});
}

And myView Where i got a tag <a> that when i press, I want to create a pdf with the select * from proyectos data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <% for( let i = 0; i < datos.length; i++ ) { %>
    <%- datos[i].nombre %>
    <% } %>

    <a href="#">Create PDF</a>
</body>
</html>

You need a formatting engine to make a nice looking PDF to download. You can use eg react-pdf to https://react-pdf.org/ to generate PDFs. If you're familiar with react, it is fairly straight forward, but you need to design the page using Views, similar to div.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM