Make the pdf more correct and attractive with different colours and add professional borders by removing this original and add index according to topics

Reading File
Running Command

cd /tmp/workspace/attachments/e8507807-5f28-4d06-83c4-be077f25c356 && python3 -c " import pdfplumber with pdfplumber.open('SW INCOMPLETE ASSISGNMENT (1).pdf') as pdf: print(f'Total pages: {len(pdf.pages)}') for i, page in enumerate(pdf.pages): print(f'\n--- PAGE {i+1} ---') print(page.extract_text()) "

Running Command

mkdir -p /tmp/workspace/assignment-pdf && ls /tmp/workspace/

Writing File

~/assignment-pdf/build_pdf.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm, mm
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    PageBreak, HRFlowable, KeepTogether
)
from reportlab.platypus.flowables import Flowable
from reportlab.pdfgen import canvas
from reportlab.lib.colors import HexColor
import copy

# ── Color Palette ──────────────────────────────────────────────────
TEAL        = HexColor("#006B6B")   # deep teal  – section headers
TEAL_LIGHT  = HexColor("#E0F4F4")   # pale teal  – section bg
GOLD        = HexColor("#B8860B")   # dark gold  – subsection headers
GOLD_LIGHT  = HexColor("#FFF8DC")   # cream      – subsection bg
NAVY        = HexColor("#1A3557")   # navy blue  – title / TOC header
SKY         = HexColor("#D6EAF8")   # sky blue   – table header bg
MINT        = HexColor("#D5F5E3")   # mint green – highlight rows
LAVENDER    = HexColor("#EAE4F0")   # lavender   – alt rows
ROSE        = HexColor("#FDECEA")   # rose       – warning / note boxes
ORANGE      = HexColor("#E8600A")   # orange     – bullet accent
WHITE       = colors.white
BLACK       = colors.black
GRAY_MID    = HexColor("#555555")
BORDER_COL  = HexColor("#1A3557")

W, H = A4

# ── Page template with border ──────────────────────────────────────
class BorderCanvas(canvas.Canvas):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._saved_page_states = []

    def showPage(self):
        self._saved_page_states.append(dict(self.__dict__))
        self._startPage()

    def save(self):
        num_pages = len(self._saved_page_states)
        for state in self._saved_page_states:
            self.__dict__.update(state)
            self._draw_border_and_footer(num_pages)
            super().showPage()
        super().save()

    def _draw_border_and_footer(self, total_pages):
        self.saveState()
        # Outer border
        self.setStrokeColor(BORDER_COL)
        self.setLineWidth(2.5)
        self.rect(15*mm, 15*mm, W - 30*mm, H - 30*mm, stroke=1, fill=0)
        # Inner decorative border
        self.setStrokeColor(GOLD)
        self.setLineWidth(0.8)
        self.rect(18*mm, 18*mm, W - 36*mm, H - 36*mm, stroke=1, fill=0)

        # Corner ornaments (small squares)
        size = 4*mm
        corners = [
            (15*mm, 15*mm), (W - 15*mm - size, 15*mm),
            (15*mm, H - 15*mm - size), (W - 15*mm - size, H - 15*mm - size)
        ]
        self.setFillColor(NAVY)
        for cx, cy in corners:
            self.rect(cx, cy, size, size, stroke=0, fill=1)

        # Footer bar
        self.setFillColor(NAVY)
        self.rect(18*mm, 18*mm, W - 36*mm, 8*mm, stroke=0, fill=1)
        self.setFillColor(WHITE)
        self.setFont("Helvetica", 7)
        self.drawCentredString(W/2, 20*mm, "Nursing Assignment  |  National Immunization Schedule & National Mental Health Programme")
        self.restoreState()


# ── Custom Flowable: colored box ────────────────────────────────────
class ColorBox(Flowable):
    """A full-width filled rectangle used as a section header banner."""
    def __init__(self, text, bg=TEAL, fg=WHITE, font_size=13, height=22):
        super().__init__()
        self.text = text
        self.bg = bg
        self.fg = fg
        self.font_size = font_size
        self.height = height
        self.width = W - 56*mm   # matches usable content width

    def wrap(self, availWidth, availHeight):
        self.width = availWidth
        return (availWidth, self.height)

    def draw(self):
        c = self.canv
        c.setFillColor(self.bg)
        c.roundRect(0, 0, self.width, self.height, 4, stroke=0, fill=1)
        c.setFillColor(self.fg)
        c.setFont("Helvetica-Bold", self.font_size)
        c.drawString(8, (self.height - self.font_size) / 2 + 2, self.text)


# ── Styles ──────────────────────────────────────────────────────────
base_styles = getSampleStyleSheet()

def S(name, **kwargs):
    """Quick ParagraphStyle builder."""
    return ParagraphStyle(name, **kwargs)

title_style = S("Title",
    fontSize=22, textColor=WHITE, alignment=TA_CENTER,
    fontName="Helvetica-Bold", spaceAfter=4, leading=28)

subtitle_style = S("Subtitle",
    fontSize=14, textColor=HexColor("#CCE5FF"), alignment=TA_CENTER,
    fontName="Helvetica", spaceAfter=6, leading=18)

toc_title_style = S("TOCTitle",
    fontSize=16, textColor=NAVY, alignment=TA_CENTER,
    fontName="Helvetica-Bold", spaceAfter=10, leading=20)

toc_item_style = S("TOCItem",
    fontSize=11, textColor=NAVY, fontName="Helvetica",
    leftIndent=10, spaceAfter=4, leading=16)

toc_sub_style = S("TOCSub",
    fontSize=10, textColor=GRAY_MID, fontName="Helvetica",
    leftIndent=24, spaceAfter=3, leading=14)

section_title_style = S("SectionTitle",
    fontSize=13, textColor=WHITE, fontName="Helvetica-Bold",
    alignment=TA_LEFT, spaceBefore=6, spaceAfter=4, leading=17)

subsection_style = S("Subsection",
    fontSize=11, textColor=NAVY, fontName="Helvetica-Bold",
    spaceBefore=8, spaceAfter=3, leading=15)

body_style = S("Body",
    fontSize=10, textColor=BLACK, fontName="Helvetica",
    leading=15, spaceAfter=4, alignment=TA_JUSTIFY)

bullet_style = S("Bullet",
    fontSize=10, textColor=BLACK, fontName="Helvetica",
    leading=14, spaceAfter=3, leftIndent=16, bulletIndent=4,
    bulletFontName="Helvetica", bulletFontSize=10, bulletColor=ORANGE)

note_style = S("Note",
    fontSize=9.5, textColor=HexColor("#7B0000"), fontName="Helvetica-Oblique",
    leading=13, spaceAfter=4, leftIndent=6)

ref_style = S("Ref",
    fontSize=9, textColor=GRAY_MID, fontName="Helvetica",
    leading=13, spaceAfter=3, leftIndent=8)


# ── Helper builders ─────────────────────────────────────────────────
def section_header(text, color=TEAL):
    return [
        Spacer(1, 6),
        ColorBox(text, bg=color, fg=WHITE, font_size=13, height=24),
        Spacer(1, 4),
    ]

def subsection_header(text, color=GOLD):
    return [
        Spacer(1, 5),
        ColorBox(text, bg=color, fg=WHITE, font_size=11, height=20),
        Spacer(1, 3),
    ]

def body(text):
    return [Paragraph(text, body_style)]

def bullets(items):
    out = []
    for item in items:
        out.append(Paragraph(f"<bullet>\u2022</bullet> {item}", bullet_style))
    return out

def two_col_table(pairs, col_w=None):
    """pairs = list of (label, value) tuples."""
    col_w = col_w or [6*cm, 10.5*cm]
    data = [[Paragraph(f"<b>{k}</b>", S("th", fontSize=10, fontName="Helvetica-Bold", textColor=NAVY, leading=13)),
             Paragraph(v, S("td", fontSize=10, fontName="Helvetica", textColor=BLACK, leading=13))]
            for k, v in pairs]
    t = Table(data, colWidths=col_w)
    t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (0, -1), SKY),
        ("BACKGROUND", (1, 0), (1, -1), WHITE),
        ("ROWBACKGROUNDS", (0, 0), (-1, -1), [SKY, TEAL_LIGHT]),
        ("GRID", (0, 0), (-1, -1), 0.4, HexColor("#AAAAAA")),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
        ("ROUNDEDCORNERS", [3, 3, 3, 3]),
    ]))
    return [t, Spacer(1, 6)]

def spacer(h=6):
    return [Spacer(1, h)]


# ── Cover page flowables ────────────────────────────────────────────
def cover_page():
    elems = []
    elems.append(Spacer(1, 2*cm))

    # Title banner
    banner_data = [[Paragraph("NURSING ASSIGNMENT", title_style)]]
    bt = Table(banner_data, colWidths=[W - 56*mm])
    bt.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), NAVY),
        ("TOPPADDING", (0, 0), (-1, -1), 16),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 16),
        ("ROUNDEDCORNERS", [6, 6, 6, 6]),
    ]))
    elems.append(bt)
    elems.append(Spacer(1, 1*cm))

    sub_data = [
        [Paragraph("National Immunization Schedule &amp; Cold Chain", subtitle_style)],
        [Paragraph("National Mental Health Programme (NMHP)", subtitle_style)],
    ]
    st = Table(sub_data, colWidths=[W - 56*mm])
    st.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), TEAL),
        ("TOPPADDING", (0, 0), (-1, -1), 8),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 8),
        ("ROUNDEDCORNERS", [4, 4, 4, 4]),
    ]))
    elems.append(st)
    elems.append(Spacer(1, 2*cm))

    # Decorative divider
    elems.append(HRFlowable(width="100%", thickness=2, color=GOLD, spaceAfter=20))
    elems.append(Spacer(1, 0.5*cm))

    info = [
        ["Subject", "Community Health Nursing"],
        ["Programme", "B.Sc. Nursing"],
        ["Academic Year", "2025–2026"],
    ]
    info_data = [[Paragraph(f"<b>{k}</b>", S("ik", fontSize=11, fontName="Helvetica-Bold",
                    textColor=NAVY, leading=16)),
                  Paragraph(v, S("iv", fontSize=11, fontName="Helvetica",
                    textColor=BLACK, leading=16))]
                 for k, v in info]
    it = Table(info_data, colWidths=[5.5*cm, 11*cm])
    it.setStyle(TableStyle([
        ("ROWBACKGROUNDS", (0, 0), (-1, -1), [GOLD_LIGHT, TEAL_LIGHT]),
        ("GRID", (0, 0), (-1, -1), 0.4, HexColor("#AAAAAA")),
        ("TOPPADDING", (0, 0), (-1, -1), 8),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 8),
        ("LEFTPADDING", (0, 0), (-1, -1), 10),
        ("ROUNDEDCORNERS", [4, 4, 4, 4]),
    ]))
    elems.append(it)
    elems.append(Spacer(1, 1.5*cm))
    elems.append(HRFlowable(width="100%", thickness=2, color=GOLD, spaceAfter=10))
    elems.append(PageBreak())
    return elems


# ── Table of Contents ───────────────────────────────────────────────
def toc_page():
    elems = []
    elems.append(Spacer(1, 0.3*cm))
    banner = Table([[Paragraph("TABLE OF CONTENTS", toc_title_style)]], colWidths=[W - 56*mm])
    banner.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), TEAL_LIGHT),
        ("TOPPADDING", (0, 0), (-1, -1), 10),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 10),
        ("BOX", (0, 0), (-1, -1), 1.5, TEAL),
        ("ROUNDEDCORNERS", [4, 4, 4, 4]),
    ]))
    elems.append(banner)
    elems.append(Spacer(1, 12))

    sections = [
        ("PART I: NATIONAL IMMUNIZATION SCHEDULE & COLD CHAIN", TEAL, [
            ("1.", "Introduction to Immunization"),
            ("2.", "Types of Immunization"),
            ("3.", "Universal Immunization Programme (UIP)"),
            ("4.", "National Immunization Schedule"),
            ("5.", "Vaccines Used Under UIP"),
            ("6.", "Importance of Immunization"),
        ]),
        ("PART II: NATIONAL MENTAL HEALTH PROGRAMME (NMHP)", NAVY, [
            ("7.", "Introduction to Mental Health"),
            ("8.", "National Mental Health Programme (NMHP) – 1982"),
            ("9.", "District Mental Health Programme (DMHP)"),
            ("10.", "Administrative Levels of NMHP"),
            ("11.", "Mental Health Infrastructure in India"),
            ("12.", "Key Policies and Legislation"),
            ("13.", "iGOT-Diksha Collaboration"),
            ("14.", "Tele-MANAS (2022)"),
            ("15.", "KIRAN Helpline"),
            ("16.", "National Suicide Prevention Strategy"),
            ("17.", "Comparison: NMHP vs Tele-MANAS"),
            ("18.", "Benefits & Achievements of NMHP"),
            ("19.", "References"),
        ]),
    ]

    for part_title, color, items in sections:
        part_banner = Table([[Paragraph(part_title, S("pt", fontSize=11,
                    fontName="Helvetica-Bold", textColor=WHITE, leading=14))]],
                colWidths=[W - 56*mm])
        part_banner.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, -1), color),
            ("TOPPADDING", (0, 0), (-1, -1), 6),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
            ("LEFTPADDING", (0, 0), (-1, -1), 8),
            ("ROUNDEDCORNERS", [3, 3, 3, 3]),
        ]))
        elems.append(part_banner)
        elems.append(Spacer(1, 4))
        for num, title in items:
            elems.append(Paragraph(f"{num}&nbsp;&nbsp;{title}", toc_sub_style))
        elems.append(Spacer(1, 8))

    elems.append(HRFlowable(width="100%", thickness=1.5, color=GOLD, spaceAfter=6))
    elems.append(PageBreak())
    return elems


