I should transform a json file into pdf. I’m having trouble creating a table that allows me to make items that are too long wrap automatically and not overflow to the right side.
I paste an example of the json code that I should transform into pdf and then my implementation in python (which unfortunately returns a bad result)
json code:
"allIssues":[
{
"ruleId":"name",
"description":"Description123",
"help":"Description234",
"impact":"critical",
"selector":[
"abc1234"
],
"summary":"long text",
"source":"long text2",
},
{
...
},
]
My python implementation:
import json
from fpdf import FPDF
import pandas as pd
with open('input.json') as f:
data = json.load(f)
pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial', 'B', 16)
# Title
pdf.cell(0, 10, 'Inspection summary', 0, 1)
pdf.set_font('Arial', '', 12)
df = pd.DataFrame(data['allIssues'])
df = df[['ruleId', 'description', 'help', 'impact', 'selector', 'summary', 'source']]
col_width = pdf.w / 2.2
row_height = pdf.font_size * 2
for issue in df.itertuples(index=False):
data = [
['ruleId:', str(issue.ruleId)],
['description:', issue.description],
['help:', issue.help],
['impact:', issue.impact],
['selector:', issue.selector],
['summary:', issue.summary],
['source:', issue.source],
]
# Draw table
for row in data:
pdf.multi_cell(col_width, row_height, str(row[0]), border=0)
pdf.multi_cell(col_width, row_height, str(row[1]), border=0)
pdf.ln(row_height)
# Draw line between tables
pdf.line(10, pdf.get_y(), pdf.w - 10, pdf.get_y())
pdf.ln(row_height)
pdf.output('output.pdf', 'F')
This is a screenshot of the output:
This is what I’m trying to achive
Can you give me a hand? is it feasible to create something nice?
2
Answers
There seems to be a lot of steps in your code. You could simply loop over the columns of your transposed df and export each of them to html. Append all html tables to a root html element and export with
pdfkit
:With the following css file:
You’ll get:
Edit: updated json with the data you provided + exporting additional data + improved css
Note: you will need to install wkhtmltopdf and make sure that it is in your path.
Edit2: limiting output to desired fields
disclaimer: I am the author of
borb
, the library used in this answer.Assuming your data looks like this:
You can run the following code:
This generates the following PDF: