How much itll take to create pdf i am waitning from the last 30 mins

I'm sorry for the wait! I don't have any context about a PDF you asked me to create earlier - this appears to be a fresh session for me, so I don't have the details of your previous request.
Could you let me know:
  • What content should go in the PDF?
  • Any specific format - report, notes, resume, etc.?
Once you share the details, I can typically generate a PDF in under 2 minutes.

Opd and ipd gideline pdf multi-speciality

Asking for Preferences
Reading File
Reading File
Running Command

mkdir -p /home/daytona/workspace/opd-ipd-guidelines

Writing File

~/opd-ipd-guidelines/generate_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.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    PageBreak, HRFlowable, KeepTogether
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate
from reportlab.lib.colors import HexColor
import datetime

# ─── Color Palette ────────────────────────────────────────────────────────────
DARK_BLUE   = HexColor("#1B3A6B")
MED_BLUE    = HexColor("#2E6DA4")
LIGHT_BLUE  = HexColor("#D6E8FA")
ACCENT_TEAL = HexColor("#0E9AA7")
TABLE_HDR   = HexColor("#2E6DA4")
TABLE_ALT   = HexColor("#EAF3FB")
WHITE       = colors.white
GREY_TEXT   = HexColor("#555555")
LIGHT_GREY  = HexColor("#F2F2F2")
BORDER_GREY = HexColor("#CCCCCC")
RED_ALERT   = HexColor("#C0392B")
GREEN_OK    = HexColor("#1A7A4A")

# ─── Styles ───────────────────────────────────────────────────────────────────
def build_styles():
    base = getSampleStyleSheet()

    styles = {}

    styles['CoverTitle'] = ParagraphStyle('CoverTitle',
        fontName='Helvetica-Bold', fontSize=28, textColor=WHITE,
        alignment=TA_CENTER, spaceAfter=6, leading=34)

    styles['CoverSubtitle'] = ParagraphStyle('CoverSubtitle',
        fontName='Helvetica', fontSize=14, textColor=LIGHT_BLUE,
        alignment=TA_CENTER, spaceAfter=4, leading=20)

    styles['CoverTagline'] = ParagraphStyle('CoverTagline',
        fontName='Helvetica-Oblique', fontSize=11, textColor=WHITE,
        alignment=TA_CENTER, spaceAfter=4)

    styles['SectionHeading'] = ParagraphStyle('SectionHeading',
        fontName='Helvetica-Bold', fontSize=16, textColor=DARK_BLUE,
        spaceBefore=14, spaceAfter=6, borderPad=4,
        borderColor=ACCENT_TEAL, borderWidth=0, leading=20)

    styles['SubHeading'] = ParagraphStyle('SubHeading',
        fontName='Helvetica-Bold', fontSize=13, textColor=MED_BLUE,
        spaceBefore=10, spaceAfter=4, leading=17)

    styles['SubSubHeading'] = ParagraphStyle('SubSubHeading',
        fontName='Helvetica-Bold', fontSize=11, textColor=ACCENT_TEAL,
        spaceBefore=8, spaceAfter=3, leading=15)

    styles['BodyText'] = ParagraphStyle('BodyText',
        fontName='Helvetica', fontSize=10, textColor=HexColor("#222222"),
        spaceAfter=4, leading=14, alignment=TA_JUSTIFY)

    styles['BulletItem'] = ParagraphStyle('BulletItem',
        fontName='Helvetica', fontSize=10, textColor=HexColor("#333333"),
        spaceAfter=2, leading=14, leftIndent=16, bulletIndent=6)

    styles['SmallBold'] = ParagraphStyle('SmallBold',
        fontName='Helvetica-Bold', fontSize=10, textColor=DARK_BLUE,
        spaceAfter=2, leading=13)

    styles['Alert'] = ParagraphStyle('Alert',
        fontName='Helvetica-Bold', fontSize=10, textColor=RED_ALERT,
        spaceAfter=4, leading=14, leftIndent=8)

    styles['TOCEntry'] = ParagraphStyle('TOCEntry',
        fontName='Helvetica', fontSize=10, textColor=DARK_BLUE,
        spaceAfter=3, leading=14, leftIndent=12)

    styles['TOCSection'] = ParagraphStyle('TOCSection',
        fontName='Helvetica-Bold', fontSize=11, textColor=DARK_BLUE,
        spaceAfter=4, leading=15)

    styles['Footer'] = ParagraphStyle('Footer',
        fontName='Helvetica', fontSize=8, textColor=GREY_TEXT,
        alignment=TA_CENTER)

    return styles


def header_footer(canvas, doc):
    canvas.saveState()
    w, h = A4

    # Header bar (not on cover page)
    if doc.page > 1:
        canvas.setFillColor(DARK_BLUE)
        canvas.rect(0, h - 28, w, 28, fill=1, stroke=0)
        canvas.setFont('Helvetica-Bold', 9)
        canvas.setFillColor(WHITE)
        canvas.drawString(18, h - 18, "MULTI-SPECIALITY HOSPITAL")
        canvas.setFont('Helvetica', 9)
        canvas.drawRightString(w - 18, h - 18, "OPD & IPD Clinical Guidelines 2026")

        # Footer
        canvas.setStrokeColor(BORDER_GREY)
        canvas.line(18, 24, w - 18, 24)
        canvas.setFont('Helvetica', 8)
        canvas.setFillColor(GREY_TEXT)
        canvas.drawString(18, 12, f"Confidential - For Clinical Use Only | Generated: {datetime.date.today().strftime('%d %b %Y')}")
        canvas.drawRightString(w - 18, 12, f"Page {doc.page}")

    canvas.restoreState()


def tbl_style(header_bg=TABLE_HDR, alt=TABLE_ALT):
    return TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), header_bg),
        ('TEXTCOLOR', (0, 0), (-1, 0), WHITE),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, 0), 9),
        ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
        ('ROWBACKGROUNDS', (0, 1), (-1, -1), [WHITE, alt]),
        ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
        ('FONTSIZE', (0, 1), (-1, -1), 9),
        ('GRID', (0, 0), (-1, -1), 0.4, BORDER_GREY),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('LEFTPADDING', (0, 0), (-1, -1), 6),
        ('RIGHTPADDING', (0, 0), (-1, -1), 6),
        ('TOPPADDING', (0, 0), (-1, -1), 4),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 4),
    ])


def section_divider(s, title):
    """Returns a list of flowables for a coloured section title bar."""
    return [
        Spacer(1, 6),
        Table([[Paragraph(title, ParagraphStyle('SH', fontName='Helvetica-Bold',
                fontSize=14, textColor=WHITE, leading=18))]],
              colWidths=[A4[0] - 3.6*cm],
              style=TableStyle([
                  ('BACKGROUND', (0,0), (-1,-1), DARK_BLUE),
                  ('TOPPADDING', (0,0), (-1,-1), 7),
                  ('BOTTOMPADDING', (0,0), (-1,-1), 7),
                  ('LEFTPADDING', (0,0), (-1,-1), 14),
              ])),
        Spacer(1, 6),
    ]


# ═══════════════════════════════════════════════════════════════════════════════
# CONTENT BUILDERS
# ═══════════════════════════════════════════════════════════════════════════════

def cover_page(story, s):
    w, h = A4
    # Large coloured cover block built as a wide table
    cover_data = [[
        Paragraph("MULTI-SPECIALITY HOSPITAL", s['CoverTitle']),
    ]]
    cover_tbl = Table(cover_data, colWidths=[w - 3*cm],
        style=TableStyle([
            ('BACKGROUND', (0,0), (-1,-1), DARK_BLUE),
            ('TOPPADDING', (0,0), (-1,-1), 80),
            ('BOTTOMPADDING', (0,0), (-1,-1), 30),
            ('LEFTPADDING', (0,0), (-1,-1), 20),
            ('RIGHTPADDING', (0,0), (-1,-1), 20),
        ]))
    story.append(cover_tbl)

    # Subtitle block
    sub_data = [[Paragraph("OPD & IPD Clinical Guidelines", s['CoverSubtitle'])]]
    sub_tbl = Table(sub_data, colWidths=[w - 3*cm],
        style=TableStyle([
            ('BACKGROUND', (0,0), (-1,-1), MED_BLUE),
            ('TOPPADDING', (0,0), (-1,-1), 14),
            ('BOTTOMPADDING', (0,0), (-1,-1), 14),
            ('LEFTPADDING', (0,0), (-1,-1), 20),
        ]))
    story.append(sub_tbl)

    story.append(Spacer(1, 20))

    # Info boxes
    info = [
        ["Edition", "2026"],
        ["Scope", "All Major Clinical Specialities"],
        ["Audience", "Doctors, Residents, Clinical Staff"],
        ["Classification", "Confidential - For Internal Clinical Use"],
    ]
    info_tbl = Table(info, colWidths=[5*cm, w - 3*cm - 5*cm],
        style=TableStyle([
            ('FONTNAME', (0,0), (0,-1), 'Helvetica-Bold'),
            ('FONTNAME', (1,0), (1,-1), 'Helvetica'),
            ('FONTSIZE', (0,0), (-1,-1), 11),
            ('TEXTCOLOR', (0,0), (0,-1), DARK_BLUE),
            ('TEXTCOLOR', (1,0), (1,-1), HexColor("#333333")),
            ('ROWBACKGROUNDS', (0,0), (-1,-1), [LIGHT_GREY, WHITE]),
            ('GRID', (0,0), (-1,-1), 0.3, BORDER_GREY),
            ('TOPPADDING', (0,0), (-1,-1), 8),
            ('BOTTOMPADDING', (0,0), (-1,-1), 8),
            ('LEFTPADDING', (0,0), (-1,-1), 14),
        ]))
    story.append(info_tbl)
    story.append(PageBreak())


def toc_page(story, s):
    story += section_divider(s, "TABLE OF CONTENTS")
    toc_items = [
        ("1.", "General OPD & IPD Policies"),
        ("2.", "General Medicine"),
        ("3.", "General Surgery"),
        ("4.", "Orthopaedics"),
        ("5.", "Gynaecology & Obstetrics"),
        ("6.", "Paediatrics & Neonatology"),
        ("7.", "Cardiology"),
        ("8.", "Pulmonology / Respiratory Medicine"),
        ("9.", "Gastroenterology & Hepatology"),
        ("10.", "Neurology & Neurosurgery"),
        ("11.", "Nephrology & Urology"),
        ("12.", "Endocrinology & Diabetology"),
        ("13.", "Oncology"),
        ("14.", "Ophthalmology"),
        ("15.", "ENT (Ear, Nose & Throat)"),
        ("16.", "Dermatology"),
        ("17.", "Psychiatry"),
        ("18.", "Emergency Medicine"),
        ("19.", "Infection Control & Antibiotic Policy"),
        ("20.", "Discharge & Follow-up Policy"),
    ]
    toc_data = [["No.", "Section"]] + toc_items
    toc_tbl = Table(toc_data, colWidths=[1.2*cm, A4[0] - 3.6*cm - 1.2*cm],
        style=TableStyle([
            ('BACKGROUND', (0,0), (-1,0), DARK_BLUE),
            ('TEXTCOLOR', (0,0), (-1,0), WHITE),
            ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
            ('FONTSIZE', (0,0), (-1,0), 10),
            ('ROWBACKGROUNDS', (0,1), (-1,-1), [WHITE, TABLE_ALT]),
            ('FONTNAME', (0,1), (-1,-1), 'Helvetica'),
            ('FONTSIZE', (0,1), (-1,-1), 10),
            ('GRID', (0,0), (-1,-1), 0.3, BORDER_GREY),
            ('TOPPADDING', (0,0), (-1,-1), 6),
            ('BOTTOMPADDING', (0,0), (-1,-1), 6),
            ('LEFTPADDING', (0,0), (-1,-1), 8),
        ]))
    story.append(toc_tbl)
    story.append(PageBreak())


