简体   繁体   中英

Convert HTML to PDF using npm html-pdf

I'm trying to convert a HTML file to PDF, using npm html-pdf, but the converted PDF is not as the HTML(the style is wrong). Can someone tell me what am I doing wrong?

var pdf = require('html-pdf');
var html = fs.readFileSync('./example.html', 'utf8');

    pdf.create(html, options).toFile(folderName + '/' + fileName, function (err, res) { // if the file doesnt exist it will be created
    if (err) return console.log(err);

    console.log(res);
  });

I have implemented this but its a slightly different way to approach converting html to pdf. In the code below, I use jade (now called pug) to allow this pdf to be dynamic if it structurally wont change, just the values. In other words, it's a reusable template. Also, I did this asynchronously, which is a potential reason you are running into issues. Is there a specific reason you are writing synchronous code?

Within your code, there are a couple variables that you are not showing the definition to, so I cannot see if that's where the issue resides. If you include your code, I will be able to assist you a little more. I hope my code assists you in the meantime.

let fs = require('fs');
let path = require('path');
let jade = require('jade');
let pdf = require('html-pdf');
let filepath = path.resolve(__dirname, '../views/example.jade');
let templateVariables = {}; // If you have any to pass in
fs.readFile(filepath, 'utf8', function(err, data) {
    if (err) throw err;
    let fn = jade.compile(data);
    let html = fn(templateVariables);
    let options = {
        pageSize: 'Letter',
        marginTop: '0.5in',
        marginLeft: '0.25in',
        marginRight: '1.0in',
        marginBottom: '0.5in'
    };
    if (html) {
        pdf.create(html, options).toFile('./example.pdf', function(err, res){
            if (err) {
                console.log(err);
                cb(err);
            }
            if (res) {
                console.log('pdf res ', res);
            }
        });
    }
});

css3 in html-pdf not supported. so element like display :flex; not work in html-pdf so use the old way styling like float : left etc..

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