簡體   English   中英

使用 npm html-pdf 將 HTML 轉換為 PDF

[英]Convert HTML to PDF using npm html-pdf

我正在嘗試使用 npm html-pdf 將 HTML 文件轉換為 PDF,但轉換后的 PDF 與 HTML 不同(樣式錯誤)。 有人能告訴我我做錯了什么嗎?

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);
  });

我已經實現了這一點,但它是一種將 html 轉換為 pdf 的稍微不同的方法。 在下面的代碼中,我使用 jade(現在稱為 pug)來允許這個 pdf 是動態的,如果它在結構上不會改變,只是值。 換句話說,它是一個可重用的模板。 此外,我異步執行此操作,這是您遇到問題的潛在原因。 您編寫同步代碼是否有特定原因?

在您的代碼中,有幾個變量沒有顯示其定義,所以我看不出這是否是問題所在。 如果您包含您的代碼,我將能夠為您提供更多幫助。 我希望我的代碼在此期間對您有所幫助。

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);
            }
        });
    }
});

不支持 html-pdf 中的 css3。 所以像display :flex;這樣的元素display :flex; 在 html-pdf 中不起作用,所以使用舊的樣式樣式,如float : left等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM