简体   繁体   English

使用 npm html-pdf 将 HTML 转换为 PDF

[英]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).我正在尝试使用 npm html-pdf 将 HTML 文件转换为 PDF,但转换后的 PDF 与 HTML 不同(样式错误)。 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.我已经实现了这一点,但它是一种将 html 转换为 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.在下面的代码中,我使用 jade(现在称为 pug)来允许这个 pdf 是动态的,如果它在结构上不会改变,只是值。 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.不支持 html-pdf 中的 css3。 so element like display :flex;所以像display :flex;这样的元素display :flex; not work in html-pdf so use the old way styling like float : left etc..在 html-pdf 中不起作用,所以使用旧的样式样式,如float : left等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM