-1

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);
  });
Marija Lyka
  • 163
  • 3
  • 17
  • 1
    You need to be more specific about your problem, and maybe add relevant part of your _example.html_. As it, we can't help so much. – TGrif Jul 04 '17 at 16:43
  • If `html-pdf` command line is used to generate pdf from `example.html`, does the style issue still exist? Can you post relevant content of example.html? – shaochuancs Jul 04 '17 at 23:39
  • The PDF file that is generated from the HTML does not look like the HTML, the text is too big and there are no images. – Marija Lyka Jul 05 '17 at 08:57

2 Answers2

0

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);
            }
        });
    }
});
sirrele
  • 171
  • 1
  • 6
0

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..

YAGOUBI A.E.K
  • 101
  • 1
  • 4