Search code examples
javascripthtmlnode.jspdfwkhtmltopdf

Can't access a file by command while execution of code in Node JS


I'm creating one file [HTML] at run time by Node and converting it to PDF by command line. HTML created successfully even PDF file also created success but empty.

I checked the created HTML file contains data but command line couldn't read that I guess. Here is my code:

Create HTML file:

var getPdf=function (html,fileName,callback) {
 fs.writeFile("./pdf/"+fileName+".html", html,'utf8', function(err) {
     if(err) {
         return callback(err,[]);
     }
     fs.readFile("./pdf/"+fileName+".html","utf8", (err, data) => {
           if (err) throw err;
        console.log(data);
    });
     return callback(err,fileName);
  });
 }

Create PDF after the HTML Created:

var html="<html><head><title>Hello World</title></head><body><h1>Hello 
   Sarath!</h1></body></html>";
  getPdf(html,'sarath',function (err, fileName) {
    if(err) {
       console.log("Error: "+err);
       return false;
     }
     var cmd="xvfb-run wkhtmltopdf ./pdf/"+fileName+" ./pdf/"+fileName+".pdf";
     console.log(cmd);
     exec(cmd,function(err,stdout,stderr){
        if(err) {
           return console.log(err);;
        }
        console.log("PDF Created!",stdout);
     });

 });

Solution

  • It coudln't find the file cause you missed the extension

    var html="<html><head><title>Hello World</title></head><body><h1>Hello 
       Sarath!</h1></body></html>";
      getPdf(html,'sarath',function (err, fileName) {
        if(err) {
           console.log("Error: "+err);
           return false;
         }
         var cmd="xvfb-run wkhtmltopdf ./pdf/"+fileName+".html ./pdf/"+fileName+".pdf";
         console.log(cmd);
         exec(cmd,function(err,stdout,stderr){
            if(err) {
               return console.log(err);;
            }
            console.log("PDF Created!",stdout);
         });
    
     });