Javascript 使用js框架将json转换为pdf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26969514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:34:57  来源:igfitidea点击:

Converting json to pdf using js frameworks

javascript

提问by chiru

I want to convert json data into a pdf file via client-side Javascript. Can you please point me in a helpful direction?

我想通过客户端 Javascript 将 json 数据转换为 pdf 文件。你能指点我一个有用的方向吗?

For example, I'd like to convert this json

例如,我想转换这个 json

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

Into a pdf...

变成pdf...

Employees

FirstName: John  LastName  :Doe

FirstName: Anna LastName  :Smith

FirstName: Peter LastName  :Jones

回答by Alexander

You can generate PDF's on the client using jsPDF.

您可以使用jsPDF在客户端生成 PDF 。

var employees = [
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
];

var doc = new jsPDF();
employees.forEach(function(employee, i){
    doc.text(20, 10 + (i * 10), 
        "First Name: " + employee.firstName +
        "Last Name: " + employee.lastName);
});
doc.save('Test.pdf');

回答by Sachidhanandhan

You can use pdfmakewhich support both client side and server side rendering

您可以使用支持客户端和服务器端渲染的pdfmake

//import pdfmake
import pdfMake from 'pdfmake/build/pdfmake.js';
import pdfFonts from 'pdfmake/build/vfs_fonts.js';

pdfMake.vfs = pdfFonts.pdfMake.vfs;

const employees = [
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
];
const document = { content: [{text: 'Employees', fontStyle: 15, lineHeight: 2}] }
employees.forEach(employee => {
    document.content.push({
        columns: [
            { text: 'firstname', width: 60 },
            { text: ':', width: 10 },
            { text:employee.firstName, width: 50 },
            { text: 'lastName', width: 60 },
            {text: ':', width: 10 }, { text: employee.lastName, width: 50}
        ],
        lineHeight: 2
    });
});
pdfMake.createPdf(document).download();