Home > Blockchain >  How to FTP upload a buffer (pdf buffer) using NodeJS?
How to FTP upload a buffer (pdf buffer) using NodeJS?

Time:11-03

I converted a HTML to pdf using html-pdf-node, but I am not find a way to store this PDF in my server using FTP.

My Code:

const html_to_pdf = require('html-pdf-node');

const generatePDF = () => {
   // The test HTML file
   let content = `
      <html>
         <head>
            <title>Test Application</title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
            <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
         </head>
         <body>
            <div >
               <h2>Just a Test</h2>
            </div>
         </body>
      </html>
   `;
    
    // generating the PDF 
    let options = { 
        format: 'letter',
        margin: {
            right: '40px',
            left: '40px'
        } 
    };
    let file = { content };
    html_to_pdf.generatePdf(file, options).then((pdfBuffer) => {
       console.log(pdfBuffer); // This is the pdfBuffer. It works because if I send this buffer to my email as an attachment, I can open the PDF
       // How can I create and store a test.pdf file inside my server using FTP connection?
    });
}

Thank you

CodePudding user response:

Using ftp should do it - https://www.npmjs.com/package/ftp

Installation: npm i ftp and usage something like:

const Client = require("ftp");

// snip snip some code here

html_to_pdf.generatePdf(file, options).then((pdfBuffer) => {
  const c = new Client();
  c.on("ready", function () {
    c.put(pdfBuffer, "foo.pdf", function (err) {
      if (err) throw err;
      c.end();
    });
  });

  const secureOptions = {
      host: "localhost",
      port: 21,
      user: "TheGreatPotatoKingOfEurope",
      password: "5uper_5eekrit!"
  };
  c.connect(secureOptions);
});
  • Related