# ── PART I: Immunization content ───────────────────────────────────
def part1_immunization():
    elems = []

    # Part banner
    banner = Table([[Paragraph("PART I  |  NATIONAL IMMUNIZATION SCHEDULE &amp; COLD CHAIN",
                S("pb", fontSize=14, fontName="Helvetica-Bold", textColor=WHITE, leading=18))]],
            colWidths=[W - 56*mm])
    banner.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), TEAL),
        ("TOPPADDING", (0, 0), (-1, -1), 14),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 14),
        ("LEFTPADDING", (0, 0), (-1, -1), 10),
        ("ROUNDEDCORNERS", [5, 5, 5, 5]),
    ]))
    elems.append(banner)
    elems.append(Spacer(1, 10))

    # 1. Introduction
    elems += section_header("1.  Introduction to Immunization")
    elems += body("Immunization is one of the most successful and cost-effective public health interventions available worldwide. It protects individuals and communities from infectious diseases by stimulating the body's immune system to develop resistance against specific pathogens.")
    elems += body("The Government of India implements immunization services through the <b>Universal Immunization Programme (UIP)</b>, which aims to provide free vaccination against vaccine-preventable diseases to all eligible children and pregnant women.")
    elems += body("Vaccines save millions of lives every year by preventing diseases such as tuberculosis, diphtheria, pertussis, tetanus, polio, hepatitis B, measles, rubella, and others.")
    elems += body("To ensure vaccine effectiveness, proper storage and transportation conditions must be maintained — this system is known as the <b>Cold Chain</b>.")
    elems += spacer(6)

    # Definition box
    def_data = [[Paragraph("<b>Definition:</b> Immunization is the process by which a person becomes protected against a disease through vaccination.",
                S("def", fontSize=10, fontName="Helvetica", textColor=HexColor("#1A3557"), leading=14))]]
    dt = Table(def_data, colWidths=[W - 56*mm])
    dt.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), TEAL_LIGHT),
        ("BOX", (0, 0), (-1, -1), 1.5, TEAL),
        ("LEFTPADDING", (0, 0), (-1, -1), 10),
        ("RIGHTPADDING", (0, 0), (-1, -1), 10),
        ("TOPPADDING", (0, 0), (-1, -1), 8),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 8),
        ("ROUNDEDCORNERS", [4, 4, 4, 4]),
    ]))
    elems.append(dt)
    elems += spacer(8)

    # 2. Types
    elems += section_header("2.  Types of Immunization")
    elems += subsection_header("A.  Active Immunization")
    elems += body("Protection develops when the body's own immune system produces antibodies after exposure to a vaccine.")
    elems += bullets(["BCG", "OPV (Oral Polio Vaccine)", "Measles Vaccine"])

    elems += subsection_header("B.  Passive Immunization")
    elems += body("Protection is obtained by administering pre-formed antibodies directly into the body.")
    elems += bullets(["Tetanus Immunoglobulin", "Rabies Immunoglobulin"])
    elems += spacer(6)

    # Benefits table
    elems += subsection_header("Benefits of Immunization", color=HexColor("#2E7D32"))
    benefits = [
        ["Prevents Disease", "Stops the spread of vaccine-preventable infections."],
        ["Reduces Mortality", "Decreases death rates especially in children under 5."],
        ["Prevents Disability", "Avoids complications such as paralysis from polio."],
        ["Reduces Healthcare Costs", "Fewer hospitalizations and treatments needed."],
        ["Improves Quality of Life", "Healthier individuals and stronger communities."],
    ]
    bt = Table([["Benefit", "Explanation"]] + benefits,
               colWidths=[5*cm, 11.5*cm])
    bt.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), NAVY),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 10),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [MINT, WHITE]),
        ("GRID", (0, 0), (-1, -1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
    ]))
    elems.append(bt)
    elems += spacer(8)

    # 3. UIP
    elems += section_header("3.  Universal Immunization Programme (UIP)")
    elems += body("The Universal Immunization Programme was launched in <b>1985 by the Government of India</b> to provide free and universal access to vaccines against life-threatening diseases.")

    elems += subsection_header("Objectives of UIP")
    elems += bullets([
        "Reduce infant and child mortality",
        "Reduce maternal mortality",
        "Prevent vaccine-preventable diseases",
        "Achieve universal vaccination coverage across India",
    ])

    elems += subsection_header("Diseases Covered Under UIP")
    diseases_data = [
        ["Tuberculosis", "Polio", "Diphtheria", "Pertussis"],
        ["Tetanus", "Hepatitis B", "Measles", "Rubella"],
        ["Rotavirus Diarrhea", "Pneumococcal Disease", "Japanese Encephalitis", "Hib Infection"],
    ]
    dt2 = Table(diseases_data, colWidths=[4*cm, 4*cm, 4.5*cm, 4.5*cm])
    dt2.setStyle(TableStyle([
        ("ROWBACKGROUNDS", (0, 0), (-1, -1), [TEAL_LIGHT, MINT, LAVENDER]),
        ("GRID", (0, 0), (-1, -1), 0.5, TEAL),
        ("FONTSIZE", (0, 0), (-1, -1), 10),
        ("FONTNAME", (0, 0), (-1, -1), "Helvetica"),
        ("ALIGN", (0, 0), (-1, -1), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
    ]))
    elems.append(dt2)
    elems += spacer(10)

    # 4. Immunization Schedule
    elems += section_header("4.  National Immunization Schedule")
    elems += subsection_header("For Pregnant Women")
    pw_data = [
        ["Vaccine", "When Given"],
        ["Td-1", "Early pregnancy"],
        ["Td-2", "4 weeks after Td-1"],
        ["Td Booster", "If vaccinated in previous 3 years"],
    ]
    pw_t = Table(pw_data, colWidths=[5*cm, 11.5*cm])
    pw_t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), GOLD),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 10),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [GOLD_LIGHT, WHITE]),
        ("GRID", (0, 0), (-1, -1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
    ]))
    elems.append(pw_t)
    elems += spacer(8)

    elems += subsection_header("For Children")
    ch_data = [
        ["Age", "Vaccine(s)"],
        ["Birth", "BCG, OPV-0, Hep B Birth Dose"],
        ["6 Weeks", "Pentavalent-1, OPV-1, Rotavirus-1, IPV, PCV"],
        ["10 Weeks", "Pentavalent-2, OPV-2, Rotavirus-2"],
        ["14 Weeks", "Pentavalent-3, OPV-3, Rotavirus-3, IPV, PCV"],
        ["9–12 Months", "MR-1, JE-1, PCV Booster"],
        ["16–24 Months", "MR-2, DPT Booster, OPV Booster, JE-2"],
        ["5–6 Years", "DPT Booster-2"],
        ["10 Years", "Td"],
        ["16 Years", "Td"],
    ]
    ch_t = Table(ch_data, colWidths=[4*cm, 12.5*cm])
    ch_t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), TEAL),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 10),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [SKY, WHITE]),
        ("GRID", (0, 0), (-1, -1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
    ]))
    elems.append(ch_t)
    elems += spacer(10)

    # 5. Vaccines Used
    elems += section_header("5.  Vaccines Used Under UIP")

    vaccines = [
        ("BCG Vaccine", TEAL, "Prevents severe forms of tuberculosis.",
         [("Route", "Intradermal"), ("Site", "Left upper arm"), ("Dose", "0.05 ml for infants")]),
        ("OPV – Oral Polio Vaccine", HexColor("#1565C0"), "Protection against poliomyelitis.",
         [("Route", "Oral"), ("Dose", "2 drops")]),
        ("Pentavalent Vaccine", HexColor("#6A0572"), "Protects against Diphtheria, Pertussis, Tetanus, Hepatitis B, and Hib Infection.",
         [("Route", "Intramuscular"), ("Site", "Anterolateral thigh")]),
        ("Measles-Rubella (MR) Vaccine", HexColor("#2E7D32"), "Prevents Measles and Rubella.",
         [("Route", "Subcutaneous")]),
    ]

    for vname, vcol, vdesc, vdetails in vaccines:
        elems += subsection_header(vname, color=vcol)
        elems += body(f"<b>Purpose:</b> {vdesc}")
        for k, v in vdetails:
            elems += body(f"<b>{k}:</b> {v}")
        elems += spacer(4)

    # 6. Importance
    elems += section_header("6.  Importance of Immunization")
    importance = [
        ("1. Disease Prevention", "Prevents the spread of dangerous communicable diseases."),
        ("2. Reduction in Mortality", "Significantly reduces death rates in children and vulnerable populations."),
        ("3. Herd Immunity", "Protects unvaccinated individuals when a large proportion of the community is immune."),
        ("4. Cost Effectiveness", "Vaccination is far cheaper than treating vaccine-preventable diseases."),
        ("5. Improved Child Survival", "Major contributor to declining under-5 mortality rates globally."),
        ("6. Prevention of Epidemics", "Maintains low disease prevalence, preventing large outbreaks."),
    ]
    for title, desc in importance:
        elems += body(f"<b>{title}:</b> {desc}")
    elems += spacer(10)

    elems.append(PageBreak())
    return elems


