12

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

For example, I'd like to convert this json

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

Into a pdf...

Employees

FirstName: John  LastName  :Doe

FirstName: Anna LastName  :Smith

FirstName: Peter LastName  :Jones
2
  • 1
    JSON data to pdf? What does that even mean? Commented Nov 17, 2014 at 9:36
  • 2
    updated with what I want to do Commented Nov 17, 2014 at 9:40

2 Answers 2

16

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

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');
Sign up to request clarification or add additional context in comments.

4 Comments

I have to do same thing but my json object is big which is a table basically with more than 800 entries how I can do it
I guess it does not matter how many entries you have, the approach would be the same, or am i missing something ?
As an alternative, you can also try the pdfmake library.
How can we generate table like structure through jsPDF?
7

You can use pdfmake which support both client side and server side rendering

//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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.