You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python脚本将API获取的JSON数据转换为PDF?

Convert JSON Data to PDF in Python (Alternative Solutions)

Hey there! That "no module PDFWriter" error pops up because that old ActiveState recipe relies on a custom or deprecated library that's no longer widely maintained. Let's use modern, well-supported tools instead—here are two straightforward methods to turn your JSON data into a PDF:

Method 1: Use ReportLab (Robust, Feature-Rich)

ReportLab is a popular Python library for generating PDFs, with great support for tables, text formatting, and more.

Step 1: Install ReportLab

First, install the library via pip:

pip install reportlab

Step 2: Full Code Example

This script will parse your JSON data, create a PDF with a formatted table showing state and quantity:

import json
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.lib import colors

# Your sample JSON data
json_data = '''{ "data": [ { "state": "Manchester", "quantity": 20 }, { "state": "Surrey", "quantity": 46 }, { "state": "Scotland", "quantity": 36 }, { "state": "Kent", "quantity": 23 }, { "state": "Devon", "quantity": 43 }, { "state": "Glamorgan", "quantity": 43 } ] }'''

# Parse JSON
data = json.loads(json_data)['data']

# Prepare table data (add header row first)
table_data = [["State", "Quantity"]]
for item in data:
    table_data.append([item['state'], item['quantity']])

# Create PDF document
pdf = SimpleDocTemplate("state_quantities.pdf", pagesize=letter)

# Style the table
table_style = TableStyle([
    ('BACKGROUND', (0,0), (-1,0), colors.grey),
    ('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke),
    ('ALIGN', (0,0), (-1,-1), 'CENTER'),
    ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
    ('FONTSIZE', (0,0), (-1,0), 12),
    ('BOTTOMPADDING', (0,0), (-1,0), 12),
    ('BACKGROUND', (0,1), (-1,-1), colors.beige),
    ('GRID', (0,0), (-1,-1), 1, colors.black)
])

# Build the table and add to PDF
table = Table(table_data)
table.setStyle(table_style)
pdf.build([table])

print("PDF generated successfully!")

Method 2: Use FPDF2 (Lightweight, Easy to Use)

If you prefer a simpler, lighter library, FPDF2 (the updated version of the original FPDF) is a great choice.

Step 1: Install FPDF2

pip install fpdf2

Step 2: Full Code Example

This script creates a PDF with a title and a list of state-quantity pairs:

import json
from fpdf import FPDF

# Your sample JSON data
json_data = '''{ "data": [ { "state": "Manchester", "quantity": 20 }, { "state": "Surrey", "quantity": 46 }, { "state": "Scotland", "quantity": 36 }, { "state": "Kent", "quantity": 23 }, { "state": "Devon", "quantity": 43 }, { "state": "Glamorgan", "quantity": 43 } ] }'''

# Parse JSON
data = json.loads(json_data)['data']

# Initialize PDF
pdf = FPDF()
pdf.add_page()

# Add title
pdf.set_font("Arial", 'B', 16)
pdf.cell(200, 10, txt="State Quantity Report", ln=True, align='C')
pdf.ln(10) # Add line break

# Add content
pdf.set_font("Arial", size=12)
for idx, item in enumerate(data, 1):
    pdf.cell(200, 10, txt=f"{idx}. {item['state']}: {item['quantity']}", ln=True, align='L')

# Save PDF
pdf.output("state_quantities_fpdf.pdf")

print("PDF generated successfully!")

Both methods will generate a clean, readable PDF from your JSON data. ReportLab is better if you need advanced formatting (like complex tables, charts, or custom layouts), while FPDF2 is perfect for quick, simple documents.

内容的提问来源于stack exchange,提问作者Hitesh Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:15:10