def sec1_general_policies(story, s):
    story += section_divider(s, "1. GENERAL OPD & IPD POLICIES")

    story.append(Paragraph("1.1 OPD (Out-Patient Department) Guidelines", s['SubHeading']))
    opd = [
        "Registration: All patients must register at the front desk before consultation. Valid ID proof is mandatory.",
        "Appointment System: Walk-in and pre-booked appointments are accepted. Priority is given to senior citizens (60+), pregnant women, and patients with disabilities.",
        "Triage: A triage nurse assesses vitals and urgency before the doctor consultation.",
        "Consultation Timing: Doctors should adhere to scheduled OPD hours. Overtime cases should be flagged to the duty manager.",
        "Prescription: All prescriptions must be legible, include generic drug names, dose, route, frequency and duration. Electronic prescriptions are preferred.",
        "Referrals: Intra-hospital referrals require a completed referral form with clinical summary. External referrals must include discharge summary.",
        "Follow-up: OPD follow-up dates must be given at time of consultation. SMS/call reminders are sent 24 hours in advance.",
        "Investigations: All lab and imaging requests must carry patient ID, clinical indication, and doctor's signature/stamp.",
        "Confidentiality: Patient information is strictly confidential. Information may only be shared with written consent or as mandated by law.",
    ]
    for pt in opd:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(Spacer(1, 8))

    story.append(Paragraph("1.2 IPD (In-Patient Department) Guidelines", s['SubHeading']))
    ipd = [
        "Admission: All admissions require a doctor's admission note with diagnosis, plan of care, and expected duration.",
        "Bed Allotment: Beds are allotted based on clinical urgency, speciality, and availability. Isolation protocols apply for infectious cases.",
        "Nursing Handover: Structured handover (SBAR format) at every shift change. Verbal and written records are mandatory.",
        "Medication Administration: Medications are administered only on valid written orders. Double-check is mandatory for high-alert drugs (insulin, heparin, concentrated electrolytes).",
        "Vital Monitoring: Vitals (BP, pulse, SpO2, temperature, RR) recorded every 4-8 hours for stable patients; every 1-2 hours for critical patients.",
        "Diet Orders: Dietary requirements are prescribed by the doctor. Dietitian consult is mandatory for diabetic, renal, and post-operative patients.",
        "Patient Falls Prevention: Bed rails up at all times. Fall risk assessment on admission. Anti-slip footwear provided.",
        "Consent: Informed written consent required before all invasive procedures, surgeries, and blood transfusions.",
        "Discharge Planning: Initiated on Day 1 of admission. Discharge summary must be ready before patient leaves.",
        "VTE Prophylaxis: Assess every IPD patient for DVT/PE risk. Mechanical (TED stockings) and/or pharmacological prophylaxis as indicated.",
        "Infection Prevention: Hand hygiene compliance monitored. Contact, droplet, or airborne precautions activated as clinically indicated.",
    ]
    for pt in ipd:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec2_general_medicine(story, s):
    story += section_divider(s, "2. GENERAL MEDICINE")

    story.append(Paragraph("2.1 OPD Protocol", s['SubHeading']))
    story.append(Paragraph(
        "History and physical examination are the cornerstone of every consult. "
        "Rational investigation ordering is encouraged. Avoid unnecessary repeat investigations.",
        s['BodyText']))

    story.append(Paragraph("Common OPD Conditions - Management Summary", s['SubSubHeading']))
    tbl_data = [
        ["Condition", "Key Assessment", "First-Line Management", "Referral Trigger"],
        ["Hypertension", "BP both arms, fundoscopy, ECG",
         "Lifestyle + Amlodipine 5 mg / Losartan 50 mg", "BP >180/110 refractory; secondary HTN"],
        ["Type 2 Diabetes", "FBS, HbA1c, foot exam, urine microalbumin",
         "Metformin 500mg BD; titrate", "HbA1c >10%, ESRD, foot ulcer"],
        ["Hypothyroidism", "TSH, FT4, lipids",
         "Levothyroxine 1.6 mcg/kg/day", "Myxoedema, pregnancy"],
        ["Anaemia", "CBC, peripheral smear, iron studies, B12",
         "Iron / B12 / folate per aetiology", "Hb <7 g/dL, haemolysis, malignancy"],
        ["Fever (Acute)", "Temp, malaria card, CBC, CRP, urinalysis",
         "Paracetamol 500-1000 mg Q6H; targeted ABx", "Temp >39.5 C >5 days; severe sepsis"],
        ["URTI", "Throat, ears, LN, SpO2",
         "Symptomatic; avoid ABx unless bacterial", "SpO2 <94%, stridor, peritonsillar abscess"],
        ["Asthma (Stable)", "PEFR, spirometry, triggers",
         "SABA PRN + ICS (low-medium dose)", "Severe/brittle asthma"],
    ]
    t = Table(tbl_data, colWidths=[3.2*cm, 4*cm, 4.5*cm, 3.8*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 8))

    story.append(Paragraph("2.2 IPD Protocol", s['SubHeading']))
    ipd_items = [
        "Admit for: Uncontrolled sepsis, hypertensive emergency (>180/120 with end-organ damage), DKA, severe anaemia (Hb <7), COPD exacerbation.",
        "Daily review: Vitals, input/output chart, medication reconciliation, labs review, wound inspection if applicable.",
        "Blood cultures: 2 sets from different sites before starting antibiotics.",
        "Fluid management: Assess hydration status twice daily. Avoid over-hydration in cardiac/renal patients.",
        "Electrolytes: Monitor Na, K, Mg, phosphate daily in critically ill. Replace deficits cautiously.",
        "DVT prophylaxis: All bedridden medical patients - LMWH (Enoxaparin 40 mg SC OD) unless contraindicated.",
    ]
    for pt in ipd_items:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec3_surgery(story, s):
    story += section_divider(s, "3. GENERAL SURGERY")

    story.append(Paragraph("3.1 Pre-Operative OPD Assessment", s['SubHeading']))
    pre_op = [
        "Complete history including medications, allergies, previous anaesthesia records.",
        "Fitness assessment: CBC, LFT, RFT, coagulation profile, ECG (all patients >40 years), CXR, Echo if cardiac history.",
        "Consent: Detailed informed consent with risk-benefit discussion and documentation.",
        "NBM (Nil By Mouth): Solids - 6 hours; clear fluids - 2 hours before procedure. Communicate clearly to patient.",
        "Bowel prep: As required per surgical type (colon resections, etc.).",
        "Anti-hypertensives/Diabetic medications: Continue anti-HTN; hold Metformin 48 hours before; manage insulin per pre-op protocol.",
        "Anticoagulants: Stop Warfarin 5 days pre-op; NOAC 24-48 hours; consult haematology for complex cases.",
    ]
    for pt in pre_op:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(Spacer(1, 6))

    story.append(Paragraph("3.2 Post-Operative IPD Care", s['SubHeading']))
    post_op = [
        "Vitals monitoring Q1H for first 4 hours post-op, then Q4H if stable.",
        "Pain management: WHO analgesic ladder. Paracetamol 1g Q6H scheduled + Tramadol/Morphine PRN.",
        "Wound care: Inspect dressing at 24 hours. Daily dressing change if soiled. Document wound appearance.",
        "Drain management: Record drain output; remove drain when output <30 mL/24 hours.",
        "Early mobilisation: Day 1 post-op for most elective surgeries (physiotherapist referral).",
        "DVT prophylaxis: LMWH + TED stockings from Day 0 post-op.",
        "Diet: Clear fluids at 6 hours post bowel surgery; earlier for non-GI surgeries.",
        "Foley catheter: Remove at 24-48 hours post-op unless urological indication.",
        "Antibiotics: Prophylactic Cefazolin 1-2g at induction; extend only if contamination or infection found.",
    ]
    for pt in post_op:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))

    story.append(Paragraph("3.3 Common Surgical Conditions", s['SubSubHeading']))
    tbl_data = [
        ["Condition", "Emergency Signs", "Surgical Approach", "IPD Duration"],
        ["Appendicitis", "Rebound tenderness, fever, raised WBC",
         "Laparoscopic appendicectomy", "2-3 days"],
        ["Hernia (Inguinal)", "Non-reducible, pain, vomiting",
         "Mesh repair (open/laparoscopic)", "1-2 days"],
        ["Cholecystitis", "RUQ pain, Murphy's sign, fever",
         "Laparoscopic cholecystectomy", "2-4 days"],
        ["Intestinal Obstruction", "Distension, absolute constipation, vomiting",
         "Conservative / Laparotomy", "5-10 days"],
        ["Perforated Ulcer", "Sudden epigastric pain, peritonism",
         "Emergency laparotomy", "7-14 days"],
    ]
    t = Table(tbl_data, colWidths=[3.8*cm, 4.2*cm, 4.2*cm, 3.3*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(PageBreak())


def sec4_ortho(story, s):
    story += section_divider(s, "4. ORTHOPAEDICS")

    story.append(Paragraph("4.1 OPD Protocols", s['SubHeading']))
    story.append(Paragraph("4.1.1 Fracture Management", s['SubSubHeading']))
    tbl_data = [
        ["Fracture Type", "Initial Intervention", "Definitive Management", "Follow-up"],
        ["Colles' Fracture", "Closed reduction + POP cast",
         "POP 6 weeks; surgery if displaced", "2 wks, 6 wks, 3 months"],
        ["Neck of Femur", "Analgesia, skin traction",
         "THR or hemi-arthroplasty", "6 wks, 3 mths, 6 mths"],
        ["Shaft of Femur", "Thomas splint, IV analgesia",
         "IMN (Intramedullary Nail)", "6 wks, 3 mths, 6 mths"],
        ["Vertebral (Osteoporotic)", "Brace, analgesia",
         "Vertebroplasty if refractory", "1 month then 3-monthly"],
        ["Paediatric Supracondylar", "Analgesia, neurovascular check",
         "CRPP if displaced", "1 wk, 4 wks, 8 wks"],
    ]
    t = Table(tbl_data, colWidths=[3.8*cm, 4*cm, 4*cm, 3.7*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 6))

    story.append(Paragraph("4.2 IPD Protocols", s['SubHeading']))
    ipd = [
        "Pain: IV Paracetamol + NSAID (if no contraindication) + Opioid PRN.",
        "Neurovascular checks: Every 2 hours post reduction/surgery - 5 Ps (Pain, Pallor, Pulse, Paraesthesia, Paralysis).",
        "DVT prophylaxis: Mandatory for all hip/knee arthroplasties - LMWH for 14-35 days.",
        "Physiotherapy: Commence Day 1 post-op for joint replacements. Weight-bearing status defined by surgeon.",
        "Antibiotic prophylaxis: Cefazolin 2g at induction; repeat if surgery >3 hours.",
        "Blood transfusion: Target Hb >8 g/dL post-operatively; >10 in patients with cardiac disease.",
    ]
    for pt in ipd:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec5_gynae(story, s):
    story += section_divider(s, "5. GYNAECOLOGY & OBSTETRICS")

    story.append(Paragraph("5.1 Antenatal OPD Schedule", s['SubHeading']))
    anc = [
        ["Visit", "Gestation (Weeks)", "Key Actions"],
        ["1st ANC", "8-12 weeks", "Registration, booking bloods, USS dating, folic acid, tetanus toxoid"],
        ["2nd ANC", "16 weeks", "Anomaly screening, quadruple test if indicated, BP, urine"],
        ["3rd ANC", "20 weeks", "Anomaly scan, growth assessment, GDM screening advice"],
        ["4th ANC", "24-28 weeks", "OGTT (GDM screen), FBC, anti-D if Rh negative"],
        ["5th ANC", "32 weeks", "Growth scan, fetal movements, blood pressure"],
        ["6th ANC", "36 weeks", "Presentation, Group B Strep swab, birth plan"],
        ["7th ANC", "38-40 weeks", "CTG if indicated, induction discussion"],
    ]
    t = Table(anc, colWidths=[2.5*cm, 3.5*cm, A4[0]-3.6*cm-6*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 8))

    story.append(Paragraph("5.2 Gynaecology OPD - Common Conditions", s['SubHeading']))
    tbl_data = [
        ["Condition", "Investigation", "Management"],
        ["PCOS", "USS pelvis, LH/FSH, testosterone, fasting glucose",
         "Lifestyle modification, OCP, Metformin, fertility referral"],
        ["Fibroid Uterus", "USS, FBC (anaemia)",
         "Medical: TXA/GnRH agonist; Surgical: myomectomy/hysterectomy"],
        ["Abnormal Uterine Bleeding", "TFTs, coagulation, endometrial biopsy if >40 yrs",
         "Hormonal (LNG-IUS, OCP); Surgical if indicated"],
        ["Ectopic Pregnancy", "serum b-HCG, transvaginal USS",
         "Medical: Methotrexate if stable; Surgical if rupture/unstable"],
        ["Ovarian Cyst", "USS, CA-125 if post-menopausal",
         "Observation if <5cm simple; Surgery if complex/large"],
    ]
    t = Table(tbl_data, colWidths=[3.5*cm, 4.5*cm, A4[0]-3.6*cm-8*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 6))

    story.append(Paragraph("5.3 Obstetric IPD - Labour & Delivery", s['SubHeading']))
    labour = [
        "Admission: CTG on arrival, cervical assessment, IV access, blood group and Rh, GBS status.",
        "Active labour management: Partogram documentation every 30 minutes. Amniotomy if slow progress >2 hours.",
        "Analgesia: Epidural by anaesthesia on request. IV Pethidine 50-100mg IM as alternative.",
        "Fetal monitoring: Continuous CTG in high-risk; intermittent auscultation in low-risk (every 15 min 1st stage, every 5 min 2nd stage).",
        "Third Stage: Active management - Oxytocin 10 IU IM after delivery. Controlled cord traction.",
        "PPH Protocol: Oxytocin 20 IU in 500 mL normal saline IV + Ergometrine 0.5 mg IM + Misoprostol 800 mcg SL if needed.",
        "C-Section: Cefazolin 2g prophylaxis at induction. Foley catheter. Remove in 24 hours.",
        "Post-natal: Ambulation within 6 hours. Breastfeeding initiation within 1 hour of delivery.",
    ]
    for pt in labour:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec6_paeds(story, s):
    story += section_divider(s, "6. PAEDIATRICS & NEONATOLOGY")

    story.append(Paragraph("6.1 Paediatric OPD - Growth & Immunisation", s['SubHeading']))
    vax = [
        ["Age", "Vaccine"],
        ["Birth", "BCG, OPV-0, Hepatitis B-1"],
        ["6 weeks", "DTwP/DTaP-1, OPV-1, IPV-1, Hib-1, Hep B-2, Rotavirus-1, PCV-1"],
        ["10 weeks", "DTwP/DTaP-2, OPV-2, IPV-2, Hib-2, Rotavirus-2, PCV-2"],
        ["14 weeks", "DTwP/DTaP-3, OPV-3, IPV-3, Hib-3, Hep B-3, Rotavirus-3, PCV-3"],
        ["6 months", "Influenza (1st dose)"],
        ["9 months", "MMR-1, MenC"],
        ["12 months", "Hep A-1, Varicella-1, MMR-2"],
        ["15-18 months", "DTwP booster, OPV booster, Hib booster, PCV booster"],
        ["2 years", "Typhoid conjugate, Hep A-2"],
        ["4-6 years", "DTaP/Tdap booster, OPV/IPV booster, MMR-3"],
    ]
    t = Table(vax, colWidths=[2.5*cm, A4[0]-3.6*cm-2.5*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 8))

    story.append(Paragraph("6.2 Common Paediatric OPD Conditions", s['SubHeading']))
    tbl_data = [
        ["Condition", "Criteria", "Treatment"],
        ["Febrile Seizure", "Age 6 mo - 5 yr, temp >38C, brief generalised",
         "Midazolam buccal if >5 min; EEG/neurology if recurrent"],
        ["Pneumonia", "Tachypnoea, retractions, SpO2 <94%",
         "Amoxicillin PO (mild); IV penicillin (moderate-severe)"],
        ["Acute Diarrhoea", "Stool frequency, hydration status (DHAKA scale)",
         "ORS (Plan A-C); Zinc 20 mg/day x 14 days; no anti-motility drugs"],
        ["Asthma (Child)", "Wheeze, PEFR, symptoms frequency",
         "SABA; ICS if persistent; step-up if poor control"],
        ["Neonatal Jaundice", "TSB levels, gestation, age in hours",
         "Phototherapy if above treatment line (Bhutani nomogram); exchange if critical"],
    ]
    t = Table(tbl_data, colWidths=[3.5*cm, 5*cm, A4[0]-3.6*cm-8.5*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 6))

    story.append(Paragraph("6.3 Paediatric IPD Protocols", s['SubHeading']))
    ipd = [
        "Weight-based dosing: All drugs prescribed per kg body weight. Maximum adult doses apply.",
        "IV fluid: Hartmann's or 0.9% NaCl for maintenance; 10 mL/kg bolus for shock (reassess after each bolus).",
        "Hypoglycaemia: Blood glucose <2.6 mmol/L - 2 mL/kg 10% dextrose IV bolus.",
        "Sepsis: Blood cultures then IV antibiotics within 1 hour (Ceftriaxone 100 mg/kg/day).",
        "Meningitis: Dexamethasone 0.15 mg/kg QID x 4 days + Ceftriaxone. LP before ABx if possible.",
        "Parents: Mandatory involvement in all decisions. Daily doctor-parent communication documented.",
    ]
    for pt in ipd:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec7_cardiology(story, s):
    story += section_divider(s, "7. CARDIOLOGY")

    story.append(Paragraph("7.1 OPD Assessment", s['SubHeading']))
    story.append(Paragraph(
        "Every new cardiac patient requires: history (symptom onset, NYHA class), physical exam, 12-lead ECG, "
        "Echo 2D, FBC, RFT, lipid profile, fasting glucose/HbA1c, CXR. "
        "Risk stratification using TIMI/GRACE/HEART scores for ACS.", s['BodyText']))

    story.append(Paragraph("7.2 Chest Pain Protocol (OPD/Emergency)", s['SubSubHeading']))
    tbl_data = [
        ["Step", "Action"],
        ["1", "12-lead ECG within 10 minutes of arrival"],
        ["2", "High-sensitivity Troponin I/T at 0h and 1h (or 0h and 3h)"],
        ["3", "Aspirin 300mg stat (if not contraindicated) + Clopidogrel/Ticagrelor"],
        ["4", "IV access, continuous cardiac monitoring, SpO2, BP both arms"],
        ["5", "STEMI: Activate Cath Lab - PCI target Door-to-Balloon <90 min; Thrombolysis if PCI unavailable"],
        ["6", "NSTEMI/UA: Risk stratify; anticoagulate (LMWH/Fondaparinux); invasive strategy within 24-72h"],
        ["7", "Unstable: ICU/CCU admission; stable: monitored ward"],
    ]
    t = Table(tbl_data, colWidths=[1*cm, A4[0]-3.6*cm-1*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 8))

    story.append(Paragraph("7.3 IPD Cardiac Monitoring", s['SubHeading']))
    ipd = [
        "Continuous ECG monitoring in CCU for all ACS and arrhythmia patients.",
        "Daily weights in heart failure; strict fluid balance (target -500 mL to -1 L/day in decompensated HF).",
        "Heart Failure: IV Furosemide 40-80 mg OD; Spironolactone/Eplerenone; ACE-I/ARB; Carvedilol once stable.",
        "Atrial Fibrillation: Rate control (Bisoprolol/Diltiazem); anticoagulation (NOAC preferred); rhythm control if indicated.",
        "Post-MI medications: Aspirin, Statin (high intensity), Beta-blocker, ACE-I/ARB, DAPT (12 months if stented).",
        "Pacing: Temporary pacing for complete heart block, 3rd degree AV block, or symptomatic bradycardia <40 bpm.",
    ]
    for pt in ipd:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec8_pulm(story, s):
    story += section_divider(s, "8. PULMONOLOGY / RESPIRATORY MEDICINE")

    story.append(Paragraph("8.1 OPD Protocols", s['SubHeading']))
    tbl_data = [
        ["Condition", "Key Investigations", "Management"],
        ["COPD (Stable)", "Spirometry (FEV1/FVC <0.7), CXR, ABG",
         "LABA+LAMA; ICS if frequent exacerbations; pulm rehab; flu vaccine"],
        ["Asthma", "Spirometry, PEFR diary, FeNO",
         "Step-up ICS/LABA/LTRA per GINA; check inhaler technique"],
        ["Community-Acquired Pneumonia", "CXR, sputum C&S, FBC, CRP, procalcitonin",
         "Amoxicillin + Azithromycin (outpatient moderate); hospitalise if CURB-65 >=2"],
        ["Pleural Effusion", "USS chest, diagnostic thoracocentesis",
         "Treat underlying cause; drain if symptomatic"],
        ["TB (Pulmonary)", "Sputum AFB x3, Gene Xpert, CXR, Mantoux",
         "DOTS: 2HRZE / 4HR; notify public health"],
        ["Obstructive Sleep Apnoea", "Epworth score, overnight oximetry, polysomnography",
         "CPAP; weight loss; positional therapy"],
    ]
    t = Table(tbl_data, colWidths=[3.5*cm, 4.5*cm, A4[0]-3.6*cm-8*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 6))

    story.append(Paragraph("8.2 IPD Respiratory Emergencies", s['SubHeading']))
    ipd = [
        "Acute Severe Asthma: Salbutamol nebs Q20 min, Ipratropium nebs, IV Hydrocortisone 200mg, IV MgSO4 2g, NIV/intubation if life-threatening.",
        "COPD Exacerbation: SABDs, controlled O2 (target SpO2 88-92%), oral Prednisolone 40mg x 5 days, ABx (Amoxicillin/Doxycycline), NIV if pH <7.35.",
        "Pneumothorax: Primary spontaneous <2cm - observation; >2cm - needle aspiration or chest drain.",
        "Tension Pneumothorax: Immediate needle decompression (2nd ICS mid-clavicular line) without waiting for X-ray.",
        "Pulmonary Embolism: CTPA for diagnosis; anticoagulation (LMWH/NOAC); thrombolysis if haemodynamically unstable.",
    ]
    for pt in ipd:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec9_gastro(story, s):
    story += section_divider(s, "9. GASTROENTEROLOGY & HEPATOLOGY")

    story.append(Paragraph("9.1 OPD Guidelines", s['SubHeading']))
    tbl_data = [
        ["Condition", "Investigations", "Management"],
        ["GERD", "Clinical; OGD if alarm symptoms",
         "PPI (Omeprazole 20-40mg OD); lifestyle; H2RA add-on"],
        ["Peptic Ulcer", "OGD + CLO test, H. pylori serology",
         "H. pylori triple therapy (PPI + Amoxicillin + Clarithromycin x 14 days)"],
        ["IBS", "Symptom-based (Rome IV); exclude alarm",
         "Dietary advice (low FODMAP); antispasmodics; SSRIs for pain"],
        ["IBD (Crohn's/UC)", "Colonoscopy + biopsy, CRP, faecal calprotectin",
         "5-ASA (UC); steroids (induction); immunomodulators/biologics"],
        ["Chronic Liver Disease", "LFT, prothrombin time, platelets, USS abdomen",
         "Treat aetiology; alcohol cessation; Propranolol for portal HTN; surveillance OGD"],
        ["Acute Pancreatitis", "Lipase/amylase, USS, CT abdomen, severity score",
         "IV fluids, analgesia, NBM; ERCP if gallstone pancreatitis"],
    ]
    t = Table(tbl_data, colWidths=[3.5*cm, 4.2*cm, A4[0]-3.6*cm-7.7*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 6))

    story.append(Paragraph("9.2 GI Bleed IPD Protocol", s['SubHeading']))
    gi_bleed = [
        "Upper GI Bleed: ABCDE. IV access x2. FBC, coagulation, group and save. PPI IV (80mg bolus then 8mg/h). OGD within 24h (12h if high risk).",
        "Lower GI Bleed: Colonoscopy after stabilisation. CT angiography if massive ongoing bleed.",
        "Variceal Bleed: Terlipressin/Somatostatin + Ceftriaxone IV prophylaxis + OGD banding. Sengstaken tube if uncontrolled.",
        "Resuscitation: Target Hb 70-80 g/L (80-90 in cardiac); FFP and platelets if coagulopathy.",
        "Tranexamic Acid: 1g IV over 10 min in major haemorrhage.",
    ]
    for pt in gi_bleed:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec10_neuro(story, s):
    story += section_divider(s, "10. NEUROLOGY & NEUROSURGERY")

    story.append(Paragraph("10.1 Stroke Protocol (Time Critical)", s['SubHeading']))
    stroke = [
        ["Time Point", "Action"],
        ["0-10 min", "Call stroke team. ABCDE. Baseline vitals. IV access. Blood glucose. ECG."],
        ["0-25 min", "CT brain (no contrast). FBC, coagulation, group. NIHSS score."],
        ["0-45 min", "Review CT. Exclude haemorrhage. Decision on thrombolysis."],
        ["0-60 min", "IV Alteplase 0.9 mg/kg (max 90 mg) if ischaemic stroke <4.5 hours and eligible."],
        ["0-6 hours", "CTA/MRA. Mechanical thrombectomy for large vessel occlusion."],
        ["Ongoing", "Admission to stroke unit. Aspirin 300mg after 24h CT. Statin. Anticoagulation for AF-related stroke."],
    ]
    t = Table(stroke, colWidths=[2.5*cm, A4[0]-3.6*cm-2.5*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 8))

    story.append(Paragraph("10.2 OPD Neurology - Common Conditions", s['SubHeading']))
    tbl_data = [
        ["Condition", "Key Features", "Management"],
        ["Epilepsy", "Seizure semiology, EEG, MRI brain",
         "Valproate/Levetiracetam/Carbamazepine; driving restrictions; contraception advice"],
        ["Migraine", "ICHD-3 criteria, >4 attacks/month for prophylaxis",
         "Acute: Triptans + NSAID; Prophylaxis: Topiramate/Propranolol/Amitriptyline"],
        ["Parkinson's Disease", "UPDRS, DaTscan if uncertain",
         "Levodopa/Carbidopa; Dopamine agonists; physiotherapy"],
        ["Multiple Sclerosis", "MRI brain+spine, VEP, CSF oligoclonal bands",
         "Acute relapse: IV Methylprednisolone; DMTs (Interferon, Natalizumab, etc.)"],
        ["Peripheral Neuropathy", "NCS/EMG, B12, glucose, TSH, protein electrophoresis",
         "Treat cause; Gabapentin/Pregabalin/Duloxetine for pain"],
    ]
    t = Table(tbl_data, colWidths=[3.5*cm, 4*cm, A4[0]-3.6*cm-7.5*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 6))

    story.append(Paragraph("10.3 Neurosurgery IPD Protocols", s['SubHeading']))
    ns = [
        "Raised ICP: Head of bed 30 degrees; avoid hypotension; Mannitol 0.25-1 g/kg IV; target Na 145-155 mEq/L; intubate if GCS <=8.",
        "Post-craniotomy: Hourly neuro obs (GCS, pupils, limb power). CT head if deterioration.",
        "Subarachnoid Haemorrhage: Nimodipine 60mg Q4H (vasospasm prevention); maintain euvolaemia; monitor for hydrocephalus.",
        "Spinal injury: ABCDE; log-roll; MRI spine; Neurosurgical opinion within 4 hours for cord compression.",
    ]
    for pt in ns:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec11_nephro(story, s):
    story += section_divider(s, "11. NEPHROLOGY & UROLOGY")

    story.append(Paragraph("11.1 CKD OPD Protocol", s['SubHeading']))
    ckd_stages = [
        ["CKD Stage", "eGFR (mL/min/1.73m2)", "Actions"],
        ["Stage 1 (G1)", ">= 90", "Risk factor control; ACE-I/ARB; monitor annually"],
        ["Stage 2 (G2)", "60-89", "Repeat eGFR in 3 months; BP target <130/80; avoid NSAIDs"],
        ["Stage 3a (G3a)", "45-59", "Nephrology referral; anaemia screen; bone mineral density"],
        ["Stage 3b (G3b)", "30-44", "Anaemia Rx; phosphate binders; Vitamin D; dietary advice"],
        ["Stage 4 (G4)", "15-29", "AV fistula planning; dialysis modality education; transplant evaluation"],
        ["Stage 5 (G5)", "< 15", "Commence RRT: haemodialysis, peritoneal dialysis, or transplant"],
    ]
    t = Table(ckd_stages, colWidths=[3*cm, 3.5*cm, A4[0]-3.6*cm-6.5*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 6))

    story.append(Paragraph("11.2 Acute Kidney Injury IPD Protocol", s['SubHeading']))
    aki = [
        "KDIGO staging: Stage 1 - Cr 1.5-1.9x baseline or +0.3 mg/dL; Stage 2 - 2-2.9x; Stage 3 - >3x or Cr >4 mg/dL or oliguria <0.3 mL/kg/h x 24h.",
        "Identify and treat cause: Pre-renal (fluids), renal (steroids for GN), post-renal (relieve obstruction).",
        "Stop nephrotoxins: NSAIDs, ACE-I/ARB, Metformin, aminoglycosides, contrast agents.",
        "Fluid management: Challenge 250-500 mL crystalloid if pre-renal; avoid over-hydration.",
        "Electrolytes: Treat hyperkalaemia urgently (ECG changes = K >6.5) - Calcium gluconate + insulin-dextrose + Salbutamol nebuliser.",
        "Dialysis indications: Refractory hyperkalaemia, metabolic acidosis pH <7.15, fluid overload, uraemic symptoms.",
    ]
    for pt in aki:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec12_endo(story, s):
    story += section_divider(s, "12. ENDOCRINOLOGY & DIABETOLOGY")

    story.append(Paragraph("12.1 Diabetes OPD Protocol", s['SubHeading']))
    dm = [
        ["Parameter", "Target"],
        ["HbA1c", "< 7% (individualise: 7.5-8% in elderly/comorbid)"],
        ["Fasting Blood Glucose", "80-130 mg/dL (4.4-7.2 mmol/L)"],
        ["Post-prandial Glucose (2h)", "< 180 mg/dL (< 10 mmol/L)"],
        ["Blood Pressure", "< 130/80 mmHg"],
        ["LDL Cholesterol", "< 70 mg/dL (high CV risk)"],
        ["BMI", "18.5-24.9 kg/m2 (weight loss if overweight)"],
        ["Urine Microalbumin", "< 30 mg/g creatinine"],
    ]
    t = Table(dm, colWidths=[5*cm, A4[0]-3.6*cm-5*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 6))

    story.append(Paragraph("12.2 DKA IPD Protocol", s['SubHeading']))
    dka = [
        "Diagnosis: Blood glucose >11 mmol/L + ketonaemia >3 mmol/L (or urine ketones ++) + pH <7.3 / HCO3 <15.",
        "IV Fluids: 0.9% NaCl 1 litre in first hour; then 500 mL/hour x 4h; then 250 mL/h based on response.",
        "Insulin: Fixed rate IV insulin infusion (FRIII) 0.1 units/kg/hour. Do NOT stop background insulin.",
        "Potassium: Replace aggressively - add KCl to IV fluids once K <5.5 mmol/L.",
        "Glucose: When glucose <14 mmol/L, add 10% dextrose 125 mL/h alongside saline.",
        "Resolution criteria: pH >7.3, HCO3 >18, ketones <0.6 mmol/L. Then transition to SC insulin.",
        "Monitor: Hourly glucose + 2-hourly VBG, electrolytes, ketones for first 6 hours.",
    ]
    for pt in dka:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec13_oncology(story, s):
    story += section_divider(s, "13. ONCOLOGY")

    story.append(Paragraph("13.1 OPD Oncology Triage", s['SubHeading']))
    alarm = [
        "Unexplained weight loss >10% in 6 months",
        "Haemoptysis, haematuria, rectal bleeding in patients >45 years",
        "Progressive dysphagia",
        "New lump or mass on examination",
        "Unexplained anaemia (Hb <10 without cause)",
        "Bone pain at night or at rest",
    ]
    for pt in alarm:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(Paragraph("All alarm features require urgent referral to oncology within 2 weeks.", s['Alert']))
    story.append(Spacer(1, 6))

    story.append(Paragraph("13.2 Chemotherapy IPD Protocol", s['SubHeading']))
    chemo = [
        "Pre-chemo checklist: Signed consent; FBC (ANC >1.5, Plt >100); RFT, LFT; pregnancy test (females); antiemetic prescribed.",
        "Antiemetics: Ondansetron 8mg IV + Dexamethasone 8mg IV pre-chemo; add Aprepitant for highly emetogenic regimens.",
        "Vesicant precautions: Confirm IV line patency; use central line for vesicant drugs; observe site every 15 minutes.",
        "Febrile Neutropenia (ANC <0.5 + Temp >38.3): IV Piperacillin-Tazobactam 4.5g Q8H stat; blood cultures first.",
        "G-CSF: Filgrastim 5 mcg/kg SC daily from day 1 post-chemo in high-risk protocols.",
        "Tumour Lysis Syndrome: Hydration 3L/day; Allopurinol/Rasburicase; monitor K, phosphate, Ca, uric acid every 6 hours.",
    ]
    for pt in chemo:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec14_ophth(story, s):
    story += section_divider(s, "14. OPHTHALMOLOGY")

    story.append(Paragraph("14.1 OPD Eye Examination Protocol", s['SubHeading']))
    eye = [
        "Visual acuity (Snellen chart) - both eyes separately with and without correction.",
        "Pupillary reflex (direct and consensual); RAPD (relative afferent pupillary defect) check.",
        "Anterior segment: Slit lamp examination for cornea, lens, iris.",
        "IOP: Tonometry (normal 10-21 mmHg); >21 mmHg - glaucoma workup.",
        "Fundus: Dilated fundoscopy for retina, disc, vessels, macula.",
        "Visual fields: Confrontation; formal perimetry for glaucoma and neurological cases.",
    ]
    for pt in eye:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(Spacer(1, 6))

    story.append(Paragraph("14.2 Ophthalmic Emergencies - IPD/Emergency", s['SubHeading']))
    tbl_data = [
        ["Emergency", "Features", "Urgent Management"],
        ["Acute Angle-Closure Glaucoma", "Red eye, severe pain, halos, raised IOP",
         "IV Acetazolamide + Topical Pilocarpine + Timolol; urgent laser PI"],
        ["Central Retinal Artery Occlusion", "Sudden painless vision loss, cherry-red spot",
         "Ocular massage, IV Acetazolamide; urgent neuro/stroke workup"],
        ["Open Globe Injury", "Hypotony, uveal prolapse, hyphema",
         "NBM, eye shield, urgent surgical repair; IV ABx"],
        ["Chemical Burn", "Pain, redness, photophobia",
         "IMMEDIATE copious irrigation; pH testing; urgent Ophthalmology"],
        ["Retinal Detachment", "Floaters, flashes, curtain defect",
         "Urgent surgical repair (vitrectomy/scleral buckle)"],
    ]
    t = Table(tbl_data, colWidths=[3.5*cm, 4*cm, A4[0]-3.6*cm-7.5*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(PageBreak())


def sec15_ent(story, s):
    story += section_divider(s, "15. ENT (EAR, NOSE & THROAT)")

    story.append(Paragraph("15.1 Common OPD Conditions", s['SubHeading']))
    tbl_data = [
        ["Condition", "Assessment", "Management"],
        ["Otitis Media (Acute)", "Otoscopy (red bulging TM), fever",
         "Amoxicillin 500mg TDS x 5 days; analgesia; watchful waiting if mild in adults"],
        ["Tonsillitis", "Centor criteria, throat swab",
         "Penicillin V / Amoxicillin x 10 days if bacterial; consider tonsillectomy if recurrent (>=7/year)"],
        ["Allergic Rhinitis", "Skin prick test, nasal endoscopy",
         "Intranasal corticosteroids; antihistamines; allergen avoidance; immunotherapy"],
        ["Epistaxis", "Site (anterior vs posterior), BP, FBC",
         "Anterior - cautery or anterior pack; Posterior - Foley catheter pack; tranexamic acid"],
        ["Vertigo (BPPV)", "Dix-Hallpike test",
         "Epley manoeuvre; Betahistine 24mg BD; no driving until resolved"],
        ["Hearing Loss", "Pure tone audiometry, tympanometry",
         "Sensorineural: hearing aid/cochlear implant; Conductive: treat cause"],
    ]
    t = Table(tbl_data, colWidths=[3.2*cm, 3.8*cm, A4[0]-3.6*cm-7*cm])
    t.setStyle(tbl_style())
    story.append(t)

    story.append(Paragraph("15.2 ENT Surgical IPD Protocols", s['SubHeading']))
    ent_surg = [
        "Tonsillectomy: NBM 6h, Cefazolin at induction, steroids (Dexamethasone 8mg IV), ice collar post-op, soft diet for 2 weeks.",
        "Septoplasty/FESS: Local decongestant spray pre-op, nasal packs removed at 24-48h, saline douching started day 1.",
        "Post-operative haemorrhage: Primary (within 24h) - return to theatre. Secondary (5-10 days) - IV antibiotics, consider theatre.",
    ]
    for pt in ent_surg:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec16_derm(story, s):
    story += section_divider(s, "16. DERMATOLOGY")

    story.append(Paragraph("16.1 Common OPD Dermatology Conditions", s['SubHeading']))
    tbl_data = [
        ["Condition", "Diagnosis", "Treatment"],
        ["Psoriasis", "Clinical (plaques, scales, nails); biopsy if uncertain",
         "Topical: Betamethasone + Calcipotriol; Moderate-severe: Methotrexate / Biologics"],
        ["Atopic Dermatitis", "Clinical; IgE, patch test",
         "Emollients; Topical steroids (mild-moderate); Dupilumab/Tacrolimus (severe/refractory)"],
        ["Urticaria (Chronic)", "H1-antihistamine trial, thyroid screen, ANA",
         "Cetirizine 10mg OD; up-dose 4x; Omalizumab if refractory"],
        ["Tinea (Fungal)", "KOH scraping; dermoscopy",
         "Topical Clotrimazole/Terbinafine; oral Terbinafine for nail/extensive"],
        ["Acne Vulgaris", "Grade (comedonal / inflammatory / nodulocystic)",
         "Mild: Topical BPO/adapalene; Moderate: + Oral doxycycline; Severe: Isotretinoin"],
        ["Scabies", "Burrows in web spaces; itch worse at night",
         "Permethrin 5% cream whole body; treat all contacts; wash bedding/clothes"],
    ]
    t = Table(tbl_data, colWidths=[3.2*cm, 4*cm, A4[0]-3.6*cm-7.2*cm])
    t.setStyle(tbl_style())
    story.append(t)

    story.append(Paragraph("16.2 Dermatological Emergencies IPD", s['SubHeading']))
    derm_em = [
        "Stevens-Johnson Syndrome / TEN: Stop offending drug. ICU care. IV fluids. Wound care. Ophthalmology consult. IV Ig / Cyclosporine debated.",
        "Anaphylaxis: Adrenaline 0.5mg IM (1:1000) thigh; IV fluids; Chlorphenamine + Hydrocortisone; auto-injector on discharge.",
        "Meningococcal Septicaemia: IV Benzylpenicillin 2.4g / Ceftriaxone 2g stat; ICU; notify public health.",
    ]
    for pt in derm_em:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec17_psych(story, s):
    story += section_divider(s, "17. PSYCHIATRY")

    story.append(Paragraph("17.1 OPD Mental Health Assessment", s['SubHeading']))
    psych = [
        "All new psychiatric patients: MSE (appearance, behaviour, speech, mood, affect, thought, perception, cognition, insight).",
        "Risk assessment: Suicidal ideation (plan, intent, means, previous attempts), self-harm, harm to others.",
        "Investigations: TFTs, glucose, FBC, B12/folate, LFTs, drug screen, EEG if indicated.",
        "Capacity: Assess decision-making capacity for all major treatment decisions.",
    ]
    for pt in psych:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(Spacer(1, 6))

    story.append(Paragraph("17.2 Psychiatric Conditions - Summary", s['SubHeading']))
    tbl_data = [
        ["Condition", "First-Line Pharmacotherapy", "Adjunct / Notes"],
        ["Major Depressive Disorder", "SSRI (Sertraline 50-200mg or Escitalopram 10-20mg)",
         "CBT; review at 4 weeks; augment if no response at 6-8 wks"],
        ["Generalised Anxiety", "SSRI/SNRI (Sertraline, Venlafaxine)",
         "Buspirone; low-dose Clonazepam short-term; avoid long-term benzodiazepines"],
        ["Bipolar Disorder (Mania)", "Lithium / Valproate + Atypical antipsychotic",
         "Monitor lithium levels (0.6-1.0 mEq/L); TFTs, RFT"],
        ["Schizophrenia", "Atypical antipsychotic (Risperidone / Olanzapine)",
         "EPS monitoring; metabolic syndrome screen; LAI if non-compliant"],
        ["OCD", "SSRI (high dose: Fluoxetine 60-80mg) + ERP therapy",
         "Clomipramine as 2nd line; resistant OCD: augment with low-dose antipsychotic"],
        ["PTSD", "Sertraline / Paroxetine",
         "Trauma-focused CBT preferred; Prazosin for nightmares"],
    ]
    t = Table(tbl_data, colWidths=[3.5*cm, 4.5*cm, A4[0]-3.6*cm-8*cm])
    t.setStyle(tbl_style())
    story.append(t)

    story.append(Paragraph("17.3 Psychiatric IPD (Involuntary Admission)", s['SubHeading']))
    involuntary = [
        "Criteria: Serious mental disorder + significant risk to self or others + lacks capacity or refuses treatment.",
        "Observation ward: Continuous nursing observation; remove harmful objects; no unsupervised leave.",
        "Rapid tranquilisation: Lorazepam 1-2mg IM + Haloperidol 5mg IM if oral medication refused and patient is highly agitated.",
        "De-escalation: Verbal first; trained nursing staff; physical restraint only as last resort with documentation.",
    ]
    for pt in involuntary:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(PageBreak())


def sec18_emergency(story, s):
    story += section_divider(s, "18. EMERGENCY MEDICINE")

    story.append(Paragraph("18.1 Triage System (5-Level)", s['SubHeading']))
    triage = [
        ["Level", "Category", "Response Time", "Examples"],
        ["1", "Resuscitation", "Immediate", "Cardiac arrest, respiratory failure, GCS <=8"],
        ["2", "Emergent", "< 15 min", "STEMI, stroke, severe sepsis, anaphylaxis"],
        ["3", "Urgent", "< 30 min", "Moderate pain, fractures, febrile child, moderate dyspnoea"],
        ["4", "Semi-Urgent", "< 60 min", "Minor lacerations, stable abdominal pain, mild infections"],
        ["5", "Non-Urgent", "< 120 min", "Chronic symptoms, medication refills, minor injuries"],
    ]
    t = Table(triage, colWidths=[1.2*cm, 2.5*cm, 2.5*cm, A4[0]-3.6*cm-6.2*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 8))

    story.append(Paragraph("18.2 ABCDE Resuscitation Protocol", s['SubHeading']))
    abcde = [
        "A - Airway: Open airway (head-tilt chin-lift / jaw thrust); suction; OPA/NPA; intubation if no gag reflex.",
        "B - Breathing: O2 via non-rebreathe mask at 15 L/min; inspect chest; auscultate; SpO2; ABG.",
        "C - Circulation: IV access x2; fluid bolus 500 mL crystalloid if hypotensive; 12-lead ECG; FBC/UE/LFT/coag; blood cultures.",
        "D - Disability: GCS; pupils; BM (blood glucose); posturing; focal neurology.",
        "E - Exposure: Full body examination; temperature; skin lesions; rectal exam if GI bleed; logroll for spine.",
    ]
    for pt in abcde:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))
    story.append(Spacer(1, 6))

    story.append(Paragraph("18.3 Sepsis Six Bundle (within 1 hour)", s['SubHeading']))
    sepsis6 = [
        ["Action", "Details"],
        ["1. High-flow oxygen", "15 L/min via non-rebreathe mask; target SpO2 >94%"],
        ["2. Blood cultures", "2 sets (peripheral + central if line in situ) before antibiotics"],
        ["3. IV antibiotics", "Broad-spectrum (e.g. Piperacillin-Tazobactam 4.5g + Gentamicin if severe)"],
        ["4. IV fluid resuscitation", "30 mL/kg crystalloid bolus within 3 hours if lactate >2 or hypotensive"],
        ["5. Serial lactate", "Target lactate <2 mmol/L; repeat hourly if initially raised"],
        ["6. Urine output monitoring", "Foley catheter; target UO >0.5 mL/kg/h"],
    ]
    t = Table(sepsis6, colWidths=[3*cm, A4[0]-3.6*cm-3*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(PageBreak())


def sec19_infection(story, s):
    story += section_divider(s, "19. INFECTION CONTROL & ANTIBIOTIC POLICY")

    story.append(Paragraph("19.1 Hand Hygiene - 5 Moments", s['SubHeading']))
    moments = [
        "1. Before touching a patient",
        "2. Before a clean/aseptic procedure",
        "3. After body fluid exposure/risk",
        "4. After touching a patient",
        "5. After touching patient surroundings",
    ]
    for m in moments:
        story.append(Paragraph(m, s['BulletItem']))
    story.append(Paragraph(
        "Soap and water (30 seconds) for visible soiling. Alcohol hand-rub (20 seconds) for routine decontamination.",
        s['BodyText']))
    story.append(Spacer(1, 6))

    story.append(Paragraph("19.2 Isolation Precautions", s['SubHeading']))
    isolation = [
        ["Precaution Type", "Conditions", "PPE Required"],
        ["Contact", "MRSA, C. difficile, skin infections, wounds", "Gloves + gown"],
        ["Droplet", "Influenza, whooping cough, mumps, meningococcal", "Surgical mask + gloves + gown"],
        ["Airborne", "TB (pulmonary), measles, chickenpox, COVID-19 (aerosol-generating procedures)",
         "N95 + gloves + gown + eye protection"],
    ]
    t = Table(isolation, colWidths=[3*cm, 6*cm, A4[0]-3.6*cm-9*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 6))

    story.append(Paragraph("19.3 Empirical Antibiotic Policy", s['SubHeading']))
    abx = [
        ["Indication", "First-Line Antibiotic", "Duration"],
        ["Community-Acquired Pneumonia (mild)", "Amoxicillin 500mg TDS PO", "5 days"],
        ["CAP (moderate/severe)", "Co-amoxiclav + Clarithromycin IV", "7 days"],
        ["Urinary Tract Infection (uncomplicated)", "Nitrofurantoin 100mg BD PO", "3-5 days"],
        ["Complicated UTI/Pyelonephritis", "Ceftriaxone 1g IV OD", "7-14 days"],
        ["Skin & Soft Tissue (cellulitis)", "Flucloxacillin 1g QID IV", "5-10 days"],
        ["Intra-abdominal Sepsis", "Piperacillin-Tazobactam 4.5g TDS IV", "5-7 days"],
        ["Meningitis (bacterial)", "Ceftriaxone 2g BD IV + Dexamethasone 0.15 mg/kg QID", "10-14 days"],
        ["Febrile Neutropenia", "Piperacillin-Tazobactam 4.5g TDS IV", "Until ANC recovery"],
    ]
    t = Table(abx, colWidths=[4.5*cm, 5*cm, A4[0]-3.6*cm-9.5*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 6))
    story.append(Paragraph(
        "All antibiotic prescriptions must be reviewed at 48-72 hours. De-escalate when culture results available. "
        "Avoid broad-spectrum antibiotics unless clinically indicated. Refer to local antibiogram for resistance patterns.",
        s['BodyText']))
    story.append(PageBreak())


def sec20_discharge(story, s):
    story += section_divider(s, "20. DISCHARGE & FOLLOW-UP POLICY")

    story.append(Paragraph("20.1 Criteria for Discharge", s['SubHeading']))
    criteria = [
        "Clinically stable: Afebrile >24 hours, normalising inflammatory markers, haemodynamically stable.",
        "Tolerating oral medications and diet.",
        "Ambulating safely (or carer support arranged).",
        "Wound/drain removed or suitable for outpatient care.",
        "Patient and carer educated on discharge plan.",
    ]
    for c in criteria:
        story.append(Paragraph(f"- {c}", s['BulletItem']))
    story.append(Spacer(1, 6))

    story.append(Paragraph("20.2 Discharge Summary - Mandatory Components", s['SubHeading']))
    ds_items = [
        ["Component", "Details Required"],
        ["Patient Demographics", "Name, DOB, ID, address, contact"],
        ["Admission Details", "Date, admitting diagnosis, admitting doctor"],
        ["In-Hospital Investigations", "Key positive findings only"],
        ["Procedures Performed", "Including anaesthesia type"],
        ["Final Diagnoses", "Primary + secondary (ICD-10 coded)"],
        ["Medications on Discharge", "Drug, dose, route, frequency, duration"],
        ["Allergies", "Drug/allergy type with reaction description"],
        ["Follow-up Plan", "OPD date, referrals, repeat bloods/imaging"],
        ["Red Flags", "Symptoms requiring immediate return to ED"],
        ["Discharge Signed By", "Doctor name, designation, date, signature"],
    ]
    t = Table(ds_items, colWidths=[4*cm, A4[0]-3.6*cm-4*cm])
    t.setStyle(tbl_style())
    story.append(t)
    story.append(Spacer(1, 8))

    story.append(Paragraph("20.3 Follow-up Appointment Policy", s['SubHeading']))
    followup = [
        "Routine OPD follow-up scheduled before patient leaves the ward.",
        "High-risk patients (post-MI, post-stroke, heart failure, major surgery): Follow-up within 7 days.",
        "All others: Follow-up within 2-4 weeks.",
        "Patient given written summary + contact number for urgent queries.",
        "No-show protocol: Attempted phone contact at 24h; GP informed; letter at 1 week.",
        "Telemedicine/virtual OPD available for stable chronic disease follow-up.",
    ]
    for pt in followup:
        story.append(Paragraph(f"- {pt}", s['BulletItem']))

    story.append(Spacer(1, 16))
    story.append(HRFlowable(width="100%", thickness=1, color=DARK_BLUE))
    story.append(Spacer(1, 8))
    story.append(Paragraph(
        "This document is a living guideline. It is reviewed annually or whenever new evidence warrants update. "
        "For queries, contact the Clinical Governance Committee.",
        ParagraphStyle('Footer2', fontName='Helvetica-Oblique', fontSize=9,
                       textColor=GREY_TEXT, alignment=TA_CENTER, leading=13)))


# ═══════════════════════════════════════════════════════════════════════════════
# MAIN BUILD
# ═══════════════════════════════════════════════════════════════════════════════

def build_pdf(output_path):
    doc = BaseDocTemplate(
        output_path, pagesize=A4,
        leftMargin=1.8*cm, rightMargin=1.8*cm,
        topMargin=1.8*cm, bottomMargin=1.6*cm,
        title="OPD & IPD Clinical Guidelines - Multi-Speciality Hospital",
        author="Clinical Governance Committee",
        subject="OPD & IPD Guidelines 2026"
    )

    frame = Frame(
        doc.leftMargin, doc.bottomMargin,
        doc.width, doc.height - 30,
        id='normal'
    )
    template = PageTemplate(id='main', frames=[frame], onPage=header_footer)
    doc.addPageTemplates([template])

    s = build_styles()
    story = []

    cover_page(story, s)
    toc_page(story, s)
    sec1_general_policies(story, s)
    sec2_general_medicine(story, s)
    sec3_surgery(story, s)
    sec4_ortho(story, s)
    sec5_gynae(story, s)
    sec6_paeds(story, s)
    sec7_cardiology(story, s)
    sec8_pulm(story, s)
    sec9_gastro(story, s)
    sec10_neuro(story, s)
    sec11_nephro(story, s)
    sec12_endo(story, s)
    sec13_oncology(story, s)
    sec14_ophth(story, s)
    sec15_ent(story, s)
    sec16_derm(story, s)
    sec17_psych(story, s)
    sec18_emergency(story, s)
    sec19_infection(story, s)
    sec20_discharge(story, s)

    doc.build(story)
    print(f"PDF generated: {output_path}")


if __name__ == "__main__":
    build_pdf("/home/daytona/workspace/opd-ipd-guidelines/OPD_IPD_Clinical_Guidelines_2026.pdf")
Running Command

cd /home/daytona/workspace/opd-ipd-guidelines && python generate_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/opd-ipd-guidelines/OPD_IPD_Clinical_Guidelines_20…

Your PDF is ready! Here is your download link:

OPD IPD Clinical Guidelines 2026

PDF Document · PDF


What's included in this PDF:
The document covers 20 sections across all major specialities:
#SpecialityOPDIPD
1General PoliciesRegistration, prescriptions, referralsAdmission, nursing handover, VTE prophylaxis
2General MedicineHypertension, DM, anaemia, feverAKI fluids, sepsis, DVT
3General SurgeryPre-op assessment, consent, NBMPost-op care, wound, drain, antibiotics
4OrthopaedicsFracture management tableNeurovascular checks, DVT, physio
5Gynaecology & ObstetricsANC schedule, PCOS, fibroidsLabour, delivery, PPH, C-section
6Paediatrics & NeonatologyFull immunisation scheduleWeight-based dosing, sepsis, meningitis
7CardiologyChest pain protocol, risk scoringSTEMI, heart failure, AF management
8PulmonologyCOPD, asthma, TB, OSASevere asthma, PE, pneumothorax
9GastroenterologyGERD, peptic ulcer, IBS, IBDGI bleed protocol, variceal bleed
10Neurology & NeurosurgeryEpilepsy, migraine, Parkinson'sStroke protocol (time-to-needle), ICP management
11Nephrology & UrologyCKD staging tableAKI KDIGO staging, dialysis indications
12EndocrinologyDM targets tableDKA protocol (fluids, insulin, K+)
13OncologyAlarm symptoms, referral criteriaChemo safety, febrile neutropenia, TLS
14OphthalmologyEye exam protocolAcute glaucoma, retinal detachment, burns
15ENTOtitis media, tonsillitis, vertigoTonsillectomy, FESS post-op, haemorrhage
16DermatologyPsoriasis, eczema, acne, scabiesSJS/TEN, anaphylaxis, meningococcaemia
17PsychiatryMSE, risk assessment, medicationRapid tranquilisation, involuntary admission
18Emergency Medicine5-level triage systemABCDE protocol, Sepsis 6 bundle
19Infection ControlHand hygiene 5 moments, isolation typesEmpirical antibiotic policy table
20Discharge & Follow-up-Discharge criteria, summary components, follow-up schedule
The PDF includes a colour-coded cover page, table of contents, running header/footer, and formatted clinical tables throughout. Apologies for the wait!

Aesa karo general medicine ka jo banaya hoga tumne wo text paste krdo yhn

Here is the full General Medicine section content from the PDF:

2. GENERAL MEDICINE


2.1 OPD Protocol

History and physical examination are the cornerstone of every consult. Rational investigation ordering is encouraged. Avoid unnecessary repeat investigations.
Common OPD Conditions - Management Summary
ConditionKey AssessmentFirst-Line ManagementReferral Trigger
HypertensionBP both arms, fundoscopy, ECGLifestyle + Amlodipine 5 mg / Losartan 50 mgBP >180/110 refractory; secondary HTN
Type 2 DiabetesFBS, HbA1c, foot exam, urine microalbuminMetformin 500mg BD; titrateHbA1c >10%, ESRD, foot ulcer
HypothyroidismTSH, FT4, lipidsLevothyroxine 1.6 mcg/kg/dayMyxoedema, pregnancy
AnaemiaCBC, peripheral smear, iron studies, B12Iron / B12 / folate per aetiologyHb <7 g/dL, haemolysis, malignancy
Fever (Acute)Temp, malaria card, CBC, CRP, urinalysisParacetamol 500-1000 mg Q6H; targeted ABxTemp >39.5°C >5 days; severe sepsis
URTIThroat, ears, LN, SpO2Symptomatic; avoid ABx unless bacterialSpO2 <94%, stridor, peritonsillar abscess
Asthma (Stable)PEFR, spirometry, triggersSABA PRN + ICS (low-medium dose)Severe/brittle asthma

2.2 IPD Protocol

Admit for: Uncontrolled sepsis, hypertensive emergency (>180/120 with end-organ damage), DKA, severe anaemia (Hb <7), COPD exacerbation.
  • Daily review: Vitals, input/output chart, medication reconciliation, labs review, wound inspection if applicable.
  • Blood cultures: 2 sets from different sites before starting antibiotics.
  • Fluid management: Assess hydration status twice daily. Avoid over-hydration in cardiac/renal patients.
  • Electrolytes: Monitor Na, K, Mg, phosphate daily in critically ill. Replace deficits cautiously.
  • DVT prophylaxis: All bedridden medical patients - LMWH (Enoxaparin 40 mg SC OD) unless contraindicated.

Yahi content PDF mein Section 2 ke andar hai. Agar koi condition expand karni ho - jaise sirf Diabetes ya Hypertension ka detailed protocol chahiye - to batao, woh bhi likh deta hoon.

Elaborate krdo with real case scenario

Here is the fully elaborated General Medicine section with real clinical case scenarios for each condition:

GENERAL MEDICINE - ELABORATED CLINICAL GUIDELINES


2.1 OPD PROTOCOLS


CONDITION 1: HYPERTENSION

Definition: Sustained BP ≥140/90 mmHg on 2 separate readings.
Key Assessment:
  • BP in both arms (sitting + standing for orthostatic drop)
  • Fundoscopy - look for AV nipping, flame haemorrhages, papilloedema
  • ECG - LVH (Sokolow-Lyon criteria: S in V1 + R in V5 >35 mm)
  • Urine dipstick - proteinuria (renal cause or end-organ damage)
  • FBS, lipid profile, serum creatinine, electrolytes
First-Line Management:
StageBP RangeTreatment
Elevated130-139/80-89Lifestyle modification only
Stage 1140-159/90-99Amlodipine 5mg OD or Losartan 50mg OD
Stage 2≥160/100Dual therapy: Amlodipine + Losartan
Hypertensive Urgency>180/110, no end-organ damageOral Amlodipine 10mg; reduce BP over 24-48h
Hypertensive Emergency>180/120 + end-organ damageIV Labetalol/Nitroglycerine; ICU admission

REAL CASE SCENARIO - Hypertension
Patient: Mr. Ramesh Gupta, 54 years, male, software engineer.
Presenting Complaint: Headache and blurred vision for 2 days.
OPD Findings:
  • BP Right arm: 178/108 mmHg | BP Left arm: 176/106 mmHg
  • Fundoscopy: Grade 2 hypertensive retinopathy (AV nipping, silver wiring)
  • ECG: LVH pattern
  • Urine dipstick: Protein ++
  • BMI: 29 kg/m2 (overweight), smoker (15 pack-years)
Diagnosis: Stage 2 Hypertension with early end-organ damage (LVH + proteinuria).
Management:
  1. Started Amlodipine 5mg OD + Losartan 50mg OD
  2. Advised low-sodium diet (<2g/day), smoking cessation, 30 min walking daily
  3. Referral to ophthalmology for formal retinal assessment
  4. Renal function test + urine microalbumin ordered
  5. Follow-up in 2 weeks to reassess BP; target <130/80 in 3 months
Outcome: At 4-week follow-up, BP reduced to 144/92 - dose of Losartan uptitrated to 100mg.

CONDITION 2: TYPE 2 DIABETES MELLITUS

Definition: Fasting glucose ≥126 mg/dL on 2 occasions, or HbA1c ≥6.5%, or 2h OGTT ≥200 mg/dL.
Key Assessment:
  • FBS + HbA1c (every 3 months if uncontrolled, every 6 months if stable)
  • Foot exam: monofilament test, Doppler if pulses reduced
  • Urine microalbumin/creatinine ratio (annual)
  • Retinal screening (annual dilated fundoscopy)
  • Lipid profile, LFT, RFT
Stepwise Drug Therapy:
StepDrugNotes
Step 1Metformin 500mg BD → 1g BDWith food; hold if eGFR <30
Step 2Add SGLT2i (Empagliflozin 10mg) or GLP-1 RAPrefer SGLT2i if heart failure/CKD
Step 3Add DPP-4i (Sitagliptin 100mg) or SulphonylureaSulphonylurea has hypoglycaemia risk
Step 4Basal Insulin (Glargine 10 units SC OD at night)Titrate by 2 units every 3 days

REAL CASE SCENARIO - Type 2 Diabetes
Patient: Mrs. Sunita Devi, 48 years, female, homemaker.
Presenting Complaint: Increased thirst, frequent urination, and fatigue for 3 months. Wound on right great toe not healing for 6 weeks.
OPD Findings:
  • FBS: 218 mg/dL | HbA1c: 10.4%
  • BMI: 32 kg/m2
  • Foot exam: 2x2 cm neuropathic ulcer on right hallux, reduced monofilament sensation bilaterally
  • BP: 148/92 mmHg
  • Urine microalbumin: 85 mg/g creatinine (microalbuminuria)
Diagnosis: Type 2 DM with peripheral neuropathy, diabetic foot ulcer (Wagner Grade 2), and diabetic nephropathy.
Management:
  1. Metformin 500mg BD + Empagliflozin 10mg OD (also protective for kidneys)
  2. Losartan 50mg OD added for BP + nephroprotection
  3. Foot ulcer wound care: daily dressing, off-loading footwear
  4. Referred to vascular surgery + podiatry
  5. Statin added (Atorvastatin 40mg OD)
  6. Diabetes education session for diet, foot care, glucose monitoring
Red Flag: HbA1c >10% with active foot ulcer - patient counselled about risk of amputation if non-compliant.
IPD Trigger: Patient admitted for IV antibiotics when wound showed signs of infection (Ceftriaxone + Metronidazole).

CONDITION 3: HYPOTHYROIDISM

Definition: Insufficient thyroid hormone production. TSH >4.5 mIU/L with low FT4.
Key Assessment:
  • TSH + FT4 (FT3 rarely needed)
  • Anti-TPO antibody (Hashimoto's thyroiditis if positive)
  • Lipid profile (hypothyroidism causes dyslipidaemia)
  • ECG (bradycardia, low-voltage complexes in severe cases)
Management:
TypeTSH LevelTreatment
Subclinical hypothyroidismTSH 4.5-10, normal FT4Treat if symptomatic or pregnant
Overt hypothyroidismTSH >10, low FT4Levothyroxine 1.6 mcg/kg/day
Elderly/cardiac patientsAnyStart low: 25 mcg/day; uptitrate every 4 weeks

REAL CASE SCENARIO - Hypothyroidism
Patient: Ms. Priya Sharma, 32 years, female, teacher.
Presenting Complaint: Weight gain of 8 kg in 6 months, constipation, hair loss, feeling cold all the time, and irregular periods.
OPD Findings:
  • TSH: 38 mIU/L (severely elevated)
  • FT4: 0.4 ng/dL (low)
  • Anti-TPO antibody: Positive (1:1600)
  • Total cholesterol: 268 mg/dL
  • Pulse: 58/min
  • Dry coarse skin, periorbital puffiness, delayed ankle reflex
Diagnosis: Overt Autoimmune Hypothyroidism (Hashimoto's Thyroiditis) with dyslipidaemia.
Management:
  1. Levothyroxine 75 mcg OD (empty stomach, 30 min before breakfast)
  2. Recheck TSH + FT4 after 6 weeks
  3. No separate statin prescribed - dyslipidaemia expected to resolve with thyroid treatment
  4. Gynaecology referral for menstrual irregularity
  5. Target TSH: 0.5-2.5 mIU/L
Follow-up: At 3 months, TSH normalised to 2.1. Weight reduced by 4 kg. Cholesterol down to 198 mg/dL.

CONDITION 4: ANAEMIA

Definition: Hb <13 g/dL (males), <12 g/dL (females), <11 g/dL (pregnant).
Approach - Find the Cause First:
TypeMCVKey ClueTreatment
Iron DeficiencyLow (<80)Microcytic hypochromic, low ferritinFerrous sulphate 200mg BD x 3 months
B12 DeficiencyHigh (>100)Macrocytic, neurological symptomsIM Cyanocobalamin 1000 mcg x 6 doses, then monthly
Folate DeficiencyHigh (>100)Macrocytic, no neuro symptomsFolic acid 5mg OD x 4 months
ThalassaemiaLowEthnic background, family history, target cellsGenetic counselling; transfusion only if severe
Haemolytic AnaemiaNormal/HighRaised bilirubin, reticulocytosis, +ve CoombsSteroids; haematology referral

REAL CASE SCENARIO - Anaemia
Patient: Mrs. Kavita Joshi, 28 years, female, 20 weeks pregnant.
Presenting Complaint: Breathlessness on walking, palpitations, fatigue.
OPD Findings:
  • Hb: 7.8 g/dL
  • MCV: 68 fL (microcytic)
  • Serum ferritin: 4 ng/mL (severely low)
  • Peripheral smear: Microcytic hypochromic red cells, pencil cells
  • Dietary history: Vegetarian, low iron intake
Diagnosis: Severe Iron Deficiency Anaemia in Pregnancy.
Management:
  1. IV Iron Sucrose 200mg in 100 mL NS over 15 min (oral iron not tolerated / insufficient time)
  2. Vitamin C 500mg OD to enhance iron absorption
  3. Dietary counselling: Spinach, jaggery, dates, legumes, meat
  4. Haematinics: Folic acid 5mg + Ferrous sulphate continued after IV course
  5. Repeat Hb at 4 weeks; target Hb >10 before delivery
  6. Obstetric team alerted for delivery planning
IPD Trigger: If Hb <7 at term or symptomatic - admit for blood transfusion (packed red cells 1 unit at a time, recheck Hb after each unit).

CONDITION 5: ACUTE FEVER

Key Assessment:
  • Temperature, HR, BP, SpO2, RR
  • Malaria antigen test (RDT) + blood smear
  • CBC with differential (WBC for bacterial vs viral pattern)
  • Urine routine/microscopy
  • CRP / Procalcitonin (if sepsis suspected)
  • Blood cultures x2 before starting antibiotics
Fever Patterns and Their Clinical Significance:
PatternDescriptionAssociated Condition
ContinuousTemp stays high, <1°C variationTyphoid, lobar pneumonia
RemittentVaries >1°C, never normalTB, viral infections
IntermittentTouches normal each dayMalaria, septicaemia
Hectic/SepticWide swings with chills/rigorsAbscess, endocarditis
Pel-EbsteinAlternating fever and normal periodsHodgkin's Lymphoma

REAL CASE SCENARIO - Acute Fever
Patient: Mr. Arjun Singh, 22 years, male, student. Returned from Rajasthan 5 days ago.
Presenting Complaint: Fever with chills and rigors for 4 days, worse every alternate day. Headache, vomiting.
OPD Findings:
  • Temp: 39.8°C | HR: 110/min | BP: 104/70 mmHg
  • SpO2: 97%
  • Splenomegaly noted on examination
  • Malaria RDT: Positive for Plasmodium vivax
  • CBC: Hb 10.2 g/dL, Platelet 68,000/uL
  • Blood smear: Schüffner's dots in enlarged RBCs confirming P. vivax
Diagnosis: Vivax Malaria with thrombocytopenia.
Management:
  1. Chloroquine 600mg stat → 300mg at 6h → 300mg OD x 2 days
  2. Primaquine 15mg OD x 14 days (radical cure; check G6PD first)
  3. Paracetamol 1g Q6H for fever
  4. Oral hydration encouraged; IV fluids if vomiting persists
  5. Daily platelet monitoring
IPD Trigger: Platelet <50,000 + bleeding signs, or P. falciparum on smear, or cerebral malaria signs (altered sensorium) - immediate admission.
Outcome: Fever resolved by Day 3. Platelet normalised by Day 7. Completed 14-day Primaquine course.

CONDITION 6: UPPER RESPIRATORY TRACT INFECTION (URTI)

Key Assessment:
  • Throat exam (exudate, size of tonsils)
  • Ear exam (otitis media)
  • Lymph nodes (tender cervical lymphadenopathy)
  • SpO2, RR (to rule out LRTI)
  • Centor Score for bacterial tonsillitis:
Centor CriteriaScore
Tonsillar exudate+1
Tender anterior cervical lymph nodes+1
Fever (Temp >38°C)+1
Absence of cough+1
Age 3-14 years+1
Score ≥3 → Treat with antibiotics. Score <3 → Symptomatic only.

REAL CASE SCENARIO - URTI
Patient: Master Rohan Mehta, 8 years, male.
Presenting Complaint: Sore throat, fever 38.5°C, difficulty swallowing for 2 days. No cough.
OPD Findings:
  • Tonsils grade 3, bilateral white exudate
  • Tender anterior cervical lymph nodes bilaterally
  • Centor Score: 4 (exudate + lymph nodes + fever + no cough)
  • SpO2 99%, RR 18/min (normal)
Diagnosis: Bacterial Tonsillitis (likely Group A Streptococcus).
Management:
  1. Amoxicillin 40mg/kg/day in 3 divided doses x 10 days
  2. Paracetamol syrup 15mg/kg Q6H for fever and pain
  3. Warm salt water gargles
  4. Throat swab for culture sent
  5. Parents advised: Complete full antibiotic course to prevent rheumatic fever
  6. Return if no improvement in 48 hours or develops difficulty breathing
Red Flag Counselling: Peritonsillar abscess - if drooling, muffled voice, trismus, deviation of uvula → Emergency ENT referral.

CONDITION 7: STABLE ASTHMA

GINA Step-wise Management:
GINA StepSeverityControllerReliever
Step 1Mild intermittentNone neededSABA (Salbutamol) PRN
Step 2Mild persistentLow-dose ICS (Budesonide 200mcg BD)SABA PRN
Step 3Moderate persistentLow-ICS + LABA (Formoterol)SABA PRN
Step 4Severe persistentMedium/high ICS + LABA + LTRASABA PRN
Step 5UncontrolledAdd biologic (Omalizumab/Mepolizumab)SABA PRN

REAL CASE SCENARIO - Stable Asthma
Patient: Ms. Neha Kapoor, 19 years, female, college student.
Presenting Complaint: Episodic wheeze and shortness of breath, 3 times/week for past month. Worse at night and during exercise.
OPD Findings:
  • Spirometry: FEV1/FVC = 0.68 (obstructive), FEV1 72% predicted
  • Post-bronchodilator FEV1 improvement: 18% (significant reversibility)
  • PEFR: 320 L/min (predicted 450 L/min)
  • Triggers identified: Dust mites, cold air, exercise
  • No history of smoking; family history of atopy
Diagnosis: Moderate Persistent Asthma (GINA Step 3).
Management:
  1. Budesonide/Formoterol 160/4.5 mcg inhaler - 1 puff BD (controller)
  2. Salbutamol MDI 100 mcg - 2 puffs PRN for acute symptoms (reliever)
  3. Spacer device prescribed and technique demonstrated
  4. Written Asthma Action Plan given
  5. Dust mite covers for mattress/pillow; avoid cold exposure
  6. PEFR diary to monitor at home
  7. Review in 4 weeks; spirometry at 3 months
Inhaler Technique Check (Mandatory at every OPD visit): Shake → Exhale fully → Seal lips → Slow deep breath while pressing → Hold 10 seconds → Rinse mouth after ICS
IPD Trigger: If PEFR <50%, SpO2 <92%, unable to speak in full sentences, or no response to 3 doses of Salbutamol - Emergency admission.

2.2 IPD PROTOCOLS - ELABORATED


IPD CASE SCENARIO - Hypertensive Emergency

Patient: Mr. Vijay Kumar, 60 years, male, known hypertensive (non-compliant with medications).
Admitted With: Severe headache, vomiting, confusion. BP: 210/130 mmHg.
Investigations:
  • ECG: LVH with strain pattern
  • Creatinine: 2.8 mg/dL (raised from baseline 1.2)
  • Urine: Red cell casts (hypertensive nephropathy)
  • CT Brain: Posterior Reversible Encephalopathy Syndrome (PRES) pattern
IPD Management:
  1. ICU admission; continuous cardiac + BP monitoring
  2. IV Labetalol 20mg bolus → infusion at 2 mg/min
  3. Target: Reduce MAP by no more than 25% in first hour (rapid reduction can cause stroke/MI)
  4. Foley catheter - urine output monitoring
  5. Neurologist called for PRES management
  6. Once stable: Oral antihypertensives restarted + patient counselled on compliance
Key Teaching Point: In hypertensive emergency, DO NOT reduce BP too fast. Cerebral autoregulation is set at the high BP - rapid drop causes watershed ischaemia.

IPD CASE SCENARIO - Severe Anaemia Requiring Transfusion

Patient: Mr. Suresh Rao, 70 years, male, chronic alcoholic.
Admitted With: Breathlessness at rest, pallor, tachycardia.
  • Hb: 5.2 g/dL
  • MCV: 108 fL
  • Peripheral smear: Hypersegmented neutrophils + macrocytes
  • Serum B12: 94 pg/mL (low normal); Folate: 1.8 ng/mL (deficient)
IPD Management:
  1. Blood transfusion: 1 unit packed RBC over 4 hours (with Furosemide 20mg IV pre-transfusion given cardiac risk)
  2. Recheck Hb after each unit before further transfusion
  3. IM Methylcobalamin 1000 mcg OD x 7 days, then weekly x 4 weeks
  4. Folic acid 5mg OD oral started simultaneously
  5. Alcohol cessation counselling + hepatology referral
  6. Target Hb >8 before discharge
DVT Prophylaxis: Enoxaparin 40 mg SC OD started (bedridden, anaemic, elderly = high DVT risk).

This is the complete, elaborated General Medicine section with 7 OPD conditions and 2 IPD emergency cases, each with a real clinical scenario showing how a doctor would actually manage the patient from arrival to discharge. Let me know if you want any condition expanded further or want similar elaboration for another speciality.
This is a shared conversation. Sign in to Orris to start your own chat.