Finn
Finn

Reputation: 1459

nodejs html-to-pdf, output is not working

The html-to-pdf: https://github.com/ChaosEvoker/html-to-pdf

I want to convert HTML to PDF like this:

var htmlToPdf = require('html-to-pdf');
var html = '<div>test</div>'; //Some HTML String from code above

htmlToPdf.convertHTMLString(html, '.\\pdf\\thepdf.pdf',
        function (error, success) {
            if (error) {
                console.log('Oh noes! Errorz!');
                console.log(error);
            } else {
                console.log('Woot! Success!');
                console.log(success);
            }
        }
    );

the console:

Woot! Success!
{ process_code: 1 }

this is success,but I can not find "thepdf.pdf" in .\pdf or anywhere.

Upvotes: 1

Views: 5796

Answers (3)

sultan
sultan

Reputation: 4729

As the alternative. Puppeteer can do that job easily:

const puppeteer = require('puppeteer');
const root_directory = process.cwd();
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(`<p>Hello world!</p>`);
await page.pdf({path: `${root_directory}/src/your_file_name.pdf`, format: 'A4'});
await browser.close();

Upvotes: 0

Rohit Nayal
Rohit Nayal

Reputation: 292

Take a look a wkhtmltopdf , also please refer the dcumentation for interesting "options" which can be used with this function.

For this you will need to install a utility wkhtmltopdf by

sudo apt-get install wkhtmltopdf
npm install wkhtmltopdf --save

and then you can use the module wkhtmltopdf as followed t generate your pdf file.

var pdfConverter = require('wkhtmltopdf');
pdfConverter('html string here', {output: 'outFile.pdf'});

Upvotes: 1

Adiii
Adiii

Reputation: 59896

use npm module html-pdf

 var fs = require('fs');
var pdf = require('html-pdf');
var html = fs.readFileSync('./home.html', 'utf8'); //to your html file
var options = { format: 'Letter' };
 //in your case just your html code in place of html
     //pdf.create(<html><div>test</div></html>,.....)
pdf.create(html, options).toFile('./gerrateddoc.pdf', function(err, res) {
  if (err) return console.log(err);
  console.log(res); // { filename: '/genrateddoc.pdf' } 
});

Upvotes: 4

Related Questions