Spaces:
Runtime error
Runtime error
File size: 7,192 Bytes
5463318 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 | 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
|