ExamCraftAI / Backend /utils /pdf_generator.py
Hkoradiya123
Initial commit
5463318
Raw History Blame Contribute Delete
7.19 kB
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, ListFlowable, ListItem, PageBreak
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
import os
def create_pdf(exam_data, output_path, password=None):
from reportlab.lib.pdfencrypt import StandardEncryption
if password:
enc = StandardEncryption(password, password, canPrint=1, canModify=0, canCopy=0, canAnnotate=0)
doc = SimpleDocTemplate(output_path, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18, encrypt=enc)
else:
doc = SimpleDocTemplate(output_path, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18)
styles = getSampleStyleSheet()
# Custom Styles
title_style = ParagraphStyle(
'TitleStyle',
parent=styles['Heading1'],
fontSize=18,
spaceAfter=6,
alignment=1 # Center
)
meta_style = ParagraphStyle(
'MetaStyle',
parent=styles['Normal'],
fontSize=10,
alignment=1, # Center
spaceAfter=12,
textColor=colors.dimgrey
)
stats_style = ParagraphStyle(
'StatsStyle',
parent=styles['Normal'],
fontSize=11,
alignment=1, # Center
spaceBefore=6,
spaceAfter=18,
textColor=colors.black,
fontName='Helvetica-Bold'
)
instruction_title_style = ParagraphStyle(
'InstructionTitleStyle',
parent=styles['Normal'],
fontSize=11,
fontName='Helvetica-Bold',
spaceAfter=4
)
instruction_text_style = ParagraphStyle(
'InstructionTextStyle',
parent=styles['Normal'],
fontSize=10,
spaceAfter=24,
textColor=colors.darkgrey
)
section_style = ParagraphStyle(
'SectionStyle',
parent=styles['Heading2'],
fontSize=14,
spaceBefore=12,
spaceAfter=6,
textColor=colors.navy
)
question_style = ParagraphStyle(
'QuestionStyle',
parent=styles['Normal'],
fontSize=11,
spaceBefore=10,
spaceAfter=6
)
option_style = ParagraphStyle(
'OptionStyle',
parent=styles['Normal'],
fontSize=11,
leftIndent=20,
spaceBefore=2,
spaceAfter=2
)
answer_style = ParagraphStyle(
'AnswerStyle',
parent=styles['Normal'],
fontSize=10,
leftIndent=10,
textColor=colors.darkslategrey,
spaceBefore=4,
spaceAfter=4
)
story = []
form_data = exam_data.get('form_data', {})
generated_result = exam_data.get('generated_result', {})
# Title
main_title = form_data.get('title') or generated_result.get('title') or 'Examination Paper'
story.append(Paragraph(main_title, title_style))
# Meta Info (Subject / Grade)
subject = form_data.get('subject', '')
grade = form_data.get('classGrade', '')
meta_text = []
if subject: meta_text.append(f"Subject: {subject}")
if grade: meta_text.append(f"Grade/Class: {grade}")
if meta_text:
story.append(Paragraph(" | ".join(meta_text), meta_style))
# Stats Info (Duration / Marks)
duration = form_data.get('duration', '')
marks = form_data.get('totalMarks', '')
stats_text = []
if duration: stats_text.append(f"Time Allowed: {duration} Mins")
if marks: stats_text.append(f"Maximum Marks: {marks}")
if stats_text:
story.append(Paragraph("          ".join(stats_text), stats_style))
# Divider
story.append(Spacer(1, 10))
# General Instructions
instructions = form_data.get('instructions', '')
if instructions:
story.append(Paragraph("General Instructions:", instruction_title_style))
# Handle newlines in instructions by replacing \n with <br/>
formatted_inst = instructions.replace('\n', '<br/>')
story.append(Paragraph(formatted_inst, instruction_text_style))
# Questions sections
has_answers = False
for section in generated_result.get('sections', []):
story.append(Paragraph(section.get('section_name', 'Section'), section_style))
if section.get('instructions'):
story.append(Paragraph(f"<i>{section['instructions']}</i>", styles['Italic']))
story.append(Spacer(1, 6))
for idx, q in enumerate(section.get('questions', [])):
q_text = f"<b>Q{idx+1}.</b> {q.get('question_text')}"
# Put marks on the right side logic (simple append for now)
if q.get('marks'):
q_text += f" <b>[{q.get('marks')}]</b>"
story.append(Paragraph(q_text, question_style))
if q.get('internal_choice_question_text'):
story.append(Paragraph("<b>OR</b>", ParagraphStyle('OrStyle', parent=styles['Normal'], alignment=1, fontSize=10, textColor=colors.grey)))
story.append(Paragraph(q.get('internal_choice_question_text'), question_style))
if q.get('options') and len(q.get('options')) > 0:
opts = q.get('options')
for i, opt in enumerate(opts):
try:
bullet_char = chr(65 + i)
except ValueError:
bullet_char = "*"
story.append(Paragraph(f"{bullet_char}. {opt}", option_style))
if q.get('correct_answer') or q.get('marking_scheme'):
has_answers = True
story.append(Spacer(1, 4))
# ---------------------------------------------------------
# Answer Key & Marking Scheme (on a new page)
# ---------------------------------------------------------
if has_answers:
story.append(PageBreak())
story.append(Paragraph("Answer Key & Marking Scheme", title_style))
story.append(Paragraph(f"For: {main_title}", meta_style))
story.append(Spacer(1, 20))
for section in generated_result.get('sections', []):
story.append(Paragraph(f"Answers: {section.get('section_name', 'Section')}", section_style))
for idx, q in enumerate(section.get('questions', [])):
if q.get('correct_answer') or q.get('marking_scheme'):
story.append(Paragraph(f"<b>Q{idx+1}.</b>", ParagraphStyle('QAnsLabel', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=11, spaceBefore=8)))
if q.get('correct_answer'):
story.append(Paragraph(f"<b>Answer:</b> {q.get('correct_answer')}", answer_style))
if q.get('marking_scheme'):
story.append(Paragraph(f"<b>Marking Scheme:</b><br/>{q.get('marking_scheme').replace(chr(10), '<br/>')}", answer_style))
story.append(Spacer(1, 6))
doc.build(story)
return output_path