使用js框架将json转换为pdf

chi*_*iru 4 javascript

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

例如,我想转换这个json

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
Run Code Online (Sandbox Code Playgroud)

进入pdf ...

Employees

FirstName: John  LastName  :Doe

FirstName: Anna LastName  :Smith

FirstName: Peter LastName  :Jones
Run Code Online (Sandbox Code Playgroud)

Ale*_*der 11

您可以使用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');
Run Code Online (Sandbox Code Playgroud)

  • 我猜你有多少个条目都没关系,方法是一样的,还是我错过了什么? (2认同)

Sac*_*han 5

您可以使用支持客户端和服务器端渲染的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();
Run Code Online (Sandbox Code Playgroud)