# ── PART II: NMHP content ──────────────────────────────────────────
def part2_nmhp():
    elems = []

    # Part banner
    banner = Table([[Paragraph("PART II  |  NATIONAL MENTAL HEALTH PROGRAMME (NMHP)",
                S("pb2", fontSize=14, fontName="Helvetica-Bold", textColor=WHITE, leading=18))]],
            colWidths=[W - 56*mm])
    banner.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), NAVY),
        ("TOPPADDING", (0, 0), (-1, -1), 14),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 14),
        ("LEFTPADDING", (0, 0), (-1, -1), 10),
        ("ROUNDEDCORNERS", [5, 5, 5, 5]),
    ]))
    elems.append(banner)
    elems.append(Spacer(1, 10))

    # 7. Introduction
    elems += section_header("7.  Introduction to Mental Health", color=NAVY)
    elems += body("Mental health is a fundamental component of overall well-being. Recognizing the growing burden of mental disorders in India, the government has taken comprehensive steps to integrate mental health services into primary healthcare.")

    elems += subsection_header("Impact of Poor Mental Health", color=HexColor("#8B0000"))
    impact_data = [
        ["Impact Area", "Description"],
        ["Productivity", "Poor mental health leads to lower workplace performance, increased absenteeism, and reduced efficiency."],
        ["Social Well-being", "Affects interpersonal relationships, self-confidence, and social interactions."],
        ["Economic Burden", "According to the WHO, mental disorders contribute significantly to the global burden of disease and lead to high economic costs."],
    ]
    it = Table(impact_data, colWidths=[4.5*cm, 12*cm])
    it.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), HexColor("#8B0000")),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 10),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [ROSE, WHITE]),
        ("GRID", (0, 0), (-1, -1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
    ]))
    elems.append(it)
    elems += spacer(8)

    # 8. NMHP
    elems += section_header("8.  National Mental Health Programme (NMHP) – 1982", color=NAVY)
    elems += body("Recognizing the growing burden of mental disorders and the shortage of mental health services, India launched the <b>National Mental Health Programme (NMHP) in 1982</b>. The primary goal was to ensure that mental healthcare becomes an integral part of the general healthcare system.")

    elems += subsection_header("Key Components of NMHP")
    elems += bullets([
        "District Mental Health Programme (DMHP) — expanded community mental health services, covers 767 districts.",
        "Provides counselling, outpatient services, suicide prevention programs, and awareness initiatives.",
        "10-bedded inpatient mental health facilities at the district level.",
        "Integration of mental health into primary healthcare services.",
        "Training of healthcare workers in mental health management.",
    ])
    elems += spacer(8)

    # 9. DMHP Core Strategy
    elems += section_header("9.  District Mental Health Programme (DMHP) – Five Core Components", color=NAVY)
    dmhp_data = [
        ["Component", "Description"],
        ["1. Service Provision (Clinical)", "Early detection at community level; OPD psychiatric services at District Hospitals, CHCs & PHCs; 10-bed inpatient wards; free psychotropic medicines."],
        ["2. Human Resource Development", "Training medical officers at PHCs; equipping ANMs and ASHA workers; funding specialist teams (Psychiatrists, Psychologists, Social Workers, Nurses) at district level."],
        ["3. Public Awareness (IEC)", "Stigma-reduction campaigns; community education on mental distress & substance abuse; school/college life skills and suicide prevention programs."],
        ["4. Monitoring & Research", "Patient registries and treatment data; operational research on regional trends; quarterly reviews by state and central health committees."],
        ["5. Digital Innovation (Tele-MANAS)", "24/7 tele-counseling across the country; linking callers to DMHP units or tertiary institutes for in-person intervention."],
    ]
    dt3 = Table(dmhp_data, colWidths=[5*cm, 11.5*cm])
    dt3.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), NAVY),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 9.5),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [SKY, LAVENDER]),
        ("GRID", (0, 0), (-1, -1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("TOPPADDING", (0, 0), (-1, -1), 6),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
    ]))
    elems.append(dt3)
    elems += spacer(8)

    # 10. Administrative levels
    elems += section_header("10.  Administrative Levels of NMHP", color=NAVY)
    levels = [
        ("National Level", "Ministry of Health & Family Welfare (MoHFW); Central Mental Health Authority & Apex Institutes."),
        ("State Level", "State Department of Health & Family Welfare; State Mental Health Authority (SMHA)."),
        ("District Level", "District Mental Health Programme (DMHP) Team; District Hospital (10-Bed Psychiatric Ward)."),
        ("Sub-District / Grassroot", "Community Health Centres (CHCs) → Primary Health Centres (PHCs) → Health & Wellness Centres / ASHAs."),
    ]
    for lvl, desc in levels:
        elems += body(f"<b>{lvl}:</b> {desc}")
    elems += body("The DMHP was started in <b>27 districts</b> across the country in <b>1996</b>. It has since expanded to cover most districts in India.")
    elems += spacer(8)

    # 11. Infrastructure
    elems += section_header("11.  Mental Health Infrastructure in India", color=NAVY)
    elems += bullets([
        "In 2024, <b>25 Centres of Excellence</b> were sanctioned to train more postgraduate students in mental health.",
        "<b>47 PG Departments</b> in mental health have been established or upgraded in 19 government medical colleges.",
        "Mental health services are being introduced in <b>22 newly established AIIMS</b>.",
        "<b>47 Government-Run Mental Hospitals</b> including 3 Central Mental Health Institutions: NIMHANS (Bengaluru), LGBRIMH (Tezpur, Assam), and CIP (Ranchi).",
        "Integration of mental health services in <b>Ayushman Bharat – Health & Wellness Centres (HWCs)</b>.",
        "Over <b>1.73 lakh SHCs and PHCs</b> upgraded to Ayushman Arogya Mandirs, with mental health services added.",
    ])
    elems += spacer(8)

    # 12. Key Policies
    elems += section_header("12.  Key Policies and Legislation", color=NAVY)
    policies = [
        ("NIMHANS Act, 2012", "Declared NIMHANS, Bengaluru as an Institute of National Importance. Expanded academic and research capabilities in psychiatry, neuropsychology, and mental health sciences."),
        ("RPwD Act, 2016", "Replaced the PWD Act, 1995. Expanded disability definition to include mental illness. Aligned with the UN Convention on Rights of Persons with Disabilities (UNCRPD). Ensures equality, dignity, and non-discrimination."),
        ("Mental Healthcare Act, 2017", "Ensures the right to mental healthcare services; protects dignity and rights of persons with mental illness; decriminalized suicide in India; replaced the Mental Health Act of 1987."),
        ("National Health Policy, 2017", "Acknowledged mental health as a national health priority. Integrates mental healthcare into primary healthcare. Aims to bridge treatment gap through PHCs and HWCs under Ayushman Bharat."),
    ]
    pol_data = [["Legislation", "Key Features"]] + [[p, d] for p, d in policies]
    pt = Table(pol_data, colWidths=[4.5*cm, 12*cm])
    pt.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), HexColor("#4A148C")),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 9.5),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [LAVENDER, WHITE]),
        ("GRID", (0, 0), (-1, -1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("TOPPADDING", (0, 0), (-1, -1), 6),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
        ("FONTNAME", (0, 1), (0, -1), "Helvetica-Bold"),
        ("TEXTCOLOR", (0, 1), (0, -1), HexColor("#4A148C")),
    ]))
    elems.append(pt)
    elems += spacer(8)

    # 13. iGOT-Diksha
    elems += section_header("13.  iGOT-Diksha Collaboration for Mental Health Training", color=NAVY)
    elems += body("The government collaborated with the <b>iGOT-Diksha platform</b>, a digital learning initiative launched in <b>2020</b>, to train healthcare professionals, frontline workers, and community health volunteers in mental healthcare.")
    elems += subsection_header("Program Focus Areas")
    elems += bullets([
        "Building capacity for mental health care at the grassroots level.",
        "Equipping doctors and nurses with skills to diagnose and treat mental disorders.",
        "Promoting mental health awareness in rural areas.",
        "Expanding India's mental health workforce for better early intervention.",
    ])
    elems += spacer(8)

    # 14. Tele-MANAS
    elems += section_header("14.  National Tele Mental Health Programme – Tele-MANAS (2022)", color=HexColor("#006064"))
    elems += body("Launched on <b>October 10, 2022</b>, the National Tele Mental Health Programme (Tele MANAS) provides <b>free, 24/7 mental health support</b> through a national toll-free helpline available in 20 Indian languages.")

    stats_data = [
        ["Statistic", "Detail"],
        ["Helpline Numbers", "14416 / 1800-89-14416"],
        ["Languages Supported", "20 Indian languages"],
        ["Calls Handled (by Feb 2025)", "Over 1.81 million (18,27,951 calls)"],
        ["Tele MANAS Cells", "53 cells across various states"],
        ["Mentoring Institutes", "23 nationwide"],
        ["Regional Coordinating Centers", "5 Centers"],
        ["App Launch", "October 2024"],
        ["Video Consultations", "Karnataka, Tamil Nadu, and J&K"],
        ["WHO Recognition", "Praised as effective and scalable by WHO"],
    ]
    st2 = Table(stats_data, colWidths=[6*cm, 10.5*cm])
    st2.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), HexColor("#006064")),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 9.5),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [HexColor("#E0F7FA"), WHITE]),
        ("GRID", (0, 0), (-1, -1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
        ("FONTNAME", (0, 1), (0, -1), "Helvetica-Bold"),
    ]))
    elems.append(st2)
    elems += spacer(4)

    elems += subsection_header("Tele-MANAS Services Include", color=HexColor("#006064"))
    elems += bullets([
        "Immediate tele-counselling by trained mental health professionals.",
        "Referral support to psychiatrists for severe cases.",
        "Mental health awareness campaigns via digital platforms.",
        "Mobile-based interventions for rural and remote areas.",
        "Video consultations, e-prescriptions, and follow-up services.",
    ])
    elems += spacer(8)

    # 15. KIRAN
    elems += section_header("15.  KIRAN Helpline – Merged into Tele-MANAS", color=NAVY)
    elems += body("The <b>KIRAN Helpline (1800-599-0019)</b>, initially launched in <b>2020</b> during COVID-19, was merged into Tele-MANAS in <b>2022</b> to streamline mental health helpline operations.")
    elems += body("During the COVID-19 pandemic, the government provided:")
    elems += bullets([
        "24/7 nationwide psychosocial assistance helpline.",
        "Online mental health training for health workers through iGOT-Diksha.",
        "Public awareness campaigns on stress management via media.",
        "Official guidelines and advisories to promote mental well-being.",
    ])
    elems += spacer(8)

    # 16. NSPS
    elems += section_header("16.  National Suicide Prevention Strategy (NSPS) – 2022", color=HexColor("#8B0000"))
    elems += body("The <b>National Suicide Prevention Strategy (NSPS)</b> was launched by the Ministry of Health and Family Welfare (MoHFW) in <b>2022</b> with the goal of reducing suicide mortality by <b>10% by 2030</b>.")
    elems += subsection_header("Key Components of NSPS", color=HexColor("#8B0000"))
    elems += bullets([
        "Mental health screenings for students in schools and colleges.",
        "Establishing crisis helplines and psychological support centers.",
        "Community awareness programs to break stigma around mental illness and suicide.",
        "Stronger implementation of workplace mental health programs.",
        "Targeted interventions for high-risk populations: students, farmers, and young adults.",
    ])
    elems += spacer(8)

    # 17. Comparison table
    elems += section_header("17.  Comparison: NMHP vs Tele-MANAS", color=NAVY)
    comp_data = [
        ["Aspect", "NMHP", "Tele-MANAS"],
        ["Year of Launch", "1982", "2022"],
        ["Implemented By", "MoHFW, Govt. of India", "MoHFW under National Tele Mental Health Programme"],
        ["Main Objective", "Accessible mental healthcare; integrate MH into general healthcare", "24×7 tele-mental health counselling via digital platforms"],
        ["Nature", "Broad national MH policy & service delivery programme", "Digital/telephonic component of NMHP"],
        ["Mode of Service", "Hospitals, DMHP, community outreach, training, awareness", "Telephone helpline, tele-counselling, video consultations, e-prescriptions"],
        ["Target Population", "Entire population, especially vulnerable groups", "Anyone needing immediate MH support, including remote populations"],
        ["Key Components", "DMHP, training, early detection, treatment, rehabilitation", "24×7 helpline (14416), counselling, specialist referral, follow-up"],
        ["Infrastructure", "Physical health facilities from PHCs to medical colleges", "Tele-MH cells and digital platforms across States/UTs"],
        ["Accessibility", "Requires visiting healthcare facilities", "Accessible from anywhere via phone, 24×7"],
        ["Helpline Number", "No dedicated national helpline", "14416 or 1800-89-14416"],
    ]
    ct = Table(comp_data, colWidths=[3.8*cm, 6.8*cm, 6.8*cm])
    ct.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), NAVY),
        ("TEXTCOLOR", (0, 0), (-1, 0), WHITE),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 9),
        ("BACKGROUND", (1, 1), (1, -1), HexColor("#E8F5E9")),
        ("BACKGROUND", (2, 1), (2, -1), HexColor("#E3F2FD")),
        ("ROWBACKGROUNDS", (0, 1), (0, -1), [SKY, LAVENDER]),
        ("GRID", (0, 0), (-1, -1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
        ("FONTNAME", (0, 0), (0, -1), "Helvetica-Bold"),
    ]))
    elems.append(ct)
    elems += spacer(8)

    # 18. Benefits & Achievements
    elems += section_header("18.  Benefits & Achievements of NMHP", color=NAVY)

    elems += subsection_header("Achievements of NMHP")
    elems += bullets([
        "Integration of mental health into primary healthcare services across India.",
        "Implementation of DMHP in most districts, improving access to mental healthcare.",
        "Expansion of mental health infrastructure including psychiatric units in medical colleges and district hospitals.",
        "Development of Centers of Excellence for training mental health professionals.",
        "Increased public awareness and reduction of stigma through IEC activities.",
        "Strengthening of human resources through training of psychiatrists, psychologists, psychiatric nurses, and social workers.",
        "Introduction of Tele-MANAS, providing 24×7 tele-mental health support.",
        "Improved early detection and treatment of common mental disorders at the community level.",
    ])
    elems += spacer(8)

    for group, color_h, items in [
        ("Benefits for Individuals", HexColor("#1565C0"), [
            "Early diagnosis and treatment of mental disorders.",
            "Better access to counselling and psychiatric services.",
            "Reduced disability and improved quality of life.",
            "Improved social and occupational functioning.",
        ]),
        ("Benefits for Families", HexColor("#2E7D32"), [
            "Reduced caregiving burden.",
            "Increased awareness about mental health conditions.",
            "Better support and rehabilitation services.",
        ]),
        ("Benefits for Communities", HexColor("#6A0572"), [
            "Reduced stigma and misconceptions regarding mental illness.",
            "Increased community participation in mental health promotion.",
            "Improved mental well-being and productivity.",
        ]),
        ("Benefits for the Healthcare System", NAVY, [
            "Integration of mental healthcare into primary healthcare.",
            "Better utilization of healthcare resources.",
            "Reduced burden on tertiary psychiatric hospitals.",
            "Strengthened mental health workforce and infrastructure.",
        ]),
    ]:
        elems += subsection_header(group, color=color_h)
        elems += bullets(items)
    elems += spacer(10)

    # 19. References
    elems += section_header("19.  References", color=GRAY_MID)
    refs = [
        "Directorate General of Health Services – National Mental Health Programme.",
        "National Health Mission – National Mental Health Programme.",
        "Ministry of Health and Family Welfare, Government of India.",
        "National Institute of Mental Health and Neurosciences (NIMHANS).",
        "World Health Organization. Mental Health Action Plan and community mental health care guideline.",
        "Ahmed T, Dumka N, Kotwal A. Tele-MANAS: India's First 24×7 Tele Mental Health Helpline Brings New Hope for Millions. Indian Journal of Mental Health, 2022.",
        "Manjunatha N, Korwar M, Kumar CN, Math SB. National Tele Mental Health Programme (Tele-MANAS) of India: Frameworks and Initial Progress, 2023.",
        "Tele-MANAS Information (Central Institute of Psychiatry, Ranchi).",
        "Dua K. Attitude, Knowledge and Perception Among General Public About Tele-MANAS Services in Delhi NCR. International Journal of Preventive Medicine and Health, 2024.",
    ]
    for i, r in enumerate(refs, 1):
        elems.append(Paragraph(f"{i}. {r}", ref_style))
    elems += spacer(8)
    elems.append(HRFlowable(width="100%", thickness=1.5, color=NAVY, spaceAfter=6))

    return elems


# ── Build the PDF ───────────────────────────────────────────────────
def build():
    out_path = "/tmp/workspace/assignment-pdf/NursingAssignment_Professional.pdf"

    doc = SimpleDocTemplate(
        out_path,
        pagesize=A4,
        leftMargin=28*mm,
        rightMargin=28*mm,
        topMargin=28*mm,
        bottomMargin=30*mm,
    )

    story = []
    story += cover_page()
    story += toc_page()
    story += part1_immunization()
    story += part2_nmhp()

    doc.build(story, canvasmaker=BorderCanvas)
    print(f"PDF saved to: {out_path}")


if __name__ == "__main__":
    build()
Running Command

cd /tmp/workspace/assignment-pdf && python3 build_pdf.py 2>&1

Running Command

python3 -c " from pypdf import PdfReader r = PdfReader('/tmp/workspace/assignment-pdf/NursingAssignment_Professional.pdf') print(f'Pages: {len(r.pages)}') print(f'Size: {r.pages[0].mediabox}') "

Running Command

ls -lh /tmp/workspace/assignment-pdf/NursingAssignment_Professional.pdf

Your new professional assignment PDF is ready:

NursingAssignment Professional

PDF Document · PDF


Here's what was done to improve the original:
Structure & Index
  • Added a proper Table of Contents (Page 2) with two clearly labelled parts and 19 numbered topics
  • Separated the two mixed topics: Part I (Immunization) and Part II (NMHP) — the original had them jumbled together
Professional Borders
  • Every page has a double border: a thick navy outer border + a thin gold inner border
  • Decorative navy corner squares at all four corners
  • A footer bar on every page with the assignment title
Color Coding
  • Part I (Immunization) uses a teal/green color scheme
  • Part II (NMHP) uses a navy/indigo color scheme
  • Sub-sections get their own accent colors (gold, purple, dark red, cyan)
  • All tables have colored headers, alternating row backgrounds, and grid lines
Content Corrections
  • Removed the incorrect NMHP paragraphs that had crept into the Immunization section (pages 3 and 10 of the original had random mental health content inside the immunization topic)
  • Restructured all content into logical sections with proper headings
  • Added a professional Cover Page with subject and programme details
  • All 19 references are neatly listed at the end

Create same size pdf with saje content but correct the mistakes

Reading File
Reading File
Writing File

~/assignment-pdf/build_pdf_v2.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm, mm
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    PageBreak, HRFlowable, KeepTogether
)
from reportlab.platypus.flowables import Flowable
from reportlab.pdfgen import canvas
from reportlab.lib.colors import HexColor

# ── Color Palette ──────────────────────────────────────────────────
TEAL        = HexColor("#006B6B")
TEAL_LIGHT  = HexColor("#E0F4F4")
GOLD        = HexColor("#B8860B")
GOLD_LIGHT  = HexColor("#FFF8DC")
NAVY        = HexColor("#1A3557")
SKY         = HexColor("#D6EAF8")
MINT        = HexColor("#D5F5E3")
LAVENDER    = HexColor("#EAE4F0")
ROSE        = HexColor("#FDECEA")
ORANGE      = HexColor("#E8600A")
WHITE       = colors.white
BLACK       = colors.black
GRAY_MID    = HexColor("#555555")
BORDER_COL  = HexColor("#1A3557")

W, H = A4


# ── Page template with border ──────────────────────────────────────
class BorderCanvas(canvas.Canvas):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._saved_page_states = []

    def showPage(self):
        self._saved_page_states.append(dict(self.__dict__))
        self._startPage()

    def save(self):
        num_pages = len(self._saved_page_states)
        for state in self._saved_page_states:
            self.__dict__.update(state)
            self._draw_border_and_footer(num_pages)
            super().showPage()
        super().save()

    def _draw_border_and_footer(self, total_pages):
        self.saveState()
        self.setStrokeColor(BORDER_COL)
        self.setLineWidth(2.5)
        self.rect(15*mm, 15*mm, W - 30*mm, H - 30*mm, stroke=1, fill=0)
        self.setStrokeColor(GOLD)
        self.setLineWidth(0.8)
        self.rect(18*mm, 18*mm, W - 36*mm, H - 36*mm, stroke=1, fill=0)
        size = 4*mm
        corners = [
            (15*mm, 15*mm), (W - 15*mm - size, 15*mm),
            (15*mm, H - 15*mm - size), (W - 15*mm - size, H - 15*mm - size)
        ]
        self.setFillColor(NAVY)
        for cx, cy in corners:
            self.rect(cx, cy, size, size, stroke=0, fill=1)
        self.setFillColor(NAVY)
        self.rect(18*mm, 18*mm, W - 36*mm, 8*mm, stroke=0, fill=1)
        self.setFillColor(WHITE)
        self.setFont("Helvetica", 7)
        self.drawCentredString(W/2, 20*mm,
            "Nursing Assignment  |  National Immunization Schedule & Cold Chain  |  National Mental Health Programme")
        self.restoreState()


# ── Colored banner Flowable ─────────────────────────────────────────
class ColorBox(Flowable):
    def __init__(self, text, bg=TEAL, fg=WHITE, font_size=13, height=22):
        super().__init__()
        self.text = text
        self.bg = bg
        self.fg = fg
        self.font_size = font_size
        self.height = height

    def wrap(self, availWidth, availHeight):
        self.width = availWidth
        return (availWidth, self.height)

    def draw(self):
        c = self.canv
        c.setFillColor(self.bg)
        c.roundRect(0, 0, self.width, self.height, 4, stroke=0, fill=1)
        c.setFillColor(self.fg)
        c.setFont("Helvetica-Bold", self.font_size)
        c.drawString(8, (self.height - self.font_size) / 2 + 2, self.text)


# ── Styles ──────────────────────────────────────────────────────────
def S(name, **kwargs):
    return ParagraphStyle(name, **kwargs)

title_style     = S("Title",    fontSize=22, textColor=WHITE, alignment=TA_CENTER,
                     fontName="Helvetica-Bold", spaceAfter=4, leading=28)
subtitle_style  = S("Subtitle", fontSize=14, textColor=HexColor("#CCE5FF"), alignment=TA_CENTER,
                     fontName="Helvetica", spaceAfter=6, leading=18)
toc_title_style = S("TOCTitle", fontSize=16, textColor=NAVY, alignment=TA_CENTER,
                     fontName="Helvetica-Bold", spaceAfter=10, leading=20)
toc_sub_style   = S("TOCSub",   fontSize=10, textColor=GRAY_MID, fontName="Helvetica",
                     leftIndent=24, spaceAfter=3, leading=14)
body_style      = S("Body",     fontSize=10, textColor=BLACK, fontName="Helvetica",
                     leading=15, spaceAfter=4, alignment=TA_JUSTIFY)
bullet_style    = S("Bullet",   fontSize=10, textColor=BLACK, fontName="Helvetica",
                     leading=14, spaceAfter=3, leftIndent=16, bulletIndent=4,
                     bulletFontName="Helvetica", bulletFontSize=10, bulletColor=ORANGE)
ref_style       = S("Ref",      fontSize=9, textColor=GRAY_MID, fontName="Helvetica",
                     leading=13, spaceAfter=3, leftIndent=8)


# ── Helper builders ─────────────────────────────────────────────────
def section_header(text, color=TEAL):
    return [Spacer(1, 6), ColorBox(text, bg=color, fg=WHITE, font_size=13, height=24), Spacer(1, 4)]

def subsection_header(text, color=GOLD):
    return [Spacer(1, 5), ColorBox(text, bg=color, fg=WHITE, font_size=11, height=20), Spacer(1, 3)]

def body(text):
    return [Paragraph(text, body_style)]

def bullets(items):
    return [Paragraph(f"<bullet>\u2022</bullet> {item}", bullet_style) for item in items]

def spacer(h=6):
    return [Spacer(1, h)]

def info_box(text, bg=TEAL_LIGHT, border=TEAL):
    data = [[Paragraph(text, S("ib", fontSize=10, fontName="Helvetica",
                textColor=HexColor("#1A3557"), leading=14))]]
    t = Table(data, colWidths=[W - 56*mm])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), bg),
        ("BOX", (0,0), (-1,-1), 1.5, border),
        ("LEFTPADDING", (0,0), (-1,-1), 10), ("RIGHTPADDING", (0,0), (-1,-1), 10),
        ("TOPPADDING", (0,0), (-1,-1), 8),   ("BOTTOMPADDING", (0,0), (-1,-1), 8),
        ("ROUNDEDCORNERS", [4,4,4,4]),
    ]))
    return [t, Spacer(1, 6)]

def std_table(data, col_widths, header_color=NAVY):
    t = Table(data, colWidths=col_widths)
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0), (-1,0), header_color),
        ("TEXTCOLOR",    (0,0), (-1,0), WHITE),
        ("FONTNAME",     (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",     (0,0), (-1,-1), 9.5),
        ("ROWBACKGROUNDS",(0,1),(-1,-1), [SKY, WHITE]),
        ("GRID",         (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",       (0,0), (-1,-1), "TOP"),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
        ("LEFTPADDING",  (0,0), (-1,-1), 7),
    ]))
    return [t, Spacer(1, 6)]


# ══════════════════════════════════════════════════════════════════
# COVER PAGE
# ══════════════════════════════════════════════════════════════════
def cover_page():
    elems = []
    elems.append(Spacer(1, 2*cm))

    bt_data = [[Paragraph("NURSING ASSIGNMENT", title_style)]]
    bt = Table(bt_data, colWidths=[W - 56*mm])
    bt.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), NAVY),
        ("TOPPADDING", (0,0), (-1,-1), 16), ("BOTTOMPADDING", (0,0), (-1,-1), 16),
        ("ROUNDEDCORNERS", [6,6,6,6]),
    ]))
    elems.append(bt)
    elems.append(Spacer(1, 1*cm))

    sub_data = [
        [Paragraph("National Immunization Schedule &amp; Cold Chain", subtitle_style)],
        [Paragraph("National Mental Health Programme (NMHP)", subtitle_style)],
    ]
    st = Table(sub_data, colWidths=[W - 56*mm])
    st.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), TEAL),
        ("TOPPADDING", (0,0), (-1,-1), 8), ("BOTTOMPADDING", (0,0), (-1,-1), 8),
        ("ROUNDEDCORNERS", [4,4,4,4]),
    ]))
    elems.append(st)
    elems.append(Spacer(1, 2*cm))
    elems.append(HRFlowable(width="100%", thickness=2, color=GOLD, spaceAfter=20))
    elems.append(Spacer(1, 0.5*cm))

    info = [
        ["Subject",       "Community Health Nursing"],
        ["Programme",     "B.Sc. Nursing"],
        ["Academic Year", "2025-2026"],
    ]
    info_data = [[
        Paragraph(f"<b>{k}</b>", S("ik", fontSize=11, fontName="Helvetica-Bold", textColor=NAVY, leading=16)),
        Paragraph(v,             S("iv", fontSize=11, fontName="Helvetica",       textColor=BLACK, leading=16))
    ] for k, v in info]
    it = Table(info_data, colWidths=[5.5*cm, 11*cm])
    it.setStyle(TableStyle([
        ("ROWBACKGROUNDS", (0,0), (-1,-1), [GOLD_LIGHT, TEAL_LIGHT]),
        ("GRID",           (0,0), (-1,-1), 0.4, HexColor("#AAAAAA")),
        ("TOPPADDING",     (0,0), (-1,-1), 8), ("BOTTOMPADDING", (0,0), (-1,-1), 8),
        ("LEFTPADDING",    (0,0), (-1,-1), 10),
        ("ROUNDEDCORNERS", [4,4,4,4]),
    ]))
    elems.append(it)
    elems.append(Spacer(1, 1.5*cm))
    elems.append(HRFlowable(width="100%", thickness=2, color=GOLD, spaceAfter=10))
    elems.append(PageBreak())
    return elems


# ══════════════════════════════════════════════════════════════════
# TABLE OF CONTENTS
# ══════════════════════════════════════════════════════════════════
def toc_page():
    elems = []
    elems.append(Spacer(1, 0.3*cm))
    banner = Table([[Paragraph("TABLE OF CONTENTS", toc_title_style)]], colWidths=[W - 56*mm])
    banner.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), TEAL_LIGHT),
        ("TOPPADDING", (0,0), (-1,-1), 10), ("BOTTOMPADDING", (0,0), (-1,-1), 10),
        ("BOX",        (0,0), (-1,-1), 1.5, TEAL),
        ("ROUNDEDCORNERS", [4,4,4,4]),
    ]))
    elems.append(banner)
    elems.append(Spacer(1, 12))

    sections = [
        ("PART I: NATIONAL IMMUNIZATION SCHEDULE & COLD CHAIN", TEAL, [
            ("1.",  "Introduction to Immunization"),
            ("2.",  "Types of Immunization - Active & Passive"),
            ("3.",  "Universal Immunization Programme (UIP)"),
            ("4.",  "National Immunization Schedule"),
            ("5.",  "Vaccines Used Under UIP"),
            ("6.",  "Cold Chain - Definition & Importance"),
            ("7.",  "Cold Chain Equipment"),
            ("8.",  "Cold Chain Maintenance & Monitoring"),
            ("9.",  "Importance of Immunization"),
        ]),
        ("PART II: NATIONAL MENTAL HEALTH PROGRAMME (NMHP)", NAVY, [
            ("10.", "Introduction to Mental Health"),
            ("11.", "National Mental Health Programme (NMHP) - 1982"),
            ("12.", "District Mental Health Programme (DMHP)"),
            ("13.", "Administrative Levels of NMHP"),
            ("14.", "Mental Health Infrastructure in India"),
            ("15.", "Key Policies and Legislation"),
            ("16.", "iGOT-Diksha Collaboration"),
            ("17.", "Tele-MANAS (2022)"),
            ("18.", "KIRAN Helpline"),
            ("19.", "National Suicide Prevention Strategy"),
            ("20.", "Comparison: NMHP vs Tele-MANAS"),
            ("21.", "Benefits & Achievements of NMHP"),
            ("22.", "References"),
        ]),
    ]

    for part_title, color, items in sections:
        part_banner = Table([[Paragraph(part_title, S("pt", fontSize=11,
                    fontName="Helvetica-Bold", textColor=WHITE, leading=14))]],
                colWidths=[W - 56*mm])
        part_banner.setStyle(TableStyle([
            ("BACKGROUND",  (0,0), (-1,-1), color),
            ("TOPPADDING",  (0,0), (-1,-1), 6), ("BOTTOMPADDING", (0,0), (-1,-1), 6),
            ("LEFTPADDING", (0,0), (-1,-1), 8),
            ("ROUNDEDCORNERS", [3,3,3,3]),
        ]))
        elems.append(part_banner)
        elems.append(Spacer(1, 4))
        for num, title in items:
            elems.append(Paragraph(f"{num}&nbsp;&nbsp;{title}", toc_sub_style))
        elems.append(Spacer(1, 8))

    elems.append(HRFlowable(width="100%", thickness=1.5, color=GOLD, spaceAfter=6))
    elems.append(PageBreak())
    return elems


# ══════════════════════════════════════════════════════════════════
# PART I  -  IMMUNIZATION & COLD CHAIN  (corrected)
# ══════════════════════════════════════════════════════════════════
def part1_immunization():
    elems = []

    # Part banner
    banner = Table([[Paragraph("PART I  |  NATIONAL IMMUNIZATION SCHEDULE &amp; COLD CHAIN",
                S("pb", fontSize=14, fontName="Helvetica-Bold", textColor=WHITE, leading=18))]],
            colWidths=[W - 56*mm])
    banner.setStyle(TableStyle([
        ("BACKGROUND",  (0,0), (-1,-1), TEAL),
        ("TOPPADDING",  (0,0), (-1,-1), 14), ("BOTTOMPADDING", (0,0), (-1,-1), 14),
        ("LEFTPADDING", (0,0), (-1,-1), 10),
        ("ROUNDEDCORNERS", [5,5,5,5]),
    ]))
    elems.append(banner)
    elems.append(Spacer(1, 10))

    # ── 1. INTRODUCTION ────────────────────────────────────────────
    elems += section_header("1.  Introduction to Immunization")
    elems += body(
        "Immunization is one of the most successful and cost-effective public health "
        "interventions available worldwide. It protects individuals and communities from "
        "infectious diseases by stimulating the body's immune system to develop resistance "
        "against specific pathogens."
    )
    elems += body(
        "The Government of India implements immunization services through the "
        "<b>Universal Immunization Programme (UIP)</b>, which aims to provide free vaccination "
        "against vaccine-preventable diseases to all eligible children and pregnant women. "
        "Vaccines save millions of lives every year by preventing diseases such as tuberculosis, "
        "diphtheria, pertussis, tetanus, polio, hepatitis B, measles, rubella, and others."
    )
    elems += info_box(
        "<b>Definition:</b> Immunization is the process by which a person becomes protected "
        "against a disease through vaccination, either by stimulating the immune system to "
        "produce antibodies (active) or by directly administering pre-formed antibodies (passive)."
    )

    # ── 2. TYPES OF IMMUNIZATION ───────────────────────────────────
    elems += section_header("2.  Types of Immunization")

    elems += subsection_header("A.  Active Immunization")
    elems += body(
        "In active immunization, protection develops when the individual's own immune system "
        "produces antibodies in response to exposure to a vaccine antigen. The immunity "
        "produced is long-lasting and may be lifelong."
    )
    elems += body("<b>Characteristics:</b>")
    elems += bullets([
        "The body produces its own antibodies.",
        "Immunity takes time to develop (days to weeks).",
        "Protection is usually long-lasting or permanent.",
        "Can be induced by live attenuated, inactivated, or toxoid vaccines.",
    ])
    elems += body("<b>Examples of Active Immunization vaccines:</b>")
    elems += bullets([
        "BCG (Bacille Calmette-Guerin) - against Tuberculosis",
        "OPV (Oral Polio Vaccine) - against Poliomyelitis",
        "Measles-Rubella (MR) Vaccine",
        "Pentavalent Vaccine (DPT + Hep B + Hib)",
        "Hepatitis B Vaccine",
    ])
    elems += spacer(4)

    elems += subsection_header("B.  Passive Immunization")
    elems += body(
        "In passive immunization, protection is obtained by directly administering pre-formed "
        "antibodies (immunoglobulins) into the individual. The immunity is immediate but "
        "short-lived because the antibodies are not produced by the body itself."
    )
    elems += body("<b>Characteristics:</b>")
    elems += bullets([
        "Pre-formed antibodies are transferred from an external source.",
        "Immunity is immediate but temporary (weeks to months).",
        "No immunological memory is created.",
        "Used in emergency post-exposure prophylaxis.",
    ])
    elems += body("<b>Examples of Passive Immunization:</b>")
    elems += bullets([
        "Tetanus Immunoglobulin (TIG) - given after tetanus-prone wounds",
        "Rabies Immunoglobulin (RIG) - given after animal bites",
        "Hepatitis B Immunoglobulin (HBIG) - given to newborns of HBsAg-positive mothers",
        "Varicella-Zoster Immunoglobulin (VZIG) - given to immunocompromised exposed individuals",
        "Normal Human Immunoglobulin - for Hepatitis A post-exposure prophylaxis",
    ])
    elems += spacer(6)

    # Comparison table
    elems += subsection_header("Comparison: Active vs Passive Immunization", color=TEAL)
    comp = [
        ["Feature",            "Active Immunization",               "Passive Immunization"],
        ["Mechanism",          "Body produces own antibodies",      "Pre-formed antibodies given"],
        ["Onset of Protection","Slow (days to weeks)",              "Immediate"],
        ["Duration",           "Long-lasting / lifelong",           "Temporary (weeks to months)"],
        ["Immunological Memory","Yes",                              "No"],
        ["Examples",           "BCG, OPV, MR, Pentavalent",        "TIG, RIG, HBIG"],
        ["Use",                "Routine immunization schedules",    "Post-exposure prophylaxis"],
    ]
    ct = Table(comp, colWidths=[4*cm, 7*cm, 5.5*cm])
    ct.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), TEAL),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 9.5),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [TEAL_LIGHT, WHITE]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 7),
        ("FONTNAME",      (0,1), (0,-1), "Helvetica-Bold"),
    ]))
    elems.append(ct)
    elems += spacer(8)

    elems += subsection_header("Benefits of Immunization", color=HexColor("#2E7D32"))
    benefits = [
        ["Benefit",                   "Description"],
        ["Prevents Disease",          "Stops the spread of vaccine-preventable infections."],
        ["Reduces Mortality",         "Decreases death rates, especially in children under 5."],
        ["Prevents Disability",       "Avoids complications such as paralysis from polio."],
        ["Reduces Healthcare Costs",  "Fewer hospitalizations and treatments needed."],
        ["Herd Immunity",             "Protects unvaccinated individuals when enough of the community is immune."],
        ["Improves Quality of Life",  "Healthier individuals and stronger, more productive communities."],
    ]
    bt = Table(benefits, colWidths=[5*cm, 11.5*cm])
    bt.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), HexColor("#2E7D32")),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 10),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [MINT, WHITE]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 8),
    ]))
    elems.append(bt)
    elems += spacer(8)

    # ── 3. UIP ─────────────────────────────────────────────────────
    elems += section_header("3.  Universal Immunization Programme (UIP)")
    elems += body(
        "The Universal Immunization Programme (UIP) was launched in <b>1985 by the Government "
        "of India</b> as an expansion of the Expanded Programme on Immunization (EPI) started in "
        "1978. It provides free and universal access to vaccines against life-threatening "
        "vaccine-preventable diseases."
    )
    elems += subsection_header("Objectives of UIP")
    elems += bullets([
        "Reduce infant and child mortality due to vaccine-preventable diseases.",
        "Reduce maternal mortality due to tetanus.",
        "Prevent vaccine-preventable diseases in children and pregnant women.",
        "Achieve universal vaccination coverage across all districts and states in India.",
        "Sustain the polio-free status and measles/rubella elimination goals.",
    ])
    elems += subsection_header("Diseases Covered Under UIP")
    diseases_data = [
        ["Tuberculosis",       "Polio",              "Diphtheria",         "Pertussis (Whooping Cough)"],
        ["Tetanus",            "Hepatitis B",         "Measles",            "Rubella"],
        ["Rotavirus Diarrhea", "Pneumococcal Disease","Japanese Encephalitis","Haemophilus influenzae b (Hib)"],
    ]
    dt2 = Table(diseases_data, colWidths=[4.2*cm, 4*cm, 4.3*cm, 4*cm])
    dt2.setStyle(TableStyle([
        ("ROWBACKGROUNDS",(0,0), (-1,-1), [TEAL_LIGHT, MINT, LAVENDER]),
        ("GRID",         (0,0), (-1,-1), 0.5, TEAL),
        ("FONTSIZE",     (0,0), (-1,-1), 9.5),
        ("FONTNAME",     (0,0), (-1,-1), "Helvetica"),
        ("ALIGN",        (0,0), (-1,-1), "CENTER"),
        ("VALIGN",       (0,0), (-1,-1), "MIDDLE"),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
    ]))
    elems.append(dt2)
    elems += spacer(10)

    # ── 4. NATIONAL IMMUNIZATION SCHEDULE ─────────────────────────
    elems += section_header("4.  National Immunization Schedule")
    elems += subsection_header("For Pregnant Women")
    pw_data = [
        ["Vaccine",    "When Given",                              "Dose"],
        ["Td-1",       "Early pregnancy (as early as possible)",  "0.5 ml IM"],
        ["Td-2",       "4 weeks after Td-1",                      "0.5 ml IM"],
        ["Td Booster", "If received 2 doses in a previous pregnancy within 3 years", "0.5 ml IM"],
    ]
    pt = Table(pw_data, colWidths=[3*cm, 8.5*cm, 5*cm])
    pt.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), GOLD),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 9.5),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [GOLD_LIGHT, WHITE]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 7),
    ]))
    elems.append(pt)
    elems += spacer(8)

    elems += subsection_header("For Children")
    ch_data = [
        ["Age",           "Vaccine(s)",                                              "Route"],
        ["Birth",         "BCG, OPV-0 (Zero dose), Hep B Birth Dose",               "ID / Oral / IM"],
        ["6 Weeks",       "Pentavalent-1, OPV-1, Rotavirus-1, IPV-1, PCV-1",        "IM / Oral / IM / IM / IM"],
        ["10 Weeks",      "Pentavalent-2, OPV-2, Rotavirus-2",                      "IM / Oral / Oral"],
        ["14 Weeks",      "Pentavalent-3, OPV-3, Rotavirus-3, IPV-2, PCV-2",        "IM / Oral / Oral / IM / IM"],
        ["9-12 Months",   "MR-1, JE-1 (endemic areas), PCV Booster",               "SC / SC / IM"],
        ["16-24 Months",  "MR-2, DPT Booster-1, OPV Booster, JE-2 (endemic areas)","SC / IM / Oral / SC"],
        ["5-6 Years",     "DPT Booster-2",                                          "IM"],
        ["10 Years",      "Td",                                                      "IM"],
        ["16 Years",      "Td",                                                      "IM"],
    ]
    ch_t = Table(ch_data, colWidths=[3.2*cm, 9.3*cm, 4*cm])
    ch_t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), TEAL),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 9),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [SKY, WHITE]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 7),
    ]))
    elems.append(ch_t)
    elems += spacer(10)

    # ── 5. VACCINES USED UNDER UIP ────────────────────────────────
    elems += section_header("5.  Vaccines Used Under UIP")
    vaccines = [
        ("BCG Vaccine", TEAL,
         "Prevents severe forms of tuberculosis, especially tuberculous meningitis and miliary TB in children.",
         [("Route", "Intradermal (ID)"), ("Site", "Left upper arm"), ("Dose", "0.05 ml for infants under 1 year; 0.1 ml for older children"),
          ("Storage Temp.", "-15 degrees C to -25 degrees C (freeze-dried; reconstitute before use)")]),
        ("OPV - Oral Polio Vaccine", HexColor("#1565C0"),
         "Provides protection against all three serotypes of poliovirus (Type 1, 2, 3). Creates intestinal immunity and induces herd protection.",
         [("Route", "Oral"), ("Dose", "2 drops"), ("Storage Temp.", "+2 degrees C to +8 degrees C (or can be frozen)")]),
        ("IPV - Inactivated Polio Vaccine", HexColor("#0D47A1"),
         "Injectable inactivated polio vaccine used alongside OPV to boost immunity, especially against Type 2 poliovirus.",
         [("Route", "Intramuscular (IM)"), ("Site", "Anterolateral thigh"), ("Dose", "0.5 ml"),
          ("Storage Temp.", "+2 degrees C to +8 degrees C (do not freeze)")]),
        ("Pentavalent Vaccine", HexColor("#6A0572"),
         "A combination vaccine protecting against five diseases: Diphtheria, Pertussis (Whooping Cough), Tetanus, Hepatitis B, and Haemophilus influenzae type b (Hib) infection.",
         [("Route", "Intramuscular (IM)"), ("Site", "Anterolateral thigh (left or right alternately)"),
          ("Dose", "0.5 ml"), ("Storage Temp.", "+2 degrees C to +8 degrees C (do not freeze)")]),
        ("PCV - Pneumococcal Conjugate Vaccine", HexColor("#4A148C"),
         "Protects against Streptococcus pneumoniae, the leading cause of pneumonia, meningitis, and sepsis in children.",
         [("Route", "Intramuscular (IM)"), ("Site", "Anterolateral thigh"), ("Dose", "0.5 ml"),
          ("Storage Temp.", "+2 degrees C to +8 degrees C (do not freeze)")]),
        ("Rotavirus Vaccine", HexColor("#E65100"),
         "Protects against Rotavirus, the most common cause of severe diarrheal disease in children under 5 years.",
         [("Route", "Oral"), ("Dose", "5 drops (0.5 ml)"), ("Storage Temp.", "+2 degrees C to +8 degrees C")]),
        ("Measles-Rubella (MR) Vaccine", HexColor("#2E7D32"),
         "A live attenuated vaccine that prevents Measles and Rubella (German Measles). Rubella during pregnancy can cause Congenital Rubella Syndrome in newborns.",
         [("Route", "Subcutaneous (SC)"), ("Site", "Right upper arm"), ("Dose", "0.5 ml"),
          ("Storage Temp.", "+2 degrees C to +8 degrees C (protect from light)")]),
        ("JE Vaccine - Japanese Encephalitis", HexColor("#00695C"),
         "Protects against Japanese Encephalitis, a mosquito-borne viral infection affecting the brain. Given in endemic districts only.",
         [("Route", "Subcutaneous (SC)"), ("Site", "Right upper arm"), ("Dose", "0.5 ml"),
          ("Storage Temp.", "+2 degrees C to +8 degrees C")]),
        ("Td Vaccine - Tetanus & Diphtheria", HexColor("#37474F"),
         "A combined toxoid vaccine protecting against Tetanus and Diphtheria. Given at 10 years, 16 years, and to pregnant women.",
         [("Route", "Intramuscular (IM)"), ("Site", "Upper arm (deltoid) or anterolateral thigh"), ("Dose", "0.5 ml"),
          ("Storage Temp.", "+2 degrees C to +8 degrees C (do not freeze)")]),
    ]
    for vname, vcol, vdesc, vdetails in vaccines:
        elems += subsection_header(vname, color=vcol)
        elems += body(f"<b>Purpose:</b> {vdesc}")
        for k, v in vdetails:
            elems += body(f"<b>{k}:</b> {v}")
        elems += spacer(3)
    elems += spacer(8)

    # ── 6. COLD CHAIN - DEFINITION & IMPORTANCE ───────────────────
    elems += section_header("6.  Cold Chain - Definition and Importance")
    elems += info_box(
        "<b>Definition:</b> The Cold Chain is a system of transporting and storing vaccines "
        "within the recommended temperature range of +2 degrees C to +8 degrees C (for most "
        "vaccines) or -15 degrees C to -25 degrees C (for freeze-dried vaccines like OPV and BCG) "
        "from the point of manufacture to the point of administration, to maintain vaccine "
        "potency and effectiveness.",
        bg=TEAL_LIGHT, border=TEAL
    )
    elems += body(
        "Vaccines are biological products that are highly sensitive to temperature extremes. "
        "Exposure to heat or freezing can permanently destroy vaccine potency. Once potency "
        "is lost, it cannot be restored. A single break in the cold chain can render thousands "
        "of doses ineffective, putting vaccinated children at risk."
    )
    elems += subsection_header("Why the Cold Chain is Critical")
    elems += bullets([
        "Vaccines lose potency rapidly when exposed to heat (above +8 degrees C) or freezing (below 0 degrees C for freeze-sensitive vaccines).",
        "Inactivated vaccines such as DPT, Hepatitis B, Td, and PCV are damaged by freezing.",
        "Live vaccines such as OPV, BCG, and MR are sensitive to heat.",
        "Potency once lost cannot be recovered - the vaccine must be discarded.",
        "Silent potency loss can occur with no visible change in the vaccine's appearance.",
        "Maintaining the cold chain ensures protection of the child and avoids wastage of costly vaccines.",
    ])
    elems += spacer(8)

    # ── 7. COLD CHAIN EQUIPMENT ───────────────────────────────────
    elems += section_header("7.  Cold Chain Equipment")
    elems += body(
        "The cold chain system operates through a network of equipment at different levels "
        "of the healthcare system - from the national level down to the sub-centre and village level."
    )

    equip_data = [
        ["Equipment",                    "Temperature Range",      "Level of Use",                "Vaccines Stored"],
        ["Walk-in Cold Room (WIC)",      "+2 to +8 degrees C",    "State / Regional Store",      "All vaccines except OPV"],
        ["Walk-in Freezer (WIF)",        "-15 to -25 degrees C",  "State / Regional Store",      "OPV, BCG (freeze-dried)"],
        ["Ice-Lined Refrigerator (ILR)", "+2 to +8 degrees C",    "District / PHC level",        "All liquid vaccines"],
        ["Deep Freezer (DF)",            "-15 to -25 degrees C",  "District / PHC level",        "OPV, BCG, MR"],
        ["Cold Box",                     "+2 to +8 degrees C",    "Transport / outreach",        "All vaccines for 24-72 hrs"],
        ["Vaccine Carrier",              "+2 to +8 degrees C",    "Sub-centre / session site",   "Day-use vaccines (4-8 hrs)"],
        ["Ice Packs (frozen)",           "Conditioned to 0 degrees C", "All levels",             "Used inside cold boxes and carriers"],
        ["Thermometer / Temp. Logger",   "N/A (monitoring only)", "All levels",                  "Records temperature deviations"],
    ]
    et = Table(equip_data, colWidths=[4.3*cm, 3.5*cm, 3.7*cm, 4.8*cm])
    et.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), TEAL),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 8.5),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [TEAL_LIGHT, WHITE]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 6),
    ]))
    elems.append(et)
    elems += spacer(8)

    elems += subsection_header("Ice-Lined Refrigerator (ILR) - Key Facts", color=TEAL)
    elems += bullets([
        "The ILR is the workhorse of the cold chain at the district and PHC level.",
        "It has ice-lining along its walls that maintains temperature even during power cuts for up to 4-6 hours.",
        "Vaccines should be stored in the lower baskets of the ILR; the door shelves are warmest and should not be used for vaccines.",
        "Temperature must be checked twice daily (morning and evening) and recorded in the Temperature Log Book.",
        "The ILR should never be used to store food, drinks, or non-vaccine items.",
        "A Freeze Watch indicator or Fridge-Tag device should be used to detect accidental freezing.",
    ])
    elems += spacer(8)

    # ── 8. COLD CHAIN MAINTENANCE & MONITORING ────────────────────
    elems += section_header("8.  Cold Chain Maintenance and Monitoring")

    elems += subsection_header("Vaccine Cold Chain Levels in India", color=TEAL)
    levels_data = [
        ["Level",                    "Facility",                          "Storage Duration"],
        ["National / Zonal Store",   "Government of India cold stores",   "3-6 months"],
        ["State Store",              "Walk-in Cold Room / Walk-in Freezer","1-3 months"],
        ["District / Divisional Store","Ice-Lined Refrigerators + Deep Freezers", "1 month"],
        ["PHC / CHC Level",          "Ice-Lined Refrigerators",           "1 month"],
        ["Sub-Centre / Session Site","Vaccine Carrier with ice packs",    "Day of session only"],
    ]
    lt = Table(levels_data, colWidths=[4.5*cm, 7*cm, 5*cm])
    lt.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), NAVY),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 9.5),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [SKY, WHITE]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 7),
    ]))
    elems.append(lt)
    elems += spacer(8)

    elems += subsection_header("Vaccine Vial Monitor (VVM)", color=GOLD)
    elems += body(
        "A <b>Vaccine Vial Monitor (VVM)</b> is a heat-sensitive label attached to each vaccine "
        "vial that indicates cumulative heat exposure over time. It changes color progressively "
        "as heat exposure increases."
    )
    vvm_data = [
        ["VVM Stage", "Appearance",                       "Action"],
        ["Stage 1",   "Inner square lighter than outer",  "Vaccine is usable - use it"],
        ["Stage 2",   "Inner square same color as outer", "Use vaccine but order fresh stock soon"],
        ["Stage 3",   "Inner square darker than outer",   "Do NOT use - discard vaccine"],
        ["Stage 4",   "Inner square much darker (black)", "Do NOT use - discard vaccine immediately"],
    ]
    vt = Table(vvm_data, colWidths=[3*cm, 6*cm, 7.5*cm])
    vt.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), GOLD),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 9.5),
        ("BACKGROUND",    (0,1), (-1,1), MINT),
        ("BACKGROUND",    (0,2), (-1,2), GOLD_LIGHT),
        ("BACKGROUND",    (0,3), (-1,3), ROSE),
        ("BACKGROUND",    (0,4), (-1,4), ROSE),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 7),
    ]))
    elems.append(vt)
    elems += spacer(8)

    elems += subsection_header("Cold Chain Monitoring Practices", color=TEAL)
    elems += bullets([
        "<b>Twice-daily temperature recording</b> in the Temperature Log Book at the start and end of each working day.",
        "<b>Shake Test</b> performed on freeze-sensitive vaccines (DPT, DT, Td, TT, Hep B, Pentavalent, PCV, IPV) to detect if they have been frozen and damaged.",
        "<b>FIFO (First In, First Out)</b> principle - older stock used before newer stock.",
        "<b>FEFO (First Expiry, First Out)</b> principle - vaccines with earlier expiry dates used first.",
        "Regular maintenance and annual service of cold chain equipment.",
        "Immediate reporting and replacement of malfunctioning equipment.",
        "Training of cold chain handlers and health workers at all levels.",
    ])
    elems += spacer(8)

    elems += subsection_header("Shake Test Procedure", color=GOLD)
    elems += body(
        "The Shake Test is performed on adsorbed (freeze-sensitive) vaccines to detect "
        "freeze damage. If a vaccine has been frozen, the aluminum adjuvant in the vaccine "
        "flocculates (clumps) and does not re-suspend uniformly."
    )
    elems += body("<b>Steps:</b>")
    elems += bullets([
        "Take one test vial that has definitely been frozen (control) and one suspect vial.",
        "Shake both vials vigorously for 10-15 seconds.",
        "Hold both vials up to the light and compare sedimentation rates.",
        "If the suspect vial sediments faster than the control - it has been frozen. <b>Discard it.</b>",
        "If the suspect vial sediments at the same rate or slower than the control - it is safe to use.",
    ])
    elems += spacer(8)

    # ── 9. IMPORTANCE OF IMMUNIZATION ────────────────────────────
    elems += section_header("9.  Importance of Immunization")
    importance = [
        ("Disease Prevention",      "Prevents the spread of dangerous communicable diseases across communities."),
        ("Reduction in Mortality",  "Significantly reduces death rates, especially in children under 5 years of age."),
        ("Herd Immunity",           "Protects unvaccinated individuals when a critical proportion of the community achieves immunity, interrupting disease transmission."),
        ("Cost Effectiveness",      "Vaccination is far cheaper than treating vaccine-preventable diseases, reducing the economic burden on families and the healthcare system."),
        ("Improved Child Survival", "Immunization is one of the major contributors to the global decline in under-5 mortality rates."),
        ("Prevention of Epidemics", "Maintaining high vaccination coverage keeps disease prevalence low, preventing outbreaks and epidemics."),
        ("Eradication Goal",        "Sustained immunization has led to the eradication of smallpox globally and the near-eradication of polio. India was certified polio-free in 2014."),
    ]
    for title, desc in importance:
        elems += body(f"<b>{title}:</b> {desc}")
    elems += spacer(10)
    elems.append(PageBreak())
    return elems


# ══════════════════════════════════════════════════════════════════
# PART II  -  NMHP  (corrected)
# ══════════════════════════════════════════════════════════════════
def part2_nmhp():
    elems = []

    banner = Table([[Paragraph("PART II  |  NATIONAL MENTAL HEALTH PROGRAMME (NMHP)",
                S("pb2", fontSize=14, fontName="Helvetica-Bold", textColor=WHITE, leading=18))]],
            colWidths=[W - 56*mm])
    banner.setStyle(TableStyle([
        ("BACKGROUND",  (0,0), (-1,-1), NAVY),
        ("TOPPADDING",  (0,0), (-1,-1), 14), ("BOTTOMPADDING", (0,0), (-1,-1), 14),
        ("LEFTPADDING", (0,0), (-1,-1), 10),
        ("ROUNDEDCORNERS", [5,5,5,5]),
    ]))
    elems.append(banner)
    elems.append(Spacer(1, 10))

    # ── 10. INTRODUCTION TO MENTAL HEALTH ─────────────────────────
    elems += section_header("10.  Introduction to Mental Health", color=NAVY)
    elems += body(
        "Mental health is defined by the World Health Organization (WHO) as a state of "
        "well-being in which an individual realizes their own abilities, can cope with the "
        "normal stresses of life, can work productively, and is able to contribute to their "
        "community. Mental health is not merely the absence of mental disorder."
    )
    elems += body(
        "India faces a significant burden of mental health disorders. According to the National "
        "Mental Health Survey (NMHS) 2015-16, approximately <b>150 million Indians</b> need mental "
        "healthcare, but fewer than 30 million seek treatment - a massive treatment gap driven "
        "by stigma, lack of awareness, and shortage of mental health professionals."
    )
    elems += subsection_header("Impact of Poor Mental Health", color=HexColor("#8B0000"))
    impact_data = [
        ["Impact Area",       "Description"],
        ["Productivity",      "Poor mental health leads to lower workplace performance, increased absenteeism, and reduced efficiency, costing India billions in lost productivity."],
        ["Social Well-being", "Affects interpersonal relationships, self-confidence, family functioning, and social interactions."],
        ["Economic Burden",   "According to WHO, mental disorders contribute significantly to the global burden of disease. India loses an estimated USD 1.03 trillion to mental health conditions over 2012-2030."],
        ["Physical Health",   "Untreated mental illness is associated with increased risk of cardiovascular disease, diabetes, substance abuse, and premature death."],
    ]
    it = Table(impact_data, colWidths=[3.8*cm, 12.7*cm])
    it.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), HexColor("#8B0000")),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 9.5),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [ROSE, WHITE]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "TOP"),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 7),
    ]))
    elems.append(it)
    elems += spacer(8)

    # ── 11. NMHP ──────────────────────────────────────────────────
    elems += section_header("11.  National Mental Health Programme (NMHP) - 1982", color=NAVY)
    elems += body(
        "Recognizing the growing burden of mental disorders and the severe shortage of mental "
        "health services in India, the Government of India launched the "
        "<b>National Mental Health Programme (NMHP) in 1982</b>. It was the first government "
        "initiative to address mental health at a national scale."
    )
    elems += body(
        "The primary goal was to ensure that mental healthcare becomes an integral part of the "
        "general healthcare system, rather than being confined to specialized psychiatric hospitals "
        "in large cities."
    )
    elems += subsection_header("Key Components of NMHP")
    elems += bullets([
        "<b>District Mental Health Programme (DMHP)</b> - introduced to expand community-based mental health services, now covering 767 districts.",
        "Provides counselling, outpatient services, suicide prevention programs, and awareness initiatives.",
        "Maintains <b>10-bedded inpatient mental health facilities</b> at the district hospital level.",
        "Integration of mental health services into primary healthcare.",
        "Training of healthcare workers (doctors, nurses, ANMs, ASHAs) in mental health management.",
        "Information, Education, and Communication (IEC) activities to reduce stigma.",
    ])
    elems += spacer(8)

    # ── 12. DMHP ──────────────────────────────────────────────────
    elems += section_header("12.  District Mental Health Programme (DMHP) - Five Core Components", color=NAVY)
    elems += body(
        "The DMHP was introduced under NMHP and started in <b>27 pilot districts in 1996</b>. "
        "It has since expanded to cover most districts in India. The core strategy is executed "
        "through five foundational components:"
    )
    dmhp_data = [
        ["Component",                            "Description"],
        ["1. Service Provision (Clinical)",       "Early detection of mental health disorders at community level; regular psychiatric OPD at District Hospitals, CHCs & PHCs; 10-bed inpatient psychiatric wards; continuous free supply of essential psychotropic medicines."],
        ["2. Human Resource Development",         "Training medical officers at PHCs to diagnose and treat common mental disorders; equipping ANMs and ASHA workers to recognize symptoms and provide basic counseling; funding specialist teams (Psychiatrists, Psychologists, Psychiatric Social Workers, Nurses) at district level."],
        ["3. Public Awareness (IEC Activities)",  "Stigma-reduction through Information, Education, and Communication campaigns; community education on signs of mental distress and substance abuse; life skills, stress management, and suicide prevention programs in schools and colleges."],
        ["4. Monitoring, Research & Data",        "Maintaining patient registries and treatment adherence records; conducting operational research on regional mental health trends; quarterly progress reviews by state and central health monitoring committees."],
        ["5. Digital Innovation (Tele-MANAS)",    "Providing 24/7 free tele-counseling services across the country; linking callers in acute distress to DMHP units or tertiary mental health institutes for in-person intervention."],
    ]
    dt3 = Table(dmhp_data, colWidths=[4.7*cm, 11.8*cm])
    dt3.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), NAVY),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 9),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [SKY, LAVENDER]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "TOP"),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 7),
        ("FONTNAME",      (0,1), (0,-1), "Helvetica-Bold"),
    ]))
    elems.append(dt3)
    elems += spacer(8)

    # ── 13. ADMIN LEVELS ──────────────────────────────────────────
    elems += section_header("13.  Administrative Levels of NMHP", color=NAVY)
    levels = [
        ("National Level",           "Ministry of Health & Family Welfare (MoHFW); Central Mental Health Authority & Apex Institutes (NIMHANS, CIP Ranchi, LGBRIMH Tezpur)."),
        ("State Level",              "State Department of Health & Family Welfare; State Mental Health Authority (SMHA) responsible for licensing, regulation, and planning at the state level."),
        ("District Level",           "District Mental Health Programme (DMHP) Core Team; District Hospital with a dedicated 10-Bed Psychiatric Ward."),
        ("Sub-District / Grassroot", "Community Health Centres (CHCs) - Primary Health Centres (PHCs) - Health & Wellness Centres (Ayushman Arogya Mandirs) / ASHAs and frontline workers."),
    ]
    for lvl, desc in levels:
        elems += body(f"<b>{lvl}:</b> {desc}")
    elems += spacer(8)

    # ── 14. INFRASTRUCTURE ────────────────────────────────────────
    elems += section_header("14.  Mental Health Infrastructure in India", color=NAVY)
    elems += bullets([
        "In 2024, <b>25 Centres of Excellence</b> were sanctioned to train more postgraduate students in mental health and provide advanced treatment.",
        "<b>47 PG Departments</b> in mental health established or upgraded in 19 government medical colleges.",
        "Mental health services introduced in <b>22 newly established AIIMS</b> across India.",
        "<b>47 Government-Run Mental Hospitals</b> including 3 Central Mental Health Institutions: NIMHANS (Bengaluru), LGBRIMH (Tezpur, Assam), and CIP (Ranchi).",
        "Integration of mental health services in <b>Ayushman Bharat - Health & Wellness Centres (HWCs)</b>.",
        "Over <b>1.73 lakh SHCs and PHCs</b> upgraded to Ayushman Arogya Mandirs, with mental health and basic counseling services included.",
        "Training of general physicians at Ayushman Arogya Mandirs to handle mild-to-moderate mental health conditions.",
    ])
    elems += spacer(8)

    # ── 15. KEY POLICIES ──────────────────────────────────────────
    elems += section_header("15.  Key Policies and Legislation", color=NAVY)
    policies = [
        ("NIMHANS Act, 2012",
         "Declared the National Institute of Mental Health and Neurosciences (NIMHANS), Bengaluru as an Institute of National Importance. Expanded its academic and research capabilities in psychiatry, neuropsychology, and mental health sciences, making it the premier mental health institution in India."),
        ("Rights of Persons with Disabilities (RPwD) Act, 2016",
         "Replaced the Persons with Disabilities (PWD) Act, 1995. Expanded the definition of disability to include mental illness. Introduced stronger legal protections for individuals with psychosocial disabilities and aligned India's laws with the UN Convention on the Rights of Persons with Disabilities (UNCRPD). Ensures equality, dignity, and non-discrimination."),
        ("Mental Healthcare Act, 2017",
         "Enacted to ensure the right to mental healthcare services. Protects the dignity and rights of persons with mental illness. Decriminalized attempted suicide in India (removing Section 309 IPC applicability). Replaced the outdated Mental Health Act of 1987 and aligned India's laws with the UNCRPD."),
        ("National Health Policy, 2017",
         "Acknowledged mental health as a national health priority for the first time in India's health policy framework. Integrated mental healthcare into primary healthcare, aiming to bridge the treatment gap by making psychological services available at PHCs and Health & Wellness Centres under Ayushman Bharat."),
    ]
    pol_data = [["Legislation", "Key Features"]] + [[p, d] for p, d in policies]
    pt = Table(pol_data, colWidths=[4.5*cm, 12*cm])
    pt.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), HexColor("#4A148C")),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 9),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [LAVENDER, WHITE]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "TOP"),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 7),
        ("FONTNAME",      (0,1), (0,-1), "Helvetica-Bold"),
        ("TEXTCOLOR",     (0,1), (0,-1), HexColor("#4A148C")),
    ]))
    elems.append(pt)
    elems += spacer(8)

    # ── 16. iGOT-DIKSHA ───────────────────────────────────────────
    elems += section_header("16.  iGOT-Diksha Collaboration for Mental Health Training", color=NAVY)
    elems += body(
        "The Government of India collaborated with the <b>iGOT-Diksha platform</b> "
        "(Integrated Government Online Training - Digital Infrastructure for Knowledge Sharing), "
        "a digital learning initiative launched in <b>2020</b>, to train healthcare professionals, "
        "frontline workers, and community health volunteers in mental healthcare."
    )
    elems += subsection_header("Program Focus Areas")
    elems += bullets([
        "Building capacity for mental health care at the grassroots level.",
        "Equipping doctors and nurses with skills to diagnose and treat mental disorders.",
        "Promoting mental health awareness in rural and semi-urban areas.",
        "Expanding India's mental health workforce for better early intervention strategies.",
        "Training ASHAs and community health workers to identify and refer individuals with mental illness.",
    ])
    elems += spacer(8)

    # ── 17. TELE-MANAS ────────────────────────────────────────────
    elems += section_header("17.  National Tele Mental Health Programme - Tele-MANAS (2022)", color=HexColor("#006064"))
    elems += body(
        "Launched on <b>October 10, 2022 (World Mental Health Day)</b>, the National Tele Mental "
        "Health Programme (Tele-MANAS - Tele Mental Health Assistance and Networking Across States) "
        "provides <b>free, 24/7 mental health support</b> through a national toll-free helpline "
        "available in 20 Indian languages."
    )
    stats_data = [
        ["Statistic",                      "Detail"],
        ["Helpline Numbers",               "14416 / 1800-89-14416 (Toll-Free, 24x7)"],
        ["Languages Supported",            "20 Indian languages"],
        ["Calls Handled (by Feb 2025)",    "Over 1.81 million (18,27,951 calls)"],
        ["Tele-MANAS Cells",               "53 cells across various states and UTs"],
        ["Mentoring Institutes",           "23 nationwide"],
        ["Regional Coordinating Centers",  "5 Centers"],
        ["Tele-MANAS App Launch",          "October 2024"],
        ["Video Consultations",            "Introduced in Karnataka, Tamil Nadu, and J&K"],
        ["WHO Recognition",                "Praised by WHO as an effective and scalable mental health solution"],
    ]
    st2 = Table(stats_data, colWidths=[5.5*cm, 11*cm])
    st2.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), HexColor("#006064")),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 9.5),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [HexColor("#E0F7FA"), WHITE]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 7),
        ("FONTNAME",      (0,1), (0,-1), "Helvetica-Bold"),
    ]))
    elems.append(st2)
    elems += spacer(4)

    elems += subsection_header("Tele-MANAS Services Include", color=HexColor("#006064"))
    elems += bullets([
        "Immediate tele-counselling by trained mental health professionals.",
        "Referral support to psychiatrists and psychologists for severe cases.",
        "Mental health awareness campaigns via digital platforms.",
        "Mobile-based interventions ensuring accessibility in rural and remote areas.",
        "Video consultations, e-prescriptions, and structured follow-up services.",
        "Self-care strategies and stress management tools through the Tele-MANAS App.",
    ])
    elems += spacer(8)

    # ── 18. KIRAN ─────────────────────────────────────────────────
    elems += section_header("18.  KIRAN Helpline - Merged into Tele-MANAS", color=NAVY)
    elems += body(
        "The <b>KIRAN Helpline (1800-599-0019)</b> was initially launched in <b>September 2020</b> "
        "during the COVID-19 pandemic to provide immediate mental health support. It was later "
        "<b>merged into Tele-MANAS in 2022</b> to consolidate and streamline India's mental health "
        "helpline operations."
    )
    elems += body("During the COVID-19 pandemic, the government provided:")
    elems += bullets([
        "24/7 nationwide psychosocial assistance through the KIRAN helpline.",
        "Online mental health training for health workers through the iGOT-Diksha platform.",
        "Public awareness campaigns on stress management, anxiety, and grief via media channels.",
        "Official guidelines and advisories for mental well-being during lockdowns.",
        "Special support for frontline health workers dealing with pandemic-related burnout.",
    ])
    elems += spacer(8)

    # ── 19. NSPS ──────────────────────────────────────────────────
    elems += section_header("19.  National Suicide Prevention Strategy (NSPS) - 2022", color=HexColor("#8B0000"))
    elems += body(
        "The <b>National Suicide Prevention Strategy (NSPS)</b> was launched by the Ministry of "
        "Health and Family Welfare (MoHFW) in <b>November 2022</b>. It is India's first dedicated "
        "suicide prevention policy with the goal of reducing suicide mortality by <b>10% by 2030</b>."
    )
    elems += subsection_header("Key Components of NSPS", color=HexColor("#8B0000"))
    elems += bullets([
        "Mental health screenings for students in schools and colleges.",
        "Establishing crisis intervention helplines and psychological support centers.",
        "Community awareness programs to break the stigma around mental illness and suicide.",
        "Stronger implementation of workplace mental health programs.",
        "Restricting access to means of suicide (e.g., pesticide storage regulations).",
        "Responsible media reporting guidelines on suicide to prevent contagion.",
        "Targeted interventions for high-risk populations: students, farmers, women, and young adults.",
    ])
    elems += spacer(8)

    # ── 20. COMPARISON TABLE ──────────────────────────────────────
    elems += section_header("20.  Comparison: NMHP vs Tele-MANAS", color=NAVY)
    comp_data = [
        ["Aspect",            "NMHP",                                   "Tele-MANAS"],
        ["Year of Launch",    "1982",                                   "2022"],
        ["Full Form",         "National Mental Health Programme",       "Tele Mental Health Assistance and Networking Across States"],
        ["Implemented By",    "MoHFW, Government of India",            "MoHFW under National Tele Mental Health Programme"],
        ["Main Objective",    "Accessible mental healthcare; integrate MH into general healthcare", "24x7 tele-mental health counselling via digital platforms"],
        ["Nature",            "Broad national MH policy and service delivery programme", "Digital/telephonic arm of NMHP"],
        ["Mode of Service",   "Hospitals, DMHP, community outreach, training, awareness", "Telephone helpline, tele-counselling, video consultations, e-prescriptions"],
        ["Target Population", "Entire population, especially vulnerable and underserved groups", "Anyone needing immediate MH support, including remote populations"],
        ["Key Components",    "DMHP, training, early detection, treatment, rehabilitation", "24x7 helpline (14416), counselling, specialist referral, follow-up services"],
        ["Infrastructure",    "Physical health facilities from PHCs to medical colleges", "Tele-MH cells and digital platforms across States/UTs"],
        ["Accessibility",     "Requires visiting healthcare facilities in person", "Accessible from anywhere via phone, 24x7"],
        ["Helpline Number",   "No dedicated national helpline",         "14416 or 1800-89-14416"],
    ]
    ct = Table(comp_data, colWidths=[3.5*cm, 6.7*cm, 6.3*cm])
    ct.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), NAVY),
        ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
        ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE",      (0,0), (-1,-1), 8.5),
        ("BACKGROUND",    (1,1), (1,-1), HexColor("#E8F5E9")),
        ("BACKGROUND",    (2,1), (2,-1), HexColor("#E3F2FD")),
        ("ROWBACKGROUNDS",(0,1), (0,-1), [SKY, LAVENDER]),
        ("GRID",          (0,0), (-1,-1), 0.5, HexColor("#AAAAAA")),
        ("VALIGN",        (0,0), (-1,-1), "TOP"),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 6),
        ("FONTNAME",      (0,0), (0,-1), "Helvetica-Bold"),
    ]))
    elems.append(ct)
    elems += spacer(8)

    # ── 21. BENEFITS & ACHIEVEMENTS ───────────────────────────────
    elems += section_header("21.  Benefits and Achievements of NMHP", color=NAVY)

    elems += subsection_header("Achievements of NMHP")
    elems += bullets([
        "Integration of mental health into primary healthcare services across India.",
        "Implementation of DMHP in the majority of districts, improving community access to mental healthcare.",
        "Expansion of mental health infrastructure including psychiatric units in medical colleges and district hospitals.",
        "Development of 25 Centres of Excellence for training mental health professionals.",
        "Increased public awareness and reduction of stigma through IEC activities.",
        "Strengthening of human resources through training of psychiatrists, psychologists, psychiatric nurses, and social workers.",
        "Introduction of Tele-MANAS, providing 24x7 tele-mental health support across the country.",
        "Improved early detection and treatment of common mental disorders at the community level.",
        "Enactment of the Mental Healthcare Act, 2017 and the RPwD Act, 2016 to protect rights of persons with mental illness.",
    ])
    elems += spacer(8)

    for group, color_h, items in [
        ("Benefits for Individuals", HexColor("#1565C0"), [
            "Early diagnosis and treatment of mental disorders.",
            "Better access to counselling and psychiatric services at community level.",
            "Reduced disability and improved quality of life.",
            "Improved social and occupational functioning.",
            "Access to free essential psychotropic medicines through DMHP.",
        ]),
        ("Benefits for Families", HexColor("#2E7D32"), [
            "Reduced caregiving burden through community-based services.",
            "Increased awareness about mental health conditions and how to support a family member.",
            "Better support and rehabilitation services, reducing social isolation.",
        ]),
        ("Benefits for Communities", HexColor("#6A0572"), [
            "Reduced stigma and misconceptions regarding mental illness.",
            "Increased community participation in mental health promotion.",
            "Improved overall mental well-being and community productivity.",
        ]),
        ("Benefits for the Healthcare System", NAVY, [
            "Integration of mental healthcare into primary healthcare, making it sustainable.",
            "Better utilization of healthcare resources across all tiers.",
            "Reduced burden on overburdened tertiary psychiatric hospitals.",
            "Strengthened mental health workforce and improved infrastructure nationwide.",
        ]),
    ]:
        elems += subsection_header(group, color=color_h)
        elems += bullets(items)
    elems += spacer(10)

    # ── 22. REFERENCES ────────────────────────────────────────────
    elems += section_header("22.  References", color=GRAY_MID)
    refs = [
        "Directorate General of Health Services - National Immunization Schedule, Government of India.",
        "National Health Mission - National Immunization Schedule and Cold Chain Guidelines, MoHFW.",
        "WHO/UNICEF - Cold Chain Management Guidelines for Immunization Programmes.",
        "National Cold Chain and Vaccine Management Resource Centre (NCCVMRC), Government of India.",
        "National Health Mission - National Mental Health Programme.",
        "Ministry of Health and Family Welfare, Government of India - Mental Health Policy Documents.",
        "National Institute of Mental Health and Neurosciences (NIMHANS), Bengaluru.",
        "World Health Organization - Mental Health Action Plan 2013-2030.",
        "Ahmed T, Dumka N, Kotwal A. Tele-MANAS: India's First 24x7 Tele Mental Health Helpline. Indian Journal of Mental Health, 2022.",
        "Manjunatha N, Korwar M, Kumar CN, Math SB. National Tele Mental Health Programme (Tele-MANAS) of India: Frameworks and Initial Progress, 2023.",
        "Tele-MANAS Programme Information - Central Institute of Psychiatry (CIP), Ranchi.",
        "Dua K. Attitude, Knowledge and Perception Among General Public About Tele-MANAS Services in Delhi NCR. International Journal of Preventive Medicine and Health, 2024.",
    ]
    for i, r in enumerate(refs, 1):
        elems.append(Paragraph(f"{i}.  {r}", ref_style))
    elems += spacer(8)
    elems.append(HRFlowable(width="100%", thickness=1.5, color=NAVY, spaceAfter=6))
    return elems


# ══════════════════════════════════════════════════════════════════
# BUILD
# ══════════════════════════════════════════════════════════════════
def build():
    out_path = "/tmp/workspace/assignment-pdf/NursingAssignment_Corrected.pdf"
    doc = SimpleDocTemplate(
        out_path, pagesize=A4,
        leftMargin=28*mm, rightMargin=28*mm,
        topMargin=28*mm, bottomMargin=30*mm,
    )
    story = []
    story += cover_page()
    story += toc_page()
    story += part1_immunization()
    story += part2_nmhp()
    doc.build(story, canvasmaker=BorderCanvas)
    print(f"PDF saved to: {out_path}")

if __name__ == "__main__":
    build()
Running Command

cd /tmp/workspace/assignment-pdf && python3 build_pdf_v2.py 2>&1

Running Command

python3 -c " from pypdf import PdfReader r = PdfReader('/tmp/workspace/assignment-pdf/NursingAssignment_Corrected.pdf') print(f'Pages: {len(r.pages)}') import os size = os.path.getsize('/tmp/workspace/assignment-pdf/NursingAssignment_Corrected.pdf') print(f'File size: {size/1024:.1f} KB') "

Built successfully - 16 pages, A4 size, same professional design. Here is your corrected PDF:

NursingAssignment Corrected

PDF Document · PDF


Here is a summary of every mistake that was corrected:
Content errors fixed:
#Original MistakeCorrection
1Cold Chain completely missing from content despite being in the titleAdded 3 full sections: Cold Chain definition & importance, Cold Chain Equipment table (8 equipment types), Maintenance & Monitoring including VVM stages and Shake Test
2NMHP/DMHP paragraphs inserted mid-Immunization section (community participation, self-help promotion, DMHP objectives)Removed entirely - those paragraphs belonged to Part II
3Passive Immunization listed NMHP pilot training text as its contentReplaced with correct passive immunization characteristics, mechanism, and proper examples (TIG, RIG, HBIG, VZIG)
4Active vs Passive had no comparison or detailAdded proper characteristics for each type, a comparison table, and a complete examples list
5Vaccine table missing Route columnAdded Route column to the children's immunization schedule
6Vaccine entries incomplete - BCG, OPV only briefly describedExpanded all 9 vaccines with Purpose, Route, Site, Dose, and Storage Temperature
7India polio-free status and eradication history not mentionedAdded under Importance of Immunization (India certified polio-free 2014)
8NSPS had incomplete description (cut off mid-sentence)Completed with all key components including means restriction and media guidelines
9References lacked immunization/cold chain sourcesAdded WHO/UNICEF cold chain guidelines and NCCVMRC references
10TOC updated to include Cold Chain sections (6-8) with correct numberingAll 22 sections now listed accurately
This is a shared conversation. Sign in to Orris to start your own chat.