What are the parts included in abdomen teach me with a diagram

Reading File
Finding Sources
Searching the Web

abdomen parts regions anatomy diagram labeled

Finding Sources
Loading Image
Reading File
Loading Image
Reading File
Generating Image

Detailed labeled anatomy diagram of the abdomen showing: 1) The nine abdominal regions (right hypochondriac, epigastric, left hypochondriac, right lumbar, umbilical, left lumbar, right iliac/inguinal, hypogastric/pubic, left iliac/inguinal) with grid lines; 2) All major organs labeled inside their respective regions: liver and gallbladder in right hypochondriac, stomach and spleen in left hypochondriac, small intestine and transverse colon in umbilical, appendix and cecum in right iliac, sigmoid colon in left iliac, bladder in hypogastric; 3) The abdominal wall layers on a side cross-section inset: skin, subcutaneous fat, external oblique, internal oblique, transversus abdominis, peritoneum; 4) Bony landmarks labeled: xiphoid process, costal margin, iliac crest, pubic symphysis; 5) Major vessels: abdominal aorta, inferior vena cava. Clean medical illustration style, white background, color-coded organs, clear label lines

Here is a complete guide to the abdomen, with diagrams!

The Abdomen - Parts & Anatomy

The abdomen is the region of the body between the thorax (chest) above and the pelvis below. It is bounded:
  • Superiorly - the diaphragm (at vertebral level T12 posteriorly, xiphoid process anteriorly)
  • Inferiorly - the pelvic inlet
  • Anteriorly - the abdominal wall muscles
  • Posteriorly - the lumbar vertebrae (L1-L5)

πŸ“ DIAGRAM 1: The Nine Abdominal Regions

Nine abdominal regions 3D diagram
The abdomen is divided into 9 regions by two vertical lines (midclavicular lines) and two horizontal lines (subcostal and transtubercular planes):
RegionLocationKey Organs
Right HypochondriacUpper rightRight lobe of liver, gallbladder, right kidney, small intestine
EpigastricUpper middleStomach, left lobe of liver, duodenum, head of pancreas
Left HypochondriacUpper leftSpleen, left kidney, stomach, tail of pancreas, part of colon
Right LumbarMiddle rightAscending colon, right kidney, part of liver
UmbilicalMiddle centerSmall intestine (jejunum/ileum), transverse colon, aorta
Left LumbarMiddle leftDescending colon, left kidney, parts of small intestine
Right Iliac (Inguinal)Lower rightCecum, appendix, right ovary (females)
Hypogastric (Pubic)Lower middleUrinary bladder, uterus (females), sigmoid colon, rectum
Left Iliac (Inguinal)Lower leftSigmoid colon, left ovary (females)

πŸ“ DIAGRAM 2: Nine Regions with Planes

Nine regions with transpyloric and transtubercular planes

πŸ“ DIAGRAM 3: Custom Labeled Anatomy Diagram

Detailed abdomen anatomy diagram with organs, regions, and abdominal wall layers

πŸ”² Alternative: 4-Quadrant Division

Clinicians also commonly divide the abdomen into 4 quadrants using just the umbilicus as the crossing point:
QuadrantAbbreviationContents
Right Upper QuadrantRUQLiver, gallbladder, right kidney, duodenum, pancreas head, hepatic flexure of colon
Left Upper QuadrantLUQStomach, spleen, left kidney, pancreas body/tail, splenic flexure of colon
Right Lower QuadrantRLQCecum, appendix, right ovary/tube, right ureter
Left Lower QuadrantLLQSigmoid colon, left ovary/tube, left ureter

πŸ—οΈ Layers of the Abdominal Wall

From outside in:
  1. Skin
  2. Subcutaneous fat (Camper's fascia)
  3. Scarpa's fascia (membranous layer of superficial fascia)
  4. External oblique muscle
  5. Internal oblique muscle
  6. Transversus abdominis muscle
  7. Transversalis fascia
  8. Preperitoneal fat
  9. Parietal peritoneum

πŸ«€ Major Vessels in the Abdomen

  • Abdominal aorta - runs down the midline, gives off celiac trunk (L1), superior mesenteric artery (L1), renal arteries (L1-L2), inferior mesenteric artery (L3), and bifurcates into common iliac arteries at L4
  • Inferior vena cava (IVC) - runs to the right of the aorta, drains into the right atrium through the diaphragm at T8

πŸ“Œ Key Landmarks

LandmarkVertebral Level
Xiphoid processT9-T10
Transpyloric planeL1
Subcostal planeL3
UmbilicusL3-L4
Transtubercular planeL5
Pubic symphysisS3-S4

Sources: Gray's Anatomy for Students (textbook) | Kenhub - Abdominal Regions

What are the parts included in the pelvis what should be learnt

Reading File
Finding Sources
Searching the Web

pelvis anatomy parts regions bones muscles organs what to learn medical students diagram

Reading File
Loading Image
Loading Image
Finding Sources
Loading Image
Loading Image
Generating Image

Labeled anatomy diagram of the bony pelvis showing: ilium with iliac crest, ASIS (anterior superior iliac spine), AIIS (anterior inferior iliac spine), PSIS (posterior superior iliac spine), iliac fossa, arcuate line; ischium with ischial spine, ischial tuberosity, lesser and greater sciatic notch; pubis with pubic symphysis, superior and inferior pubic ramus, obturator foramen; sacrum with sacral promontory and sacral foramina; coccyx; pelvic inlet (brim) marked with linea terminalis; greater pelvis (false pelvis) and lesser pelvis (true pelvis) labeled; acetabulum labeled. Also show key dimensions: transverse diameter 13cm, obstetric conjugate 11cm. Side panel showing male vs female pelvis differences. Clean medical illustration, white background, color-coded bones

What are the topic included in the pelvis

Finding Sources
Searching the Web

pelvis anatomy topics syllabus medical students Gray's anatomy curriculum

Reading File
Finding Sources
Finding Sources
Reading File
Reading Web Page

https://teachmeanatomy.info/pelvis

Reading File
Generating Image

A clean medical study guide mind map showing all topics included in Pelvis anatomy. Central node says "PELVIS". Branches spread out to these 8 main topic categories, each with sub-topics listed: 1) BONY PELVIS - Hip bone (Ilium, Ischium, Pubis), Sacrum, Coccyx, Greater vs Lesser pelvis, Pelvic inlet/outlet, Male vs Female pelvis differences; 2) JOINTS & LIGAMENTS - Sacroiliac joint, Pubic symphysis, Sacrospinous ligament, Sacrotuberous ligament; 3) PELVIC WALLS & FLOOR - Obturator internus, Piriformis, Levator ani (pubococcygeus, iliococcygeus, puborectalis), Coccygeus; 4) PELVIC ORGANS - Urinary bladder, Ureter, Rectum, Uterus (female), Ovaries & uterine tubes (female), Prostate & seminal vesicles (male); 5) BLOOD VESSELS - Internal iliac artery (anterior/posterior trunk), Internal iliac vein, Ovarian/testicular vessels; 6) NERVES - Lumbosacral trunk, Sacral plexus, Pudendal nerve, Autonomic nerves; 7) PERINEUM - Anal triangle, Urogenital triangle, Perineal membrane, Pouches, Erectile tissues; 8) CLINICAL TOPICS - Childbirth mechanics, Pelvic fractures, Pelvic inflammatory disease. Color-coded branches, white background, educational poster style

What are the topics included in the pelvis anatomy

Finding Sources
Searching the Web

pelvis anatomy complete topic list medical curriculum bony pelvis muscles organs nerves vessels perineum

Reading File
Generating Image

A clean, color-coded medical study poster titled "PELVIS ANATOMY - Complete Topic List" with a structured outline layout (not a mind map). Use colored section boxes for each major topic. Include these 8 numbered sections with their sub-topics listed underneath each: 1. BONY PELVIS (blue box) - Hip bone: Ilium, Ischium, Pubis / Sacrum & Coccyx / Pelvic inlet & outlet / Greater pelvis vs Lesser (true) pelvis / Pelvic diameters / Male vs Female pelvis differences 2. JOINTS & LIGAMENTS (green box) - Sacroiliac joint / Pubic symphysis / Sacrospinous ligament / Sacrotuberous ligament / Lumbosacral joint 3. PELVIC WALLS & FLOOR (orange box) - Pelvic walls: Obturator internus, Piriformis / Pelvic diaphragm: Levator ani (pubococcygeus, iliococcygeus, puborectalis), Coccygeus / Fascia of pelvic floor 4. PELVIC VISCERA / ORGANS (red box) - Urinary bladder / Ureters / Rectum & anal canal / Male: Prostate, Seminal vesicles, Ductus deferens / Female: Uterus, Ovaries, Uterine tubes, Vagina / Peritoneum & pouches 5. BLOOD VESSELS (purple box) - Internal iliac artery: anterior trunk, posterior trunk / Branches: obturator, vesical, uterine, vaginal, pudendal, gluteal / Internal iliac vein / Ovarian/testicular vessels 6. NERVES (yellow box) - Lumbosacral trunk / Sacral plexus (L4-S3) / Pudendal nerve / Obturator nerve / Autonomic nerves: pelvic splanchnic nerves, hypogastric plexus / Coccygeal plexus 7. PERINEUM (teal box) - Anal triangle: external anal sphincter, ischio-anal fossa / Urogenital triangle: perineal membrane, superficial & deep perineal pouches / Male perineum: penis, scrotum, bulb / Female perineum: clitoris, vulva, vaginal opening / Perineal body 8. CLINICAL CORRELATIONS (gray box) - Pudendal nerve block / Episiotomy / Pelvic fractures / Prostate enlargement / Ectopic pregnancy / Uterine prolapse / Childbirth mechanics White background, professional educational style, large clear font

Here is the complete breakdown of all topics in Pelvis Anatomy, drawn from Gray's Anatomy for Students (Chapter 5):

Pelvis Anatomy Complete Topic List

πŸ“š Complete Topics in Pelvis Anatomy


1. 🦴 BONY PELVIS

The structural foundation - always start here.
  • Hip bone (Os coxae) - made of 3 fused bones:
    • Ilium - iliac crest, ASIS, AIIS, PSIS, iliac fossa, arcuate line
    • Ischium - ischial spine, ischial tuberosity, lesser & greater sciatic notch
    • Pubis - pubic symphysis, superior & inferior pubic ramus, obturator foramen
  • Sacrum - sacral promontory, sacral foramina, sacral canal
  • Coccyx
  • Greater pelvis (false) vs Lesser pelvis (true)
  • Pelvic inlet (brim) and pelvic outlet
  • Pelvic diameters (obstetric conjugate ~11 cm, transverse ~13 cm)
  • Male vs Female pelvis differences

2. πŸ”— JOINTS & LIGAMENTS

  • Sacroiliac joint - fibrocartilaginous, very strong
  • Pubic symphysis - secondary cartilaginous joint
  • Sacrospinous ligament - divides greater & lesser sciatic foramen
  • Sacrotuberous ligament
  • Lumbosacral joint

3. πŸ’ͺ PELVIC WALLS & FLOOR

  • Pelvic walls:
    • Obturator internus
    • Piriformis
  • Pelvic floor (Pelvic diaphragm):
    • Levator ani (3 parts):
      • Pubococcygeus
      • Iliococcygeus
      • Puborectalis
    • Coccygeus
  • Obturator canal and obturator membrane
  • Fascia of pelvic floor and walls

4. πŸ«€ PELVIC VISCERA (Organs)

  • Urinary bladder - trigone, detrusor muscle, neck
  • Ureters - pelvic course, relation to uterine artery ("water under the bridge")
  • Rectum & Anal canal
  • Male organs: Prostate, Seminal vesicles, Ductus deferens, Ejaculatory ducts
  • Female organs: Uterus, Ovaries, Uterine (Fallopian) tubes, Vagina
  • Peritoneum - rectouterine pouch (of Douglas), vesicouterine pouch, rectovesical pouch (male)

5. 🩸 BLOOD VESSELS

  • Internal iliac artery - main artery of the pelvis
    • Posterior trunk: Iliolumbar, lateral sacral, superior gluteal arteries
    • Anterior trunk: Umbilical, obturator, vesical, uterine/vaginal, middle rectal, internal pudendal, inferior gluteal arteries
  • Internal iliac vein and tributaries
  • Median sacral artery
  • Ovarian/testicular vessels (from aorta)
  • Lymphatics - internal, external, common iliac nodes

6. 🧠 NERVES

  • Lumbosacral trunk (L4-L5)
  • Sacral plexus (L4-S3):
    • Superior & inferior gluteal nerves
    • Sciatic nerve (largest nerve in the body)
    • Pudendal nerve (S2-S4) - main nerve of perineum
    • Nerve to obturator internus, piriformis, quadratus femoris
    • Posterior cutaneous nerve of thigh
  • Coccygeal plexus
  • Autonomic nerves:
    • Pelvic splanchnic nerves (parasympathetic S2-S4) - control erection & bladder
    • Hypogastric plexus (sympathetic) - controls ejaculation
    • Inferior hypogastric (pelvic) plexus

7. πŸ”Ί PERINEUM

The perineum is a diamond-shaped region inferior to the pelvic floor. It is divided by a line between the ischial tuberosities into:
A. Anal Triangle (posterior)
  • Ischio-anal fossae
  • External anal sphincter (deep, superficial, subcutaneous parts)
  • Anococcygeal body
B. Urogenital Triangle (anterior)
  • Perineal membrane
  • Deep perineal pouch: external urethral sphincter, deep transverse perineal muscle
  • Superficial perineal pouch: erectile tissues, ischiocavernosus, bulbospongiosus muscles
  • In men: crura of penis, bulb of penis, corpus cavernosum, corpus spongiosum
  • In women: crura of clitoris, bulbs of vestibule, Bartholin's (greater vestibular) glands
  • Perineal body - central fibromuscular node where everything converges

8. πŸ₯ CLINICAL CORRELATIONS

TopicRelevance
Pudendal nerve blockAnalgesia in childbirth at ischial spine
EpisiotomyCut at perineal body during delivery
Pelvic fracturesRisk to bladder, urethra, pudendal vessels
Prostate enlargement (BPH)Urethral compression, urinary retention
Ectopic pregnancyRupture into rectouterine pouch
Uterine prolapseLevator ani weakness
Ureteric injuryRisk in hysterectomy - ureter crosses under uterine artery
VaricoceleDilated pampiniform plexus
Digital rectal examPalpates prostate posteriorly through rectum
Childbirth mechanicsPelvic diameters, fetal head engagement

πŸ“‹ Study Order Recommendation (from Gray's)

1. Bony pelvis & landmarks
2. Joints & ligaments
3. Pelvic walls & floor muscles
4. Pelvic viscera (start with bladder β†’ rectum β†’ reproductive organs)
5. Peritoneum & fascial spaces
6. Nerves (somatic first, then autonomic)
7. Blood vessels & lymphatics
8. Perineum (anal triangle β†’ urogenital triangle)
9. Clinical cases

Source: Gray's Anatomy for Students, Chapter 5 - Pelvis and Perineum (pages 413-515)

Create a summary PDF of pelvis anatomy for quick revision

Reading File
Running Command

mkdir -p /home/daytona/workspace/pelvis-anatomy && ls /home/daytona/workspace/

Writing File

~/pelvis-anatomy/generate_pdf.py

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

OUTPUT = "/home/daytona/workspace/pelvis-anatomy/Pelvis_Anatomy_Quick_Revision.pdf"

# ── Colour palette ──────────────────────────────────────────────────────────
C_NAVY    = colors.HexColor("#1A3560")
C_BLUE    = colors.HexColor("#2C6FAC")
C_LBLUE   = colors.HexColor("#D6E8F7")
C_ORANGE  = colors.HexColor("#E07B39")
C_LORANGE = colors.HexColor("#FDE9D9")
C_GREEN   = colors.HexColor("#2E7D52")
C_LGREEN  = colors.HexColor("#D4EDDA")
C_PURPLE  = colors.HexColor("#5B3F8C")
C_LPURPLE = colors.HexColor("#EDE3F7")
C_RED     = colors.HexColor("#C0392B")
C_LRED    = colors.HexColor("#FAD7D3")
C_TEAL    = colors.HexColor("#117A8B")
C_LTEAL   = colors.HexColor("#D1ECF1")
C_DGRAY   = colors.HexColor("#343A40")
C_LGRAY   = colors.HexColor("#F4F5F7")
C_YELLOW  = colors.HexColor("#856404")
C_LYELLOW = colors.HexColor("#FFF3CD")
WHITE     = colors.white

# ── Styles ───────────────────────────────────────────────────────────────────
styles = getSampleStyleSheet()

def S(name, **kw):
    return ParagraphStyle(name, **kw)

sTitle = S("sTitle",
    fontSize=26, fontName="Helvetica-Bold",
    textColor=WHITE, alignment=TA_CENTER, spaceAfter=4)
sSubtitle = S("sSubtitle",
    fontSize=13, fontName="Helvetica",
    textColor=WHITE, alignment=TA_CENTER, spaceAfter=2)
sSource = S("sSource",
    fontSize=9, fontName="Helvetica-Oblique",
    textColor=colors.HexColor("#B8D4F0"), alignment=TA_CENTER)

sSectionHead = S("sSectionHead",
    fontSize=13, fontName="Helvetica-Bold",
    textColor=WHITE, spaceBefore=10, spaceAfter=4,
    leftIndent=8, leading=17)

sSubHead = S("sSubHead",
    fontSize=10.5, fontName="Helvetica-Bold",
    textColor=C_NAVY, spaceBefore=6, spaceAfter=2)

sBody = S("sBody",
    fontSize=9.5, fontName="Helvetica",
    textColor=C_DGRAY, spaceAfter=3, leading=14)

sBullet = S("sBullet",
    fontSize=9.2, fontName="Helvetica",
    textColor=C_DGRAY, leftIndent=14, spaceAfter=2, leading=13,
    bulletIndent=6)

sBulletBold = S("sBulletBold",
    fontSize=9.2, fontName="Helvetica-Bold",
    textColor=C_NAVY, leftIndent=14, spaceAfter=2, leading=13,
    bulletIndent=6)

sNote = S("sNote",
    fontSize=8.5, fontName="Helvetica-Oblique",
    textColor=C_ORANGE, leftIndent=8, spaceAfter=3)

sTableHead = S("sTableHead",
    fontSize=9, fontName="Helvetica-Bold",
    textColor=WHITE, alignment=TA_CENTER)
sTableCell = S("sTableCell",
    fontSize=8.5, fontName="Helvetica",
    textColor=C_DGRAY, alignment=TA_LEFT, leading=12)
sTableCellBold = S("sTableCellBold",
    fontSize=8.5, fontName="Helvetica-Bold",
    textColor=C_NAVY, alignment=TA_LEFT, leading=12)

sPageNum = S("sPageNum",
    fontSize=8, fontName="Helvetica",
    textColor=colors.HexColor("#888888"), alignment=TA_CENTER)

sFooter = S("sFooter",
    fontSize=7.5, fontName="Helvetica-Oblique",
    textColor=colors.HexColor("#999999"), alignment=TA_CENTER)

# ── Helper builders ───────────────────────────────────────────────────────────
W = A4[0] - 3*cm   # usable width

def section_banner(text, bg_color, icon=""):
    """Coloured banner for a section heading."""
    data = [[Paragraph(f"{icon}  {text}" if icon else text, sSectionHead)]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), bg_color),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 10),
        ("ROUNDEDCORNERS", [4]),
    ]))
    return t

def info_box(text, bg=C_LYELLOW, border=C_YELLOW):
    data = [[Paragraph(text, S("infotext", fontSize=9, fontName="Helvetica",
                               textColor=C_YELLOW, leading=13))]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0), (-1,-1), bg),
        ("BOX",          (0,0), (-1,-1), 1, border),
        ("TOPPADDING",   (0,0), (-1,-1), 7),
        ("BOTTOMPADDING",(0,0), (-1,-1), 7),
        ("LEFTPADDING",  (0,0), (-1,-1), 10),
    ]))
    return t

def two_col_table(rows, header=None, h_bg=C_BLUE):
    """Generic 2-column table."""
    col1 = W * 0.38
    col2 = W * 0.62
    data = []
    if header:
        data.append([Paragraph(header[0], sTableHead),
                     Paragraph(header[1], sTableHead)])
    for r in rows:
        data.append([Paragraph(r[0], sTableCellBold),
                     Paragraph(r[1], sTableCell)])
    t = Table(data, colWidths=[col1, col2])
    style = [
        ("GRID",         (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
        ("ROWBACKGROUNDS",(0, 1 if header else 0), (-1,-1),
            [WHITE, C_LGRAY]),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
        ("LEFTPADDING",  (0,0), (-1,-1), 7),
    ]
    if header:
        style += [
            ("BACKGROUND",   (0,0), (-1,0), h_bg),
            ("FONTNAME",     (0,0), (-1,0), "Helvetica-Bold"),
            ("FONTSIZE",     (0,0), (-1,0), 9),
        ]
    t.setStyle(TableStyle(style))
    return t

def three_col_table(rows, header=None, h_bg=C_PURPLE, colW=None):
    if colW is None:
        colW = [W*0.28, W*0.28, W*0.44]
    data = []
    if header:
        data.append([Paragraph(h, sTableHead) for h in header])
    for r in rows:
        data.append([Paragraph(str(c), sTableCell) for c in r])
    t = Table(data, colWidths=colW)
    style = [
        ("GRID",         (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
        ("ROWBACKGROUNDS",(0, 1 if header else 0), (-1,-1), [WHITE, C_LGRAY]),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
        ("LEFTPADDING",  (0,0), (-1,-1), 7),
    ]
    if header:
        style += [("BACKGROUND", (0,0), (-1,0), h_bg)]
    t.setStyle(TableStyle(style))
    return t

def bullet(text, bold_prefix=None):
    if bold_prefix:
        return Paragraph(f"<b>{bold_prefix}</b> {text}", sBullet)
    return Paragraph(f"β€’ {text}", sBullet)

def sp(n=6):
    return Spacer(1, n)

# ═══════════════════════════════════════════════════════════════════════════════
# BUILD DOCUMENT
# ═══════════════════════════════════════════════════════════════════════════════
doc = SimpleDocTemplate(
    OUTPUT, pagesize=A4,
    leftMargin=1.5*cm, rightMargin=1.5*cm,
    topMargin=1.8*cm, bottomMargin=1.8*cm,
    title="Pelvis Anatomy Quick Revision",
    author="Orris Medical"
)

story = []

# ─── COVER BANNER ────────────────────────────────────────────────────────────
cover_data = [[
    Paragraph("PELVIS ANATOMY", sTitle),
    Paragraph("Quick Revision Guide", sSubtitle),
    Paragraph("Based on Gray's Anatomy for Students  |  Chapter 5: Pelvis & Perineum", sSource),
]]
cover = Table(cover_data, colWidths=[W])
cover.setStyle(TableStyle([
    ("BACKGROUND",   (0,0), (-1,-1), C_NAVY),
    ("TOPPADDING",   (0,0), (-1,-1), 18),
    ("BOTTOMPADDING",(0,0), (-1,-1), 18),
    ("LEFTPADDING",  (0,0), (-1,-1), 14),
    ("ROUNDEDCORNERS", [6]),
]))
story.append(cover)
story.append(sp(14))

# ─── TOPIC INDEX ─────────────────────────────────────────────────────────────
index_data = [
    [Paragraph("TOPIC INDEX", S("idx_h", fontSize=10, fontName="Helvetica-Bold", textColor=WHITE, alignment=TA_CENTER))],
    [Paragraph(
        "1. Bony Pelvis &amp; Landmarks   β€’   2. Joints &amp; Ligaments   β€’   3. Pelvic Walls &amp; Floor   "
        "β€’   4. Pelvic Viscera   β€’   5. Peritoneum &amp; Fascia   β€’   6. Blood Vessels   "
        "β€’   7. Nerves   β€’   8. Perineum   β€’   9. Male vs Female   β€’   10. Clinical High-Yields",
        S("idx_b", fontSize=9, fontName="Helvetica", textColor=WHITE, alignment=TA_CENTER, leading=14)
    )],
]
idx_t = Table(index_data, colWidths=[W])
idx_t.setStyle(TableStyle([
    ("BACKGROUND",   (0,0), (-1,-1), C_BLUE),
    ("TOPPADDING",   (0,0), (-1,-1), 6),
    ("BOTTOMPADDING",(0,0), (-1,-1), 8),
    ("LEFTPADDING",  (0,0), (-1,-1), 12),
    ("ROUNDEDCORNERS", [4]),
]))
story.append(idx_t)
story.append(sp(14))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 1 – BONY PELVIS
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("1. BONY PELVIS & LANDMARKS", C_NAVY, "🦴"))
story.append(sp(6))

story.append(Paragraph("The pelvis is a ring-shaped bony structure at the base of the trunk, "
    "connecting the spine to the lower limbs. It consists of the <b>two hip bones</b>, "
    "the <b>sacrum</b>, and the <b>coccyx</b>.", sBody))
story.append(sp(6))

story.append(Paragraph("Hip Bone (Os Coxae) – 3 Fused Bones", sSubHead))
bone_rows = [
    ("ILIUM", "Blade-shaped, superior part"),
    ("ISCHIUM", "Inferior-posterior part"),
    ("PUBIS", "Inferior-anterior part"),
    ("Fusion point", "Acetabulum – fuse at age 16–18"),
]
story.append(two_col_table(bone_rows, header=["BONE", "KEY FACT"], h_bg=C_NAVY))
story.append(sp(8))

story.append(Paragraph("Key Bony Landmarks", sSubHead))
landmark_rows = [
    ("Iliac crest",        "Superior border of ilium; L4 vertebral level landmark"),
    ("ASIS",               "Anterior Superior Iliac Spine – inguinal ligament & sartorius attachment"),
    ("AIIS",               "Anterior Inferior Iliac Spine – rectus femoris origin"),
    ("PSIS",               "Posterior Superior Iliac Spine – dimple of Venus; S2 level"),
    ("Ischial spine",      "Attachment of sacrospinous lig; pudendal nerve landmark"),
    ("Ischial tuberosity", "'Sitting bone' – hamstring origin; lateral corner of perineum"),
    ("Pubic tubercle",     "Inguinal ligament medial end"),
    ("Pubic symphysis",    "Secondary cartilaginous joint in midline"),
    ("Obturator foramen",  "Largest foramen in skeleton; mostly covered by obturator membrane"),
    ("Sacral promontory",  "Anterior projection of S1; obstetric landmark"),
    ("Acetabulum",         "Hip socket; formed by all 3 bones; faces laterally"),
]
story.append(two_col_table(landmark_rows, header=["LANDMARK", "SIGNIFICANCE"], h_bg=C_BLUE))
story.append(sp(8))

story.append(Paragraph("Greater vs Lesser Pelvis", sSubHead))
gl_rows = [
    ("Greater (False) Pelvis",
     "Superior to pelvic inlet; supports lower abdominal organs; bounded by iliac fossae"),
    ("Lesser (True) Pelvis",
     "Inferior to pelvic inlet; contains pelvic organs; bounded by pelvic inlet above, pelvic outlet below"),
    ("Pelvic Inlet (Brim)",
     "Linea terminalis = pubic crest + pectineal line + arcuate line + sacral ala + sacral promontory"),
    ("Pelvic Outlet",
     "Pubic symphysis β†’ ischiopubic rami β†’ ischial tuberosities β†’ sacrotuberous ligament β†’ coccyx"),
]
story.append(two_col_table(gl_rows, h_bg=C_GREEN))
story.append(sp(8))

story.append(Paragraph("Pelvic Diameters (Clinically Important)", sSubHead))
diam_rows = [
    ["Diameter", "Measurement", "Clinical Importance"],
    ["Transverse (inlet)", "~13 cm", "Widest diameter of inlet"],
    ["Obstetric conjugate", "~11 cm", "Smallest AP diameter; key for delivery"],
    ["Anatomical conjugate", "~11–12 cm", "Sacral promontory β†’ pubic symphysis upper border"],
    ["Diagonal conjugate", "~12.5 cm", "Only one measurable clinically on exam"],
    ["Bi-ischial (outlet)", "~11 cm", "Between ischial tuberosities"],
]
diam_t = Table(diam_rows, colWidths=[W*0.32, W*0.22, W*0.46])
diam_t.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), C_ORANGE),
    ("FONTNAME",   (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",   (0,0), (-1,-1), 8.5),
    ("GRID",       (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 7),
    ("TEXTCOLOR",  (0,0), (-1,0), WHITE),
    ("ALIGN",      (0,0), (-1,-1), "LEFT"),
]))
story.append(diam_t)
story.append(sp(4))
story.append(info_box("⚠ MEMORY AID: Obstetric conjugate = Anatomical conjugate βˆ’ 1.5 cm (subtract the posterior pubic thickness)"))
story.append(sp(12))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 2 – JOINTS & LIGAMENTS
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("2. JOINTS & LIGAMENTS", C_GREEN, "πŸ”—"))
story.append(sp(6))

jl_rows = [
    ("Sacroiliac joint",       "Synovial (ant.) + fibrous (post.); transmits body weight; very strong; little movement"),
    ("Pubic symphysis",        "Secondary cartilaginous; fibrocartilage disc; fuses in males; widens in pregnancy"),
    ("Lumbosacral joint",      "L5–S1 disc + zygapophyseal joints; lumbosacral trunk passes here"),
    ("Sacrospinous ligament",  "Sacrum β†’ ischial spine; converts greater sciatic notch into GREATER sciatic foramen"),
    ("Sacrotuberous ligament", "Sacrum β†’ ischial tuberosity; converts lesser sciatic notch into LESSER sciatic foramen"),
]
story.append(two_col_table(jl_rows, header=["JOINT / LIGAMENT", "KEY POINTS"], h_bg=C_GREEN))
story.append(sp(4))
story.append(info_box("⚠ CLINICAL: Sacrospinous & sacrotuberous ligaments resist forward rotation of the sacrum (nutation). They are often injured in pelvic fractures."))
story.append(sp(12))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 3 – PELVIC WALLS & FLOOR
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("3. PELVIC WALLS & FLOOR", C_ORANGE, "πŸ’ͺ"))
story.append(sp(6))

story.append(Paragraph("Pelvic Wall Muscles", sSubHead))
wall_rows = [
    ["Muscle", "Origin", "Insertion", "Nerve", "Action"],
    ["Obturator internus", "Inner surface obturator membrane", "Greater trochanter (medial)", "Nerve to OI (L5–S2)", "Lateral rotator of thigh; pelvic side wall"],
    ["Piriformis", "Anterior surface S2–S4", "Greater trochanter (superior)", "S1–S2 branches", "Lateral rotator/abductor of thigh; exits via greater sciatic foramen"],
]
wt = Table(wall_rows, colWidths=[W*0.17, W*0.22, W*0.20, W*0.18, W*0.23])
wt.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), C_ORANGE),
    ("TEXTCOLOR",  (0,0), (-1,0), WHITE),
    ("FONTNAME",   (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",   (0,0), (-1,-1), 8),
    ("GRID",       (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("ALIGN",      (0,0), (-1,-1), "LEFT"),
    ("VALIGN",     (0,0), (-1,-1), "TOP"),
]))
story.append(wt)
story.append(sp(8))

story.append(Paragraph("Pelvic Floor (Pelvic Diaphragm)", sSubHead))
story.append(Paragraph("Formed by the <b>levator ani</b> + <b>coccygeus</b>. Funnel-shaped muscular sheet suspending pelvic organs.", sBody))
story.append(sp(4))

floor_rows = [
    ["Muscle", "Parts", "Nerve", "Key Function"],
    ["Levator ani",
     "Pubococcygeus (medial)\nIliococcygeus (lateral)\nPuborectalis (innermost sling)",
     "Nerve to levator ani (S3–S4) + perineal branch of S4",
     "Supports pelvic floor; maintains continence; anorectal angle (puborectalis)"],
    ["Coccygeus (ischiococcygeus)",
     "Single muscle",
     "S4–S5",
     "Supports pelvic floor; flexes coccyx; forms posterior pelvic floor"],
]
ft = Table(floor_rows, colWidths=[W*0.18, W*0.28, W*0.26, W*0.28])
ft.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), C_ORANGE),
    ("TEXTCOLOR",  (0,0), (-1,0), WHITE),
    ("FONTNAME",   (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",   (0,0), (-1,-1), 8),
    ("GRID",       (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("ALIGN",      (0,0), (-1,-1), "LEFT"),
    ("VALIGN",     (0,0), (-1,-1), "TOP"),
]))
story.append(ft)
story.append(sp(4))
story.append(info_box("🧠 Puborectalis creates the anorectal angle (~90Β°) – loss of this sling β†’ fecal incontinence. Weakness of levator ani β†’ pelvic organ prolapse."))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 4 – PELVIC VISCERA
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("4. PELVIC VISCERA (ORGANS)", C_RED, "πŸ«€"))
story.append(sp(6))

story.append(Paragraph("Urinary Bladder", sSubHead))
story.append(two_col_table([
    ("Position",        "Retropubic; rises into abdomen when full"),
    ("Wall",            "Detrusor muscle (smooth muscle, 3 layers)"),
    ("Trigone",         "Smooth triangular area (2 ureteric orifices + internal urethral orifice)"),
    ("Internal urethral sphincter", "Smooth muscle; involuntary; sympathetic control"),
    ("Relations",       "Anteriorly: pubic symphysis. Posteriorly: rectum (M) / uterus (F). Superiorly: peritoneum"),
], h_bg=C_RED))
story.append(sp(6))

story.append(Paragraph("Ureters in the Pelvis", sSubHead))
story.append(two_col_table([
    ("Entry",     "Cross pelvic brim at bifurcation of common iliac artery (at SI joint)"),
    ("Course",    "Runs along lateral pelvic wall β†’ hooks anteriorly above levator ani β†’ enters bladder at trigone"),
    ("Key relation (F)", "Crossed SUPERIORLY by uterine artery ('water under the bridge') – risk in hysterectomy"),
    ("Key relation (M)", "Crossed by ductus deferens (duck deferens dives under)"),
], h_bg=C_RED))
story.append(sp(6))

story.append(Paragraph("Rectum & Anal Canal", sSubHead))
story.append(two_col_table([
    ("Rectum",              "Follows sacral curve; no taeniae, appendices epiploicae or haustrations"),
    ("Rectal ampulla",      "Dilated inferior part; reservoir for feces"),
    ("Anorectal junction",  "Marked by puborectalis sling; 90Β° anorectal angle"),
    ("Anal canal",          "4 cm long; internal sphincter (smooth/involuntary) + external sphincter (skeletal/voluntary)"),
    ("Dentate line",        "Junction of endoderm/ectoderm; above = visceral (no pain); below = somatic (pain)"),
    ("Haemorrhoidal plexus","Above dentate = internal haemorrhoids; below = external haemorrhoids (painful)"),
], h_bg=C_RED))
story.append(sp(6))

story.append(Paragraph("Female Reproductive Organs", sSubHead))
story.append(two_col_table([
    ("Uterus",       "Anteverted (forward on vagina) + anteflexed (fundus forward on cervix); layers: endometrium, myometrium, perimetrium"),
    ("Uterine tubes","Intramural β†’ Isthmus β†’ Ampulla (common fertilisation site) β†’ Infundibulum β†’ Fimbriae"),
    ("Ovaries",      "Intraperitoneal; attached by mesovarium; supplied by ovarian artery (from aorta at L2)"),
    ("Vagina",       "Fibromuscular tube; anterior fornix shortest; posterior fornix adjacent to rectouterine pouch"),
    ("Cervix",       "Lower uterine segment; external os visible on speculum exam"),
    ("Broad ligament","Double peritoneal fold enclosing uterine tubes, ovaries, round ligament"),
    ("Round ligament","From uterine fundus β†’ inguinal canal β†’ labia majora (remnant of gubernaculum)"),
    ("Uterosacral lig","Holds uterus in anteversion; key support; pelvic pain if stretched"),
    ("Cardinal lig",  "Strongest support; from cervix/vagina β†’ lateral pelvic wall; damaged in prolapse"),
], h_bg=C_RED))
story.append(sp(6))

story.append(Paragraph("Male Reproductive Organs", sSubHead))
story.append(two_col_table([
    ("Prostate",        "Walnut-sized; surrounds prostatic urethra; zones: peripheral (cancer), transitional (BPH), central; assessed by DRE"),
    ("Seminal vesicles","Posterior to bladder; secrete fructose (sperm energy), prostaglandins; NOT sperm storage"),
    ("Ductus deferens", "Carries sperm from epididymis; enters pelvis at deep inguinal ring; ampulla before joining seminal vesicle"),
    ("Ejaculatory duct","Ductus deferens + seminal vesicle duct; opens into prostatic urethra at verumontanum"),
    ("Urethra (M)",     "Prostatic (4cm) β†’ membranous (1.5cm, narrowest) β†’ spongy/penile (15cm)"),
], h_bg=C_RED))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 5 – PERITONEUM & FASCIA
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("5. PERITONEUM & FASCIAL SPACES", C_TEAL, "πŸ“‹"))
story.append(sp(6))

pf_rows = [
    ("Vesicouterine pouch",      "Between bladder & uterus (female); obliterated when uterus anteverted"),
    ("Rectouterine pouch (of Douglas)", "Between uterus & rectum (female); LOWEST point of peritoneum; blood/pus collects here; can be drained via posterior vaginal fornix"),
    ("Rectovesical pouch",       "Between bladder & rectum (male); lowest peritoneal recess in males"),
    ("Paravesical fossa",        "Lateral to bladder on each side"),
    ("Pararectal fossa",         "Lateral to rectum on each side"),
    ("Presacral (Waldeyer) space","Between rectum & sacrum; contains middle sacral vessels & lymph nodes"),
    ("Retropubic (Retzius) space","Between pubis & bladder; extraperitoneal; used for pelvic surgery access"),
    ("Pelvic fascia",            "Visceral fascia covers organs; parietal fascia lines walls; thickened as ligaments"),
]
story.append(two_col_table(pf_rows, header=["SPACE / LAYER", "KEY FACTS"], h_bg=C_TEAL))
story.append(sp(4))
story.append(info_box("⚠ CLINICAL: The rectouterine pouch is the most common site for pelvic abscess, endometriosis implants, and blood from ectopic pregnancy rupture."))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 6 – BLOOD VESSELS
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("6. BLOOD VESSELS OF THE PELVIS", C_PURPLE, "🩸"))
story.append(sp(6))

story.append(Paragraph("Internal Iliac Artery – Main Artery of the Pelvis", sSubHead))
story.append(Paragraph("Arises from common iliac artery at L5/S1 junction β†’ divides into <b>anterior</b> and <b>posterior trunks</b>.", sBody))
story.append(sp(5))

art_rows = [
    ["TRUNK", "BRANCH", "SUPPLY"],
    ["POSTERIOR", "Iliolumbar a.", "Posterior abdominal wall, psoas, iliacus"],
    ["POSTERIOR", "Lateral sacral a. (Γ—2)", "Sacral canal, skin/muscle over sacrum"],
    ["POSTERIOR", "Superior gluteal a. (largest)", "Gluteus medius, minimus, tensor fasciae latae"],
    ["ANTERIOR", "Umbilical a. β†’ Superior vesical a.", "Bladder (superior); umbilical ligament remnant"],
    ["ANTERIOR", "Obturator a.", "Medial thigh; passes through obturator canal"],
    ["ANTERIOR", "Inferior vesical a. (M)", "Bladder base, prostate, seminal vesicles, ureter"],
    ["ANTERIOR", "Uterine a. (F)", "Uterus, cervix, upper vagina; crosses ABOVE ureter"],
    ["ANTERIOR", "Vaginal a. (F)", "Vagina, bladder base"],
    ["ANTERIOR", "Middle rectal a.", "Rectum (anastomoses with sup & inf rectal aa.)"],
    ["ANTERIOR", "Internal pudendal a.", "Perineum, external genitalia, anal canal"],
    ["ANTERIOR", "Inferior gluteal a.", "Gluteus maximus, sciatic nerve, posterior thigh"],
]
at = Table(art_rows, colWidths=[W*0.18, W*0.35, W*0.47])
at.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), C_PURPLE),
    ("TEXTCOLOR",  (0,0), (-1,0), WHITE),
    ("FONTNAME",   (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",   (0,0), (-1,-1), 8),
    ("GRID",       (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("BACKGROUND", (0,1), (0,3), colors.HexColor("#EDE3F7")),
    ("BACKGROUND", (0,4), (0,12), colors.HexColor("#D6E8F7")),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("ALIGN",      (0,0), (-1,-1), "LEFT"),
]))
story.append(at)
story.append(sp(6))

story.append(Paragraph("Venous Drainage", sSubHead))
story.append(Paragraph(
    "Pelvic veins drain into the <b>internal iliac vein</b> β†’ common iliac vein β†’ inferior vena cava. "
    "Pelvic venous plexuses (vesical, prostatic, uterovaginal, rectal) communicate freely. "
    "The <b>ovarian vein</b> drains into the IVC on the right and the <b>left renal vein</b> on the left "
    "(clinically important – left-sided varicocele is more common).", sBody))
story.append(sp(8))

story.append(Paragraph("Lymphatic Drainage", sSubHead))
lym_rows = [
    ("Bladder / prostate / uterus (body)", "External iliac nodes"),
    ("Uterine cervix / vagina (upper)",    "Internal & external iliac nodes"),
    ("Rectum (upper)",                     "Inferior mesenteric nodes (paraortic)"),
    ("Rectum (lower) / anal canal above dentate", "Internal iliac nodes"),
    ("Anal canal below dentate line",      "Superficial inguinal nodes"),
    ("Ovary / testis",                     "Para-aortic nodes at L2 (gonadal origin)"),
]
story.append(two_col_table(lym_rows, header=["STRUCTURE", "PRIMARY LYMPH NODE DRAINAGE"], h_bg=C_PURPLE))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 7 – NERVES
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("7. NERVES OF THE PELVIS", C_BLUE, "🧠"))
story.append(sp(6))

story.append(Paragraph("Sacral Plexus (L4–S3) – Forms on Piriformis Muscle", sSubHead))
nerve_rows = [
    ["NERVE", "ROOT", "EXITS VIA", "SUPPLIES"],
    ["Sciatic nerve",            "L4–S3", "Greater sciatic foramen (below piriformis)", "Entire lower limb below knee"],
    ["Superior gluteal n.",      "L4–S1", "Greater sciatic foramen (ABOVE piriformis)", "Gluteus med/min, tensor fasciae latae"],
    ["Inferior gluteal n.",      "L5–S2", "Greater sciatic foramen (below piriformis)", "Gluteus maximus"],
    ["Pudendal nerve",           "S2–S4", "Greater sciatic β†’ around ischial spine β†’ lesser sciatic foramen β†’ pudendal canal", "ALL perineal structures"],
    ["Nerve to obturator internus", "L5–S2", "Greater sciatic β†’ lesser sciatic foramen", "Obturator internus, superior gemellus"],
    ["Nerve to quadratus femoris",  "L4–S1", "Greater sciatic foramen (deep)", "Quadratus femoris, inferior gemellus"],
    ["Posterior cutaneous n. thigh","S1–S3","Greater sciatic foramen (below piriformis)", "Skin of posterior thigh & perineum"],
    ["Pelvic splanchnic nn.",    "S2–S4", "Directly to pelvic plexus", "Parasympathetic to pelvic/perineal organs"],
    ["Perforating cutaneous n.", "S2–S3", "Through sacrotuberous ligament", "Skin over medial/inferior buttock"],
]
nt = Table(nerve_rows, colWidths=[W*0.22, W*0.11, W*0.34, W*0.33])
nt.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), C_BLUE),
    ("TEXTCOLOR",  (0,0), (-1,0), WHITE),
    ("FONTNAME",   (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",   (0,0), (-1,-1), 7.5),
    ("GRID",       (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("ALIGN",      (0,0), (-1,-1), "LEFT"),
    ("VALIGN",     (0,0), (-1,-1), "TOP"),
]))
story.append(nt)
story.append(sp(8))

story.append(Paragraph("Autonomic Nervous System of the Pelvis", sSubHead))
auto_rows = [
    ("Sympathetic (T10–L2)",
     "Via hypogastric nerve β†’ superior hypogastric plexus β†’ inferior hypogastric plexus. "
     "Controls: ejaculation, vasoconstriction, bladder neck closure, uterine contraction"),
    ("Parasympathetic (S2–S4)",
     "Pelvic splanchnic nerves (nervi erigentes) β†’ inferior hypogastric plexus. "
     "Controls: erection, bladder detrusor contraction (micturition), bowel peristalsis, vasodilation"),
    ("Inferior hypogastric plexus",
     "Main pelvic autonomic plexus on lateral walls; mixed sympathetic + parasympathetic; "
     "subdivides into vesical, uterovaginal (Frankenhauser), middle rectal, and prostatic plexuses"),
]
story.append(two_col_table(auto_rows, header=["DIVISION", "KEY POINTS"], h_bg=C_BLUE))
story.append(sp(4))
story.append(info_box("🧠 MEMORY: 'Point and Shoot' – Parasympathetic = Point (erection) | Sympathetic = Shoot (ejaculation)"))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 8 – PERINEUM
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("8. PERINEUM", C_TEAL, "πŸ”Ί"))
story.append(sp(6))

story.append(Paragraph(
    "Diamond-shaped region BELOW the pelvic floor. Boundaries: "
    "pubic symphysis (anterior), ischiopubic rami (anterolateral), ischial tuberosities (lateral), "
    "sacrotuberous ligaments (posterolateral), coccyx (posterior).", sBody))
story.append(sp(4))
story.append(Paragraph("Divided into 2 triangles by a line between the ischial tuberosities:", sBody))

story.append(sp(6))
story.append(Paragraph("A. Anal Triangle (Posterior)", sSubHead))
anal_rows = [
    ("Ischio-anal (ischiorectal) fossa", "Fat-filled wedge on each side of anal canal; allows distension; pathway for anal fistulae"),
    ("External anal sphincter",          "3 parts: subcutaneous, superficial, deep; pudendal nerve (S2–S4)"),
    ("Levator ani (roof)",               "Roof of ischio-anal fossa"),
    ("Anococcygeal body",                "Fibromuscular node between anus & coccyx"),
    ("Pudendal canal (Alcock's canal)",  "In lateral wall of fossa; contains internal pudendal vessels + pudendal nerve"),
]
story.append(two_col_table(anal_rows, h_bg=C_TEAL))
story.append(sp(6))

story.append(Paragraph("B. Urogenital Triangle (Anterior)", sSubHead))
story.append(Paragraph("Contains the <b>perineal membrane</b> (= inferior fascia of urogenital diaphragm) and 2 pouches:", sBody))
story.append(sp(4))

pouch_rows = [
    ["POUCH", "LOCATION", "MALE CONTENTS", "FEMALE CONTENTS"],
    ["Superficial perineal pouch",
     "Below perineal membrane (between membrane & Colles fascia)",
     "Crura of penis, bulb of penis, ischiocavernosus m., bulbospongiosus m., superficial transverse perineal m.",
     "Crura of clitoris, bulbs of vestibule, ischiocavernosus m., bulbospongiosus m., greater vestibular (Bartholin) glands"],
    ["Deep perineal pouch",
     "Above perineal membrane (enclosed within it)",
     "External urethral sphincter, deep transverse perineal m., bulbourethral (Cowper) glands",
     "External urethral sphincter, deep transverse perineal m., sphincter urethrovaginalis, compressor urethrae"],
]
pt = Table(pouch_rows, colWidths=[W*0.18, W*0.22, W*0.30, W*0.30])
pt.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), C_TEAL),
    ("TEXTCOLOR",  (0,0), (-1,0), WHITE),
    ("FONTNAME",   (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",   (0,0), (-1,-1), 7.5),
    ("GRID",       (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 5),
    ("ALIGN",      (0,0), (-1,-1), "LEFT"),
    ("VALIGN",     (0,0), (-1,-1), "TOP"),
]))
story.append(pt)
story.append(sp(4))
story.append(info_box("⚠ PERINEAL BODY: Central fibromuscular node where ALL perineal muscles converge. Torn during childbirth β†’ 'perineal tear'. Episiotomy cuts through it to prevent uncontrolled tearing."))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 9 – MALE vs FEMALE PELVIS
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("9. MALE vs FEMALE PELVIS", C_ORANGE, "⚧"))
story.append(sp(6))

mf_rows = [
    ["FEATURE", "MALE PELVIS", "FEMALE PELVIS"],
    ["Overall shape", "Heart/funnel shaped (android)", "Oval/cylindrical (gynecoid)"],
    ["Pelvic inlet", "Heart-shaped, narrow", "Oval/round, wider"],
    ["Pelvic outlet", "Smaller", "Larger"],
    ["Subpubic angle", "60–70Β° (acute, V-shape)", "80–90Β°+ (obtuse, U-shape)"],
    ["Sacrum", "Narrow, more curved, longer", "Wide, less curved, shorter"],
    ["Ischial spines", "More prominent, closer together", "Less prominent, wider apart"],
    ["Acetabulum", "Larger (broader)", "Smaller (relative)"],
    ["Greater sciatic notch", "Narrower (~60Β°)", "Wider (~90Β°)"],
    ["Obturator foramen", "Round", "Oval"],
    ["Pelvic brim", "Oblique, narrow", "Wider, more horizontal"],
    ["Overall build", "Heavier, rougher bone markings", "Lighter, smoother"],
]
mft = Table(mf_rows, colWidths=[W*0.28, W*0.36, W*0.36])
mft.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), C_ORANGE),
    ("TEXTCOLOR",  (0,0), (-1,0), WHITE),
    ("FONTNAME",   (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",   (0,0), (-1,-1), 8.5),
    ("GRID",       (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 7),
    ("ALIGN",      (0,0), (-1,-1), "LEFT"),
]))
story.append(mft)
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 10 – CLINICAL HIGH-YIELDS
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("10. CLINICAL HIGH-YIELDS & MNEMONICS", C_RED, "πŸ₯"))
story.append(sp(6))

clin_rows = [
    ["CLINICAL TOPIC", "ANATOMY BASIS", "KEY POINT"],
    ["Pudendal nerve block",
     "Pudendal nerve (S2–S4) wraps around ischial spine",
     "Inject lateral to ischial spine, medial approach via vagina; analgesia in childbirth"],
    ["Episiotomy",
     "Perineal body; bulbospongiosus & transverse perineal muscles",
     "Mediolateral cut (UK) or midline (US); repairs perineal body layers"],
    ["Ureteric injury in hysterectomy",
     "Ureter crosses under uterine artery 1–2 cm lateral to cervix",
     "'Water under the bridge' – ureter is the water, uterine artery the bridge"],
    ["Prostate cancer spread",
     "Peripheral zone (posterolateral) – palpable on DRE",
     "Spreads via para-aortic nodes; metastasises to lumbar spine via Batson's plexus"],
    ["BPH (Benign Prostatic Hypertrophy)",
     "Transitional zone surrounds urethra",
     "Compresses prostatic urethra β†’ urinary retention, frequency, nocturia"],
    ["Ectopic pregnancy",
     "Ampulla of uterine tube (most common site)",
     "Rupture β†’ blood fills rectouterine pouch; shoulder tip pain (diaphragm irritation)"],
    ["Uterine prolapse",
     "Weakness of cardinal & uterosacral ligaments + levator ani",
     "Multiparity, oestrogen loss; treated by pelvic floor repair or hysterectomy"],
    ["Pelvic fractures",
     "Ring fractures affect 2 points; unstable if posterior ring disrupted",
     "Risk injury to bladder, urethra, pudendal vessels, lumbosacral trunk"],
    ["Varicocele",
     "Left gonadal vein drains into left renal vein at 90Β°",
     "Left > right; 'bag of worms'; impairs spermatogenesis; right-sided β†’ rule out IVC obstruction"],
    ["Haemorrhoids",
     "Internal (above dentate line) vs External (below dentate line)",
     "Internal: painless bright red bleeding; External: painful; Somatic (pudendal) nerve below dentate"],
    ["Cystocele / rectocele",
     "Weakness of perineal membrane and anterior/posterior vaginal wall",
     "Anterior wall defect β†’ cystocele (bladder bulge); Posterior β†’ rectocele (rectum bulge)"],
    ["Sacroiliac pain",
     "SI joint; PSIS level; referred to buttock/posterior thigh",
     "Positive FABER test; common in pregnancy (relaxin hormone)"],
]
ct = Table(clin_rows, colWidths=[W*0.22, W*0.32, W*0.46])
ct.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), C_RED),
    ("TEXTCOLOR",  (0,0), (-1,0), WHITE),
    ("FONTNAME",   (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",   (0,0), (-1,-1), 7.5),
    ("GRID",       (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING", (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("ALIGN",      (0,0), (-1,-1), "LEFT"),
    ("VALIGN",     (0,0), (-1,-1), "TOP"),
]))
story.append(ct)
story.append(sp(10))

# ── MNEMONICS BOX ─────────────────────────────────────────────────────────────
story.append(section_banner("MNEMONICS & MEMORY AIDS", colors.HexColor("#4A235A")))
story.append(sp(6))
mnems = [
    ("<b>Sciatic foramen contents (Greater):</b>  'I Smuggle Illegal Peppers Over Gravel Paths' = "
     "Iliolumbar a., Superior gluteal a./n., Inferior gluteal a./n., Piriformis, "
     "Obturator internus n., sciatic nerve, Gluteal vessels, Pudendal n."),
    ("<b>Internal iliac anterior trunk:</b>  'I Urinate Very Often Under Intense Medical Pressure' = "
     "Inferior vesical, Uterine, Vaginal, Obturator, Umbilical, Internal pudendal, Middle rectal, "
     "Posterior of uterus (inf. gluteal)"),
    ("<b>Uterine artery over ureter:</b>  'Water (ureter) flows under the Bridge (uterine artery)'"),
    ("<b>Erection vs Ejaculation:</b>  'Point and Shoot' – Point = Parasympathetic (S2–S4) = erection; "
     "Shoot = Sympathetic (L1–L2) = ejaculation"),
    ("<b>Levator ani parts:</b>  'Pubo-Ilio-Pubo' = Pubococcygeus (medial), Iliococcygeus (lateral), Puborectalis (inner sling)"),
    ("<b>Dentate line:</b>  Above = no pain, visceral supply (anal columns); Below = pain, somatic supply (pudendal nerve)"),
    ("<b>Lymph drainage of testes/ovary:</b>  Drains to PARA-AORTIC nodes (not inguinal) because they descended from L2"),
]
for m in mnems:
    story.append(Paragraph(f"β€’ {m}", sBullet))
story.append(sp(6))

# ── FOOTER ────────────────────────────────────────────────────────────────────
story.append(HRFlowable(width=W, thickness=1, color=C_LGRAY))
story.append(sp(4))
story.append(Paragraph(
    "Pelvis Anatomy Quick Revision  |  Based on Gray's Anatomy for Students, Chapter 5  |  Generated by Orris Medical AI",
    sFooter))

# ── BUILD ─────────────────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    canvas.setFont("Helvetica", 8)
    canvas.setFillColor(colors.HexColor("#AAAAAA"))
    canvas.drawRightString(A4[0] - 1.5*cm, 1.0*cm, f"Page {doc.page}")
    canvas.drawString(1.5*cm, 1.0*cm, "Pelvis Anatomy Quick Revision")
    canvas.restoreState()

doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print("PDF generated:", OUTPUT)
Running Command

cd /home/daytona/workspace/pelvis-anatomy && python generate_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/pelvis-anatomy/Pelvis_Anatomy_Quick_Revision.pdf

Your PDF is ready! Download it here:

Pelvis Anatomy Quick Revision

PDF Document Β· PDF


What's inside the PDF (4 pages, color-coded):

SectionColorContents
1. Bony PelvisNavyHip bone parts, landmarks, pelvic diameters table, Greater vs Lesser pelvis
2. Joints & LigamentsGreenSacroiliac, pubic symphysis, sacrospinous, sacrotuberous
3. Pelvic Walls & FloorOrangeObturator internus, piriformis, levator ani (3 parts), coccygeus
4. Pelvic VisceraRedBladder, ureters, rectum, female organs, male organs with key relations
5. Peritoneum & FasciaTealAll peritoneal pouches, fascial spaces (including pouch of Douglas)
6. Blood VesselsPurpleFull internal iliac artery branch table (anterior + posterior trunk), lymphatics
7. NervesBlueSacral plexus table, autonomic NS (parasympathetic vs sympathetic)
8. PerineumTealAnal triangle, urogenital triangle, perineal pouches (male & female)
9. Male vs Female PelvisOrange12-point comparison table
10. Clinical High-YieldsRed12 clinical scenarios with anatomy basis
MnemonicsPurple7 memory aids including "water under the bridge", "point and shoot"

Make a pdf just like you did in pelvis with abdomen also

Running Command

mkdir -p /home/daytona/workspace/abdomen-anatomy && ls /home/daytona/workspace/

Writing File

~/abdomen-anatomy/generate_pdf.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT

OUTPUT = "/home/daytona/workspace/abdomen-anatomy/Abdomen_Anatomy_Quick_Revision.pdf"

# ── Colour palette ─────────────────────────────────────────────────────────
C_NAVY    = colors.HexColor("#1A3560")
C_BLUE    = colors.HexColor("#2C6FAC")
C_LBLUE   = colors.HexColor("#D6E8F7")
C_ORANGE  = colors.HexColor("#E07B39")
C_LORANGE = colors.HexColor("#FDE9D9")
C_GREEN   = colors.HexColor("#2E7D52")
C_LGREEN  = colors.HexColor("#D4EDDA")
C_PURPLE  = colors.HexColor("#5B3F8C")
C_LPURPLE = colors.HexColor("#EDE3F7")
C_RED     = colors.HexColor("#C0392B")
C_LRED    = colors.HexColor("#FAD7D3")
C_TEAL    = colors.HexColor("#117A8B")
C_LTEAL   = colors.HexColor("#D1ECF1")
C_DGRAY   = colors.HexColor("#343A40")
C_LGRAY   = colors.HexColor("#F4F5F7")
C_YELLOW  = colors.HexColor("#856404")
C_LYELLOW = colors.HexColor("#FFF3CD")
C_BROWN   = colors.HexColor("#6D4C1F")
C_LBROWN  = colors.HexColor("#F5E6D3")
WHITE     = colors.white

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

sTitle    = S("sTitle",    fontSize=26, fontName="Helvetica-Bold",  textColor=WHITE,  alignment=TA_CENTER, spaceAfter=4)
sSubtitle = S("sSubtitle", fontSize=13, fontName="Helvetica",       textColor=WHITE,  alignment=TA_CENTER, spaceAfter=2)
sSource   = S("sSource",   fontSize=9,  fontName="Helvetica-Oblique", textColor=colors.HexColor("#B8D4F0"), alignment=TA_CENTER)

sSectionHead = S("sSectionHead", fontSize=13, fontName="Helvetica-Bold", textColor=WHITE,
                 spaceBefore=10, spaceAfter=4, leftIndent=8, leading=17)
sSubHead     = S("sSubHead",     fontSize=10.5, fontName="Helvetica-Bold", textColor=C_NAVY,  spaceBefore=6, spaceAfter=2)
sBody        = S("sBody",        fontSize=9.5,  fontName="Helvetica",      textColor=C_DGRAY, spaceAfter=3, leading=14)
sBullet      = S("sBullet",      fontSize=9.2,  fontName="Helvetica",      textColor=C_DGRAY, leftIndent=14, spaceAfter=2, leading=13, bulletIndent=6)
sTableHead   = S("sTableHead",   fontSize=9,    fontName="Helvetica-Bold", textColor=WHITE,   alignment=TA_CENTER)
sTableCell   = S("sTableCell",   fontSize=8.5,  fontName="Helvetica",      textColor=C_DGRAY, alignment=TA_LEFT, leading=12)
sTableCellBold = S("sTableCellBold", fontSize=8.5, fontName="Helvetica-Bold", textColor=C_NAVY, alignment=TA_LEFT, leading=12)
sFooter      = S("sFooter",      fontSize=7.5,  fontName="Helvetica-Oblique", textColor=colors.HexColor("#999999"), alignment=TA_CENTER)

W = A4[0] - 3*cm

# ── Helpers ────────────────────────────────────────────────────────────────
def section_banner(text, bg_color, icon=""):
    label = f"{icon}  {text}" if icon else text
    data = [[Paragraph(label, sSectionHead)]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), bg_color),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 10),
    ]))
    return t

def info_box(text, bg=C_LYELLOW, border=C_YELLOW):
    data = [[Paragraph(text, S("ib", fontSize=9, fontName="Helvetica", textColor=C_YELLOW, leading=13))]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), bg),
        ("BOX",           (0,0), (-1,-1), 1, border),
        ("TOPPADDING",    (0,0), (-1,-1), 7),
        ("BOTTOMPADDING", (0,0), (-1,-1), 7),
        ("LEFTPADDING",   (0,0), (-1,-1), 10),
    ]))
    return t

def two_col(rows, header=None, h_bg=C_BLUE, w1=0.38):
    c1, c2 = W*w1, W*(1-w1)
    data = []
    if header:
        data.append([Paragraph(header[0], sTableHead), Paragraph(header[1], sTableHead)])
    for r in rows:
        data.append([Paragraph(r[0], sTableCellBold), Paragraph(r[1], sTableCell)])
    t = Table(data, colWidths=[c1, c2])
    style = [
        ("GRID",          (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
        ("ROWBACKGROUNDS",(0, 1 if header else 0), (-1,-1), [WHITE, C_LGRAY]),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 7),
        ("VALIGN",        (0,0), (-1,-1), "TOP"),
    ]
    if header:
        style += [("BACKGROUND", (0,0), (-1,0), h_bg)]
    t.setStyle(TableStyle(style))
    return t

def multi_col(rows, col_widths, header=None, h_bg=C_BLUE):
    data = []
    if header:
        data.append([Paragraph(h, sTableHead) for h in header])
    for r in rows:
        data.append([Paragraph(str(c), sTableCell) for c in r])
    t = Table(data, colWidths=col_widths)
    style = [
        ("GRID",          (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
        ("ROWBACKGROUNDS",(0, 1 if header else 0), (-1,-1), [WHITE, C_LGRAY]),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 6),
        ("VALIGN",        (0,0), (-1,-1), "TOP"),
        ("FONTSIZE",      (0,0), (-1,-1), 8),
        ("ALIGN",         (0,0), (-1,-1), "LEFT"),
    ]
    if header:
        style += [("BACKGROUND", (0,0), (-1,0), h_bg),
                  ("TEXTCOLOR",  (0,0), (-1,0), WHITE),
                  ("FONTNAME",   (0,0), (-1,0), "Helvetica-Bold")]
    t.setStyle(TableStyle(style))
    return t

def sp(n=6):
    return Spacer(1, n)

# ══════════════════════════════════════════════════════════════════════════════
# BUILD
# ══════════════════════════════════════════════════════════════════════════════
doc = SimpleDocTemplate(
    OUTPUT, pagesize=A4,
    leftMargin=1.5*cm, rightMargin=1.5*cm,
    topMargin=1.8*cm, bottomMargin=1.8*cm,
    title="Abdomen Anatomy Quick Revision",
    author="Orris Medical"
)
story = []

# ─── COVER ───────────────────────────────────────────────────────────────────
cover_data = [[
    Paragraph("ABDOMEN ANATOMY", sTitle),
    Paragraph("Quick Revision Guide", sSubtitle),
    Paragraph("Based on Gray's Anatomy for Students  |  Chapter 4: Abdomen", sSource),
]]
cover = Table(cover_data, colWidths=[W])
cover.setStyle(TableStyle([
    ("BACKGROUND",    (0,0), (-1,-1), C_NAVY),
    ("TOPPADDING",    (0,0), (-1,-1), 18),
    ("BOTTOMPADDING", (0,0), (-1,-1), 18),
    ("LEFTPADDING",   (0,0), (-1,-1), 14),
]))
story.append(cover)
story.append(sp(14))

# ─── INDEX ───────────────────────────────────────────────────────────────────
idx_data = [[
    Paragraph("TOPIC INDEX", S("ih", fontSize=10, fontName="Helvetica-Bold", textColor=WHITE, alignment=TA_CENTER)),
    Paragraph(
        "1. Regions &amp; Boundaries   β€’   2. Abdominal Wall   β€’   3. Peritoneum   "
        "β€’   4. GI Tract   β€’   5. Liver, Biliary &amp; Pancreas   β€’   6. Spleen &amp; Kidneys   "
        "β€’   7. Blood Vessels   β€’   8. Nerves   β€’   9. Posterior Wall   β€’   10. Clinical High-Yields",
        S("ib2", fontSize=9, fontName="Helvetica", textColor=WHITE, alignment=TA_CENTER, leading=14))
]]
idx_t = Table(idx_data, colWidths=[W])
idx_t.setStyle(TableStyle([
    ("BACKGROUND",    (0,0), (-1,-1), C_BLUE),
    ("TOPPADDING",    (0,0), (-1,-1), 6),
    ("BOTTOMPADDING", (0,0), (-1,-1), 8),
    ("LEFTPADDING",   (0,0), (-1,-1), 12),
]))
story.append(idx_t)
story.append(sp(14))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 1 – REGIONS & BOUNDARIES
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("1. REGIONS & BOUNDARIES OF THE ABDOMEN", C_NAVY, "πŸ“"))
story.append(sp(6))
story.append(Paragraph(
    "The abdomen is the region between the <b>thorax</b> (above) and the <b>pelvis</b> (below). "
    "It contains the digestive, urinary, and many endocrine organs.", sBody))
story.append(sp(5))

story.append(Paragraph("Boundaries", sSubHead))
story.append(two_col([
    ("Superior",    "Diaphragm – separates abdomen from thorax"),
    ("Inferior",    "Pelvic inlet (continues into pelvic cavity)"),
    ("Anterior",    "Abdominal wall muscles"),
    ("Posterior",   "Lumbar vertebrae L1–L5, posterior abdominal wall muscles"),
    ("Lateral",     "Lateral abdominal wall muscles"),
], h_bg=C_NAVY))
story.append(sp(8))

story.append(Paragraph("Nine Abdominal Regions", sSubHead))
story.append(Paragraph(
    "Formed by <b>2 vertical lines</b> (midclavicular) and <b>2 horizontal lines</b> "
    "(subcostal plane at L3, transtubercular plane at L5):", sBody))
story.append(sp(4))
nine_rows = [
    ["REGION", "LOCATION", "KEY ORGANS"],
    ["Right Hypochondriac",  "Upper right",   "Right lobe of liver, gallbladder, right kidney, hepatic flexure of colon"],
    ["Epigastric",           "Upper middle",  "Stomach, left lobe of liver, duodenum (D1-D2), head of pancreas, coeliac vessels"],
    ["Left Hypochondriac",   "Upper left",    "Spleen, stomach, tail of pancreas, left kidney, splenic flexure of colon"],
    ["Right Lumbar",         "Middle right",  "Ascending colon, right kidney, right ureter, part of duodenum"],
    ["Umbilical",            "Middle centre", "Transverse colon, jejunum/ileum, abdominal aorta, IVC"],
    ["Left Lumbar",          "Middle left",   "Descending colon, left kidney, left ureter, parts of small intestine"],
    ["Right Iliac (Inguinal)","Lower right",  "Cecum, appendix, right ovary/tube, right ureter, iliopsoas"],
    ["Hypogastric (Pubic)",  "Lower middle",  "Bladder (when full), uterus, sigmoid colon, rectum, small intestine"],
    ["Left Iliac (Inguinal)","Lower left",    "Sigmoid colon, left ovary/tube, left ureter"],
]
story.append(multi_col(nine_rows, [W*0.22, W*0.15, W*0.63], header=nine_rows[0], h_bg=C_BLUE))
story.append(sp(8))

story.append(Paragraph("Four Quadrant Division (Clinical Use)", sSubHead))
quad_rows = [
    ["QUADRANT", "ABBREVIATION", "KEY CONTENTS"],
    ["Right Upper Quadrant", "RUQ", "Liver (right lobe), gallbladder, right kidney, duodenum, pancreas head, hepatic flexure"],
    ["Left Upper Quadrant",  "LUQ", "Stomach, spleen, left kidney, pancreas body/tail, splenic flexure, left lobe of liver"],
    ["Right Lower Quadrant", "RLQ", "Cecum, appendix, right ovary & tube, right ureter, iliopsoas"],
    ["Left Lower Quadrant",  "LLQ", "Sigmoid colon, left ovary & tube, left ureter, descending colon"],
]
story.append(multi_col(quad_rows, [W*0.30, W*0.14, W*0.56], header=quad_rows[0], h_bg=C_ORANGE))
story.append(sp(4))
story.append(info_box("⚠ CLINICAL: RLQ pain = appendicitis (McBurney's point: 1/3 of the way from ASIS to umbilicus). RUQ pain = liver/gallbladder. LUQ pain = spleen/stomach. Epigastric = peptic ulcer/pancreatitis."))
story.append(sp(12))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 2 – ABDOMINAL WALL
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("2. ABDOMINAL WALL", C_GREEN, "πŸ—"))
story.append(sp(6))

story.append(Paragraph("Layers of the Anterior Abdominal Wall (Skin β†’ Peritoneum)", sSubHead))
layers_rows = [
    ("1. Skin", "With Langer's lines (horizontal in lower abdomen)"),
    ("2. Subcutaneous fat (Camper's fascia)", "Superficial fatty layer; continuous with general subcutaneous fat"),
    ("3. Scarpa's fascia", "Deep membranous layer; fuses with fascia lata below inguinal ligament; important in extravasation injuries"),
    ("4. External oblique muscle", "Fibres run inferomedially ('hands-in-pocket'); forms inguinal ligament"),
    ("5. Internal oblique muscle", "Fibres run superomedially at right angles to external oblique"),
    ("6. Transversus abdominis", "Fibres run horizontally; main wall-tension muscle"),
    ("7. Transversalis fascia", "Deep fascia lining abdominal cavity; deep inguinal ring is a defect here"),
    ("8. Extraperitoneal fat", "Variable layer between transversalis fascia & peritoneum"),
    ("9. Parietal peritoneum", "Innermost layer; somatic innervation β†’ sharp localised pain"),
]
story.append(two_col(layers_rows, header=["LAYER", "KEY NOTES"], h_bg=C_GREEN, w1=0.35))
story.append(sp(8))

story.append(Paragraph("Rectus Sheath", sSubHead))
rs_rows = [
    ("Contents",          "Rectus abdominis muscle, pyramidalis muscle, superior & inferior epigastric vessels, terminal branches of lower 6 intercostal nerves"),
    ("Above arcuate line","Anterior: external oblique aponeurosis + anterior leaf of internal oblique. Posterior: posterior leaf of internal oblique + transversus abdominis aponeurosis"),
    ("Below arcuate line (Douglas)","All aponeuroses pass ANTERIOR to rectus. Posterior wall = transversalis fascia only β†’ weak point"),
    ("Arcuate line",      "Halfway between umbilicus and pubis; where posterior rectus sheath ends"),
    ("Linea alba",        "Midline fusion of all 3 aponeuroses; avascular; used for midline laparotomy incisions"),
    ("Linea semilunaris", "Lateral border of rectus abdominis; curved line visible on lean individuals"),
]
story.append(two_col(rs_rows, header=["STRUCTURE", "DETAILS"], h_bg=C_GREEN))
story.append(sp(8))

story.append(Paragraph("Abdominal Wall Muscles – Summary Table", sSubHead))
muscle_rows = [
    ["MUSCLE", "ORIGIN", "INSERTION", "NERVE", "ACTION"],
    ["External oblique",   "Ribs 5–12 (outer surface)",   "Iliac crest, inguinal lig, linea alba (aponeurosis)",  "T7–T12",  "Compress abdomen; lateral flexion & rotation (opposite side)"],
    ["Internal oblique",   "Thoracolumbar fascia, iliac crest, inguinal lig", "Ribs 10–12, linea alba, pubic crest", "T7–T12, L1", "Compress abdomen; lateral flexion & rotation (same side)"],
    ["Transversus abdominis","Thoracolumbar fascia, iliac crest, lower 6 costal cartilages", "Linea alba, pubic crest", "T7–T12, L1", "Compresses abdomen; increases intra-abdominal pressure"],
    ["Rectus abdominis",   "Pubic crest & symphysis",     "Xiphoid process, costal cartilages 5–7", "T6–T12",  "Flexes trunk; compresses abdomen; depresses ribs"],
    ["Pyramidalis",        "Pubic body",                  "Linea alba",   "T12",     "Tenses linea alba; often absent"],
]
mt = Table(muscle_rows, colWidths=[W*0.17, W*0.20, W*0.22, W*0.12, W*0.29])
mt.setStyle(TableStyle([
    ("BACKGROUND",    (0,0), (-1,0), C_GREEN),
    ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
    ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",      (0,0), (-1,-1), 7.5),
    ("GRID",          (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS",(0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING",    (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING",   (0,0), (-1,-1), 5),
    ("ALIGN",         (0,0), (-1,-1), "LEFT"),
    ("VALIGN",        (0,0), (-1,-1), "TOP"),
]))
story.append(mt)
story.append(sp(8))

story.append(Paragraph("Inguinal Canal", sSubHead))
ing_rows = [
    ("Boundaries",    "4 cm long canal above inguinal ligament; runs from deep β†’ superficial inguinal ring"),
    ("Anterior wall", "External oblique aponeurosis (+ internal oblique laterally)"),
    ("Posterior wall","Transversalis fascia (+ conjoint tendon medially)"),
    ("Roof",          "Arching fibres of internal oblique + transversus abdominis"),
    ("Floor",         "Inguinal ligament + lacunar ligament medially"),
    ("Deep inguinal ring", "Lateral to inferior epigastric vessels; defect in transversalis fascia"),
    ("Superficial inguinal ring", "Medial to inferior epigastric vessels; triangular defect in external oblique aponeurosis"),
    ("Male contents", "Spermatic cord: ductus deferens, testicular artery, pampiniform plexus, lymphatics, genital branch of genitofemoral nerve, ilioinguinal nerve (lies on top, not in cord)"),
    ("Female contents","Round ligament of uterus; ilioinguinal nerve"),
    ("Hesselbach's triangle", "Medial boundary: lateral border of rectus. Lateral: inferior epigastric artery. Inferior: inguinal ligament. Site of DIRECT inguinal hernia"),
]
story.append(two_col(ing_rows, header=["FEATURE", "DETAIL"], h_bg=C_GREEN))
story.append(sp(4))
story.append(info_box("⚠ HERNIA TIP: Direct hernia passes MEDIAL to inferior epigastric artery (through Hesselbach's triangle). Indirect hernia passes LATERAL to inferior epigastric artery (through deep inguinal ring β†’ inguinal canal β†’ superficial ring)."))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 3 – PERITONEUM
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("3. PERITONEUM", C_TEAL, "πŸ“‹"))
story.append(sp(6))

story.append(Paragraph(
    "The peritoneum is the largest serous membrane in the body. "
    "<b>Parietal peritoneum</b> lines the abdominal wall (somatic nerve supply β†’ localised pain). "
    "<b>Visceral peritoneum</b> covers organs (autonomic supply β†’ diffuse, poorly localised pain).", sBody))
story.append(sp(5))

story.append(Paragraph("Peritoneal Relations of Organs", sSubHead))
prel_rows = [
    ("INTRAPERITONEAL (covered all around, have mesentery)",
     "Stomach, small intestine (jejunum, ileum), cecum, appendix, transverse colon, sigmoid colon, spleen, liver, gallbladder, ovaries"),
    ("RETROPERITONEAL – PRIMARY (never had peritoneum)",
     "Kidneys, adrenal glands, aorta, IVC, ureter, oesophagus (thoracic)"),
    ("RETROPERITONEAL – SECONDARY (lost peritoneum during development – SADP)",
     "Duodenum (D2–D4), ascending colon, descending colon, pancreas (head/body/tail), rectum"),
]
story.append(two_col(prel_rows, header=["PERITONEAL STATUS", "STRUCTURES"], h_bg=C_TEAL, w1=0.32))
story.append(sp(4))
story.append(info_box("🧠 MNEMONIC for 2Β° retroperitoneal: 'SAD PUCKER' = Suprarenal glands, Aorta/IVC, Duodenum (D2–D4), Pancreas, Ureters, Colon (ascending & descending), Kidneys, Esophagus, Rectum"))
story.append(sp(8))

story.append(Paragraph("Key Peritoneal Structures", sSubHead))
pstr_rows = [
    ("Greater omentum",      "Double fold of peritoneum hanging from greater curvature of stomach; 'policeman of abdomen' – walls off infection; apron-like"),
    ("Lesser omentum",       "From lesser curvature of stomach + duodenum to liver; contains hepatoduodenal ligament (portal triad in free edge)"),
    ("Hepatoduodenal lig",   "Free edge of lesser omentum; contains portal vein (posterior), hepatic artery proper (left), common bile duct (right) – 'The Portal Triad'"),
    ("Mesentery (of small bowel)", "Fan-shaped peritoneal fold; root 15 cm long (L2 β†’ right iliac fossa); contains SMA, SMV, lymphatics, autonomic nerves"),
    ("Transverse mesocolon", "Attaches transverse colon to posterior wall; contains middle colic vessels"),
    ("Sigmoid mesocolon",    "Inverted V-shape; left ureter crosses at apex"),
    ("Epiploic foramen (of Winslow)", "Opening between greater & lesser sacs; bounded by: hepatoduodenal lig (anterior), IVC (posterior), caudate lobe (superior), D1 (inferior); can be compressed in Pringle manoeuvre"),
    ("Lesser sac (omental bursa)", "Posterior to stomach; communicates with greater sac via epiploic foramen; fluid from perforated posterior gastric ulcer collects here"),
    ("Falciform ligament",   "Liver β†’ anterior abdominal wall; contains ligamentum teres (remnant of left umbilical vein)"),
    ("Coronary ligament",    "Bare area of liver – where liver is not covered by peritoneum"),
]
story.append(two_col(pstr_rows, header=["STRUCTURE", "KEY FACTS"], h_bg=C_TEAL))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 4 – GI TRACT
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("4. GASTROINTESTINAL TRACT", C_ORANGE, "🫁"))
story.append(sp(6))

story.append(Paragraph("Stomach", sSubHead))
story.append(two_col([
    ("Parts",     "Cardia, fundus, body, pylorus (antrum β†’ canal β†’ sphincter)"),
    ("Curvatures","Lesser curvature (right, shorter); Greater curvature (left, longer)"),
    ("Blood supply","Lesser curvature: L & R gastric aa. Greater curvature: L & R gastroepiploic aa. Fundus: short gastric aa. (from splenic a.)"),
    ("Nerve supply","Vagus (CN X) via anterior & posterior gastric nerves; sympathetic via coeliac plexus"),
    ("Relations", "Anterior: liver, diaphragm, anterior wall. Posterior: omental bursa, pancreas, left kidney/adrenal, spleen, aorta"),
    ("Pyloric sphincter", "At L1 transpyloric plane; smooth muscle; pyloric stenosis in neonates (palpable 'olive')"),
], h_bg=C_ORANGE))
story.append(sp(6))

story.append(Paragraph("Duodenum (C-shaped, mostly retroperitoneal)", sSubHead))
duo_rows = [
    ["PART", "LENGTH", "RELATIONS / KEY STRUCTURES"],
    ["D1 (Superior)",      "5 cm",   "Mobile (cap); intraperitoneal. Gallstones may perforate here. Duodenal ulcers most common here (posterior = GDA erosion β†’ haemorrhage)"],
    ["D2 (Descending)",    "8 cm",   "Retroperitoneal. Bile duct + pancreatic duct open at major duodenal papilla (ampulla of Vater). Head of pancreas medially."],
    ["D3 (Horizontal)",    "10 cm",  "Retroperitoneal. Crossed anteriorly by SMA & SMV β†’ superior mesenteric artery syndrome if vessels compress it."],
    ["D4 (Ascending)",     "2.5 cm", "Retroperitoneal β†’ intraperitoneal at duodenojejunal flexure (DJ flexure) at L2, held by ligament of Treitz (suspensory muscle of duodenum)"],
]
story.append(multi_col(duo_rows, [W*0.13, W*0.10, W*0.77], header=duo_rows[0], h_bg=C_ORANGE))
story.append(sp(6))

story.append(Paragraph("Small Intestine (Jejunum & Ileum)", sSubHead))
story.append(two_col([
    ("Total length",          "~6 m; jejunum = proximal 2/5 (~2.4 m), ileum = distal 3/5 (~3.6 m)"),
    ("Jejunum features",      "Thick wall, wide lumen, prominent plicae circulares (circular folds), long vasa recta, 1–2 arterial arcades, mesentery less fatty"),
    ("Ileum features",        "Thinner wall, narrower, fewer/absent plicae, Peyer's patches (lymphoid follicles), short vasa recta, multiple arcades, mesentery more fatty"),
    ("Ileocaecal junction",   "Ileum opens into caecum via ileocaecal valve; prevents reflux"),
    ("Blood supply",          "Superior mesenteric artery (SMA) via jejunal and ileal branches"),
    ("Meckel's diverticulum", "2% population, 2 feet from ileocaecal valve, 2 inches long, 2 types of tissue (gastric/pancreatic), 2:1 male:female ratio – most common GI congenital anomaly"),
], h_bg=C_ORANGE))
story.append(sp(6))

story.append(Paragraph("Large Intestine", sSubHead))
li_rows = [
    ["PART", "LENGTH", "LOCATION / KEY FEATURES"],
    ["Caecum",              "6 cm",   "Right iliac fossa; intraperitoneal; appendix opens posteromedially"],
    ["Appendix",            "2–20 cm","Posteromedial to caecum; all taeniae coli converge here; base at McBurney's point; blood supply: appendicular a. (branch of ileocolic a.)"],
    ["Ascending colon",     "15 cm",  "Retroperitoneal; right side; hepatic flexure joins transverse colon"],
    ["Transverse colon",    "50 cm",  "Intraperitoneal (has mesocolon); most mobile part; sags below umbilicus"],
    ["Descending colon",    "25 cm",  "Retroperitoneal; left side; splenic flexure (highest, most acute angle)"],
    ["Sigmoid colon",       "40 cm",  "Intraperitoneal (has mesocolon); S-shaped; most common site of diverticulosis & volvulus"],
    ["Rectum",              "12 cm",  "Retroperitoneal β†’ subperitoneal; no taeniae; follows sacral curve; 3 lateral folds (valves of Houston)"],
]
story.append(multi_col(li_rows, [W*0.18, W*0.10, W*0.72], header=li_rows[0], h_bg=C_RED))
story.append(sp(4))
story.append(info_box("🧠 LARGE INTESTINE features: Taeniae coli (3 longitudinal muscle bands), Haustra (sacculations), Appendices epiploicae (fat tags). These 3 distinguish large from small intestine on imaging."))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 5 – LIVER, BILIARY, PANCREAS
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("5. LIVER, BILIARY SYSTEM & PANCREAS", C_BROWN, "πŸ«€"))
story.append(sp(6))

story.append(Paragraph("Liver", sSubHead))
story.append(two_col([
    ("Location",          "RUQ; protected by ribs 7–11; dull to percussion"),
    ("Surfaces",          "Diaphragmatic (superior, anterior, posterior); Visceral (inferior)"),
    ("Lobes (anatomical)","Right lobe (large) + Left lobe divided by falciform ligament. Also: caudate lobe (posterior) & quadrate lobe (inferior) – functionally belong to LEFT lobe"),
    ("Lobes (functional – Couinaud)", "8 segments based on portal & hepatic venous supply; basis for liver resections"),
    ("Porta hepatis",     "Transverse fissure on visceral surface; entry of portal vein & hepatic artery, exit of hepatic ducts & lymphatics"),
    ("Bare area",         "Where liver is not covered by peritoneum; bounded by coronary ligaments; related to diaphragm & right adrenal gland"),
    ("Ligamentum teres",  "Round ligament in falciform ligament; remnant of left umbilical vein (fetal)"),
    ("Ligamentum venosum","In fissure on visceral surface; remnant of ductus venosus (fetal)"),
    ("Blood supply",      "Dual: hepatic artery proper (25% oxygenated blood) + portal vein (75% nutrient-rich blood)"),
    ("Venous drainage",   "3 hepatic veins (right, middle, left) drain into IVC just below diaphragm"),
], h_bg=C_BROWN))
story.append(sp(6))

story.append(Paragraph("Biliary System", sSubHead))
bil_rows = [
    ("Gallbladder",        "Pear-shaped, 10 cm; fundus, body, neck; fundus at MCL + 9th costal cartilage; Hartmann's pouch = neck dilation (gallstones lodge here)"),
    ("Cystic duct",        "Spiral valve of Heister; joins common hepatic duct β†’ common bile duct"),
    ("Common bile duct",   "4 parts: supraduodenal, retroduodenal, infraduodenal (in head of pancreas), intraduodenal. Opens at ampulla of Vater"),
    ("Calot's triangle",   "Cystic duct + common hepatic duct + visceral surface of liver; cystic artery lies within it – critical in cholecystectomy"),
    ("Ampulla of Vater",   "Common opening of CBD + main pancreatic duct at major duodenal papilla (D2); controlled by sphincter of Oddi"),
    ("Murphy's sign",      "Inspiratory arrest on deep palpation of RUQ (gallbladder point); positive in acute cholecystitis"),
]
story.append(two_col(bil_rows, header=["STRUCTURE", "KEY FACTS"], h_bg=C_BROWN))
story.append(sp(6))

story.append(Paragraph("Pancreas", sSubHead))
story.append(two_col([
    ("Parts",              "Head (in C-loop of duodenum), neck (over SMA/SMV confluence), body (behind stomach), tail (touches spleen in splenorenal ligament)"),
    ("Position",           "Retroperitoneal; L1–L2 level (transpyloric plane crosses neck)"),
    ("Main pancreatic duct (Wirsung)", "Runs through entire pancreas; joins CBD at ampulla of Vater; controlled by sphincter of Oddi"),
    ("Accessory duct (Santorini)",     "Drains head; opens at minor duodenal papilla 2 cm above major papilla"),
    ("Blood supply",       "Head: superior/inferior pancreaticoduodenal arteries. Body/tail: branches of splenic artery"),
    ("Venous drainage",    "Into portal vein & splenic vein; SMV joins splenic vein behind pancreatic neck to form portal vein"),
    ("Endocrine function", "Islets of Langerhans: Ξ± cells (glucagon), Ξ² cells (insulin), Ξ΄ cells (somatostatin)"),
    ("Annular pancreas",   "Congenital ring of pancreatic tissue encircling duodenum β†’ duodenal obstruction in neonates"),
], h_bg=C_BROWN))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 6 – SPLEEN & KIDNEYS
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("6. SPLEEN & KIDNEYS / SUPRARENAL GLANDS", C_PURPLE, "πŸ’œ"))
story.append(sp(6))

story.append(Paragraph("Spleen", sSubHead))
story.append(two_col([
    ("Size rule", "'1 Γ— 3 Γ— 5 Γ— 7 Γ— 9 Γ— 11' – 1Γ—3Γ—5 inches, 7 oz weight, ribs 9–11, L10 vertebral level"),
    ("Position",  "Left hypochondriac; long axis along rib 10; intraperitoneal"),
    ("Relations", "Anterior: stomach. Medial: left kidney. Inferior: splenic flexure of colon. Superior: diaphragm"),
    ("Ligaments", "Gastrosplenic (contains short gastric vessels & left gastroepiploic). Splenorenal (lienorenal) – contains splenic vessels & tail of pancreas"),
    ("Blood supply","Splenic artery (largest branch of coeliac trunk); tortuous course along upper pancreatic border"),
    ("Notch",     "Palpable on medial border when enlarged (splenomegaly); helps distinguish from left kidney"),
    ("Function",  "Lymphocyte/macrophage pool; filters blood; destroys old RBCs; stores platelets (30%)"),
    ("Rupture",   "Most commonly injured abdominal organ in blunt trauma; subcapsular haematoma β†’ delayed rupture"),
], h_bg=C_PURPLE))
story.append(sp(6))

story.append(Paragraph("Kidneys", sSubHead))
story.append(two_col([
    ("Position",         "Retroperitoneal; T12–L3; right lower than left (liver pushes down); right at L1, left at T12–L2"),
    ("Relations (right)","Anteriorly: right adrenal, liver, hepatic flexure, D2. Posteriorly: diaphragm, psoas, quadratus lumborum, ribs 12, subcostal nerve"),
    ("Relations (left)", "Anteriorly: left adrenal, stomach, spleen, pancreas, jejunum, splenic flexure. Posteriorly: diaphragm, psoas, QLD, ribs 11–12"),
    ("Hilum",            "Medial border at L1; structures (A-V-U anterior to posterior): renal artery (usually posterior), renal vein (anterior), renal pelvis/ureter"),
    ("Coverings",        "Renal capsule β†’ perirenal fat β†’ renal (Gerota's) fascia β†’ pararenal fat"),
    ("Blood supply",     "Renal arteries from aorta at L1–L2; right is longer (crosses behind IVC). 5 segmental arteries (end arteries)"),
    ("Venous drainage",  "Renal veins β†’ IVC. Left renal vein is 3Γ— longer; receives left gonadal vein, left suprarenal vein, left inferior phrenic"),
    ("Ureter",           "3 sites of narrowing: UPJ (pelvi-ureteric junction), pelvic brim (crosses iliac vessels), vesicoureteric junction (VUJ, narrowest)"),
    ("Horseshoe kidney", "Most common renal anomaly; isthmus at L3 (held by IMA); usually functional; susceptible to trauma"),
], h_bg=C_PURPLE))
story.append(sp(6))

story.append(Paragraph("Suprarenal (Adrenal) Glands", sSubHead))
story.append(two_col([
    ("Position",    "Retroperitoneal; sit in perirenal fat above kidneys; right is triangular (D-shaped), left is crescentic"),
    ("Cortex",      "3 zones – GFR mnemonic: Glomerulosa (aldosterone), Fasciculata (cortisol), Reticularis (androgens)"),
    ("Medulla",     "Modified sympathetic ganglion cells; secretes adrenaline (80%) & noradrenaline (20%)"),
    ("Blood supply","3 arteries: superior suprarenal (from inferior phrenic), middle suprarenal (from aorta), inferior suprarenal (from renal a.)"),
    ("Venous drainage", "Single vein each side: right drains into IVC (short, risk in right adrenalectomy); left drains into left renal vein"),
], h_bg=C_PURPLE))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 7 – BLOOD VESSELS
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("7. BLOOD VESSELS OF THE ABDOMEN", C_RED, "🩸"))
story.append(sp(6))

story.append(Paragraph("Abdominal Aorta (enters at T12, bifurcates at L4)", sSubHead))
aorta_rows = [
    ["BRANCH", "LEVEL", "TERRITORY / KEY POINTS"],
    ["Coeliac trunk",            "T12/L1",  "FOREGUT (oesophagus β†’ D2): Left gastric a., splenic a., common hepatic a. (hepatic proper + GDA)"],
    ["Superior mesenteric a. (SMA)", "L1",  "MIDGUT (D3 β†’ 2/3 transverse colon): Inferior pancreaticoduodenal, intestinal (jejunal/ileal), ileocolic, right colic, middle colic arteries"],
    ["Suprarenal aa. (middle)", "L1",       "Adrenal glands"],
    ["Renal aa.",               "L1–L2",    "Kidneys; right is longer; 5 segmental (end) arteries"],
    ["Gonadal aa.",             "L2",       "Testes (testicular) / Ovaries (ovarian). Cross ureter anteriorly"],
    ["Inferior mesenteric a. (IMA)", "L3",  "HINDGUT (2/3 transverse colon β†’ rectum): Left colic a., sigmoid aa., superior rectal a."],
    ["Lumbar aa. (Γ—4 pairs)",   "L1–L4",   "Posterior abdominal wall, spinal cord"],
    ["Median sacral a.",        "L4",       "Sacrum, coccyx, rectum"],
    ["Common iliac aa.",        "L4",       "Bifurcation of aorta; divide into internal & external iliac"],
]
story.append(multi_col(aorta_rows, [W*0.25, W*0.10, W*0.65], header=aorta_rows[0], h_bg=C_RED))
story.append(sp(6))

story.append(Paragraph("Portal Venous System", sSubHead))
story.append(Paragraph(
    "The <b>portal vein</b> carries blood from GI tract and spleen to the liver. "
    "Formed behind the neck of the pancreas by the junction of the <b>superior mesenteric vein (SMV)</b> "
    "and the <b>splenic vein</b>. Inferior mesenteric vein (IMV) drains into splenic vein.", sBody))
story.append(sp(4))

porto_rows = [
    ("Portal-systemic anastomoses (important in portal hypertension)",
     "1. Oesophageal varices (left gastric v. ↔ azygos v.) – most dangerous\n"
     "2. Rectal varices (superior rectal v. ↔ inferior/middle rectal vv.) – haemorrhoids\n"
     "3. Paraumbilical (caput medusae) – recanalized paraumbilical veins β†’ epigastric veins\n"
     "4. Retroperitoneal (Retzius veins) – colon veins ↔ posterior abdominal wall veins"),
]
story.append(two_col(porto_rows, h_bg=C_RED))
story.append(sp(4))
story.append(info_box("⚠ Portal hypertension signs: Splenomegaly, ascites, oesophageal varices (haematemesis), caput medusae (dilated periumbilical veins), haemorrhoids."))
story.append(sp(8))

story.append(Paragraph("Inferior Vena Cava (IVC)", sSubHead))
story.append(two_col([
    ("Formation",       "L5 – union of right & left common iliac veins"),
    ("Tributaries",     "Common iliac, lumbar, right gonadal (left drains into left renal vein), renal, right suprarenal, hepatic (3 veins), inferior phrenic"),
    ("Passes through diaphragm", "At T8 (caval opening in central tendon)"),
    ("IVC interruption","Azygos system provides collateral venous return from lower body"),
], h_bg=C_RED))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 8 – NERVES
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("8. NERVES OF THE ABDOMEN", C_BLUE, "🧠"))
story.append(sp(6))

story.append(Paragraph("Thoracoabdominal Nerves (Anterior Rami T7–T12 + L1)", sSubHead))
story.append(two_col([
    ("T7–T9",  "Intercostal nerves β†’ epigastric wall. T7 reaches xiphoid/epigastrium. T9 supplies umbilical region"),
    ("T10",    "Reaches umbilicus (test dermatomal level for spinal anaesthesia adequacy)"),
    ("T11",    "Subcostal nerve"),
    ("T12",    "Subcostal nerve; supplies hypogastric region"),
    ("L1",     "Iliohypogastric nerve (L1) & ilioinguinal nerve (L1) – supply inguinal region & scrotum/labia; pass through inguinal canal"),
    ("Genitofemoral n. (L1–L2)", "Genital branch enters inguinal canal; femoral branch exits via femoral canal. Cremasteric reflex (genital branch)"),
], h_bg=C_BLUE))
story.append(sp(6))

story.append(Paragraph("Lumbar Plexus (L1–L4, formed within psoas major)", sSubHead))
lp_rows = [
    ["NERVE", "ROOTS", "MOTOR", "SENSORY"],
    ["Iliohypogastric",   "L1",     "Internal oblique, transversus",  "Lower abdominal wall, gluteal skin"],
    ["Ilioinguinal",      "L1",     "Internal oblique",               "Scrotum/labia majora, medial thigh (inguinal area)"],
    ["Genitofemoral",     "L1–L2",  "Cremaster (genital branch)",     "Scrotum or labia, anterior thigh (femoral branch)"],
    ["Lateral femoral cutaneous", "L2–L3", "None",                   "Lateral thigh; meralgia paraesthetica if compressed"],
    ["Femoral nerve",     "L2–L4",  "Quadriceps, sartorius, iliacus", "Anterior thigh, medial leg (saphenous nerve)"],
    ["Obturator nerve",   "L2–L4",  "Adductor group",                "Medial thigh; referred pain from hip/hernia"],
    ["Lumbosacral trunk", "L4–L5",  "(contributes to sacral plexus)", "Passes over sacral ala into pelvis"],
]
story.append(multi_col(lp_rows, [W*0.22, W*0.11, W*0.30, W*0.37], header=lp_rows[0], h_bg=C_BLUE))
story.append(sp(6))

story.append(Paragraph("Autonomic Nerves", sSubHead))
story.append(two_col([
    ("Sympathetic supply",      "Greater splanchnic (T5–T9), Lesser splanchnic (T10–T11), Least splanchnic (T12) β†’ coeliac, superior & inferior mesenteric ganglia β†’ vasoconstriction, gut motility inhibition, sphincter contraction"),
    ("Parasympathetic – Vagus (CN X)", "Supplies foregut & midgut (to splenic flexure). Posterior vagal trunk contains coeliac fibres."),
    ("Parasympathetic – Pelvic splanchnics (S2–S4)", "Supplies hindgut (splenic flexure β†’ rectum)"),
    ("Coeliac plexus",          "Large sympathetic plexus around coeliac trunk at T12/L1; targeted in coeliac plexus block for upper abdominal cancer pain"),
    ("Aortic plexus",           "Continuation of coeliac plexus; gives superior & inferior mesenteric plexuses"),
], h_bg=C_BLUE))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 9 – POSTERIOR ABDOMINAL WALL
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("9. POSTERIOR ABDOMINAL WALL", C_GREEN, "🦴"))
story.append(sp(6))

paw_rows = [
    ["MUSCLE", "ORIGIN", "INSERTION", "NERVE", "ACTION"],
    ["Psoas major",       "T12–L5 vertebral bodies & transverse processes", "Lesser trochanter of femur (with iliacus = iliopsoas)", "L2–L4 (direct branches)", "Flexes thigh; flexes trunk on lower limb"],
    ["Iliacus",           "Iliac fossa, iliac crest, sacrum",     "Lesser trochanter (with psoas)",   "Femoral nerve (L2–L3)",   "Flexes thigh"],
    ["Quadratus lumborum","Iliac crest, iliolumbar lig, L5 transverse process", "12th rib, L1–L4 transverse processes", "T12, L1–L4",  "Lateral flexion of trunk; fixes 12th rib (breathing); extends lumbar spine"],
]
pt2 = Table(paw_rows, colWidths=[W*0.17, W*0.23, W*0.22, W*0.17, W*0.21])
pt2.setStyle(TableStyle([
    ("BACKGROUND",    (0,0), (-1,0), C_GREEN),
    ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
    ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",      (0,0), (-1,-1), 7.5),
    ("GRID",          (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS",(0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING",    (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING",   (0,0), (-1,-1), 5),
    ("ALIGN",         (0,0), (-1,-1), "LEFT"),
    ("VALIGN",        (0,0), (-1,-1), "TOP"),
]))
story.append(pt2)
story.append(sp(6))

story.append(Paragraph("Key Vertebral Level Landmarks", sSubHead))
vl_rows = [
    ("T8",  "IVC passes through diaphragm (caval opening in central tendon)"),
    ("T10", "Oesophagus passes through diaphragm (right crus)"),
    ("T12/L1", "Aorta passes through diaphragm (posterior, between crura). Coeliac trunk arises."),
    ("L1",  "Transpyloric plane (halfway between jugular notch & pubic symphysis): pylorus, D1, neck of pancreas, hilum of kidneys, SMA origin, L1 vertebra, fundus of gallbladder"),
    ("L2",  "Renal arteries, IMA origin, gonadal arteries, origin of femoral nerve"),
    ("L3",  "IMA arises, subcostal plane, umbilicus (L3–L4)"),
    ("L4",  "Aorta bifurcates into common iliac arteries; umbilicus; highest point of iliac crests"),
    ("L5",  "IVC formation (union of common iliac veins); lumbosacral trunk"),
]
story.append(two_col(vl_rows, header=["LEVEL", "LANDMARK"], h_bg=C_GREEN))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 10 – CLINICAL HIGH-YIELDS
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("10. CLINICAL HIGH-YIELDS & MNEMONICS", C_RED, "πŸ₯"))
story.append(sp(6))

clin_rows = [
    ["CLINICAL TOPIC", "ANATOMY BASIS", "KEY POINT"],
    ["Appendicitis",
     "Appendix at McBurney's point; base at confluence of taeniae coli",
     "RLQ pain, Rovsing's sign, rebound tenderness. Retrocaecal appendix β†’ psoas sign. Pelvic appendix β†’ Obturator sign"],
    ["Acute pancreatitis",
     "Pancreas retroperitoneal at L1–L2; related to duodenum & splenic vein",
     "Epigastric/LUQ pain radiating to back; Grey Turner's (flanks) & Cullen's (umbilicus) signs = retroperitoneal haemorrhage"],
    ["Gallstone ileus",
     "Gallstone erodes through gallbladder into duodenum via cholecystoduodenal fistula",
     "Rigler's triad: air in biliary tree, small bowel obstruction, ectopic gallstone"],
    ["Portal hypertension",
     "Portal-systemic anastomoses open when portal pressure exceeds 10 mmHg",
     "Varices (oesophageal), splenomegaly, ascites, caput medusae; TIPS procedure bypasses liver"],
    ["Aortic aneurysm (AAA)",
     "Infrarenal aorta (below renal arteries) most common site; L4",
     "Pulsatile epigastric mass; rupture β†’ haemodynamic collapse; retroperitoneal haematoma"],
    ["Inguinal hernia",
     "Deep inguinal ring (lateral to inferior epigastric a.) vs Hesselbach triangle (medial)",
     "Indirect (congenital, lateral) more common in males. Direct (acquired, medial) related to weak posterior wall"],
    ["Femoral hernia",
     "Through femoral canal medial to femoral vein; below inguinal ligament",
     "More common in women; high risk of strangulation; Narath's triangle"],
    ["Splenomegaly",
     "Spleen enlarges towards RLQ; notched medial border",
     "Cannot get above it (unlike kidney). Causes: malaria, portal HTN, haematological malignancy, EBV"],
    ["Referred pain – shoulder tip",
     "Diaphragm innervated by phrenic nerve (C3–C5)",
     "Blood/pus under diaphragm (e.g. ruptured ectopic, perforated duodenal ulcer) β†’ referred to C4 dermatome (shoulder tip)"],
    ["Posterior duodenal ulcer",
     "D1 posterior wall related to gastroduodenal artery (GDA)",
     "GDA erosion β†’ haematemesis/melaena. Anterior perforation β†’ free air, peritonitis"],
    ["Wilms' tumour",
     "Renal tumour of children; arises from metanephric blastema",
     "Large flank mass in child; does NOT cross midline (unlike neuroblastoma)"],
    ["Ureteric colic",
     "3 sites of narrowing: UPJ, crossing iliac vessels at pelvic brim, VUJ",
     "Loin-to-groin pain; haematuria; stone commonly lodges at VUJ (narrowest)"],
]
ct = Table(clin_rows, colWidths=[W*0.22, W*0.32, W*0.46])
ct.setStyle(TableStyle([
    ("BACKGROUND",    (0,0), (-1,0), C_RED),
    ("TEXTCOLOR",     (0,0), (-1,0), WHITE),
    ("FONTNAME",      (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",      (0,0), (-1,-1), 7.5),
    ("GRID",          (0,0), (-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS",(0,1), (-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING",    (0,0), (-1,-1), 5),
    ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING",   (0,0), (-1,-1), 6),
    ("ALIGN",         (0,0), (-1,-1), "LEFT"),
    ("VALIGN",        (0,0), (-1,-1), "TOP"),
]))
story.append(ct)
story.append(sp(10))

# ── MNEMONICS ─────────────────────────────────────────────────────────────────
story.append(section_banner("MNEMONICS & MEMORY AIDS", colors.HexColor("#4A235A")))
story.append(sp(6))
mnems = [
    ("<b>Coeliac trunk branches:</b> 'The Liver Splits':  Left gastric, Splenic, Common hepatic artery"),
    ("<b>SMA branches (I IN MIDDLE RIGHT):</b> Inferior pancreaticoduodenal, Intestinal (jejunal/ileal), Ileocolic, Middle colic, Right colic"),
    ("<b>Hepatoduodenal ligament contents (from rightβ†’left):</b> 'CBD–HA–PV' = Common Bile Duct (right), Hepatic Artery proper (left), Portal Vein (posterior)"),
    ("<b>Structures at transpyloric plane (L1):</b> 'Portly People Like Snacks' = Pylorus, Pancreatic neck, L1 body, Superior mesenteric artery"),
    ("<b>Diaphragm openings</b> (T-levels): 'I 8 (T8) 10 eggs (T10) At (Aorta) 12':  T8 = IVC, T10 = oesophagus, T12 = aorta"),
    ("<b>Retroperitoneal structures (SAD PUCKER):</b> Suprarenal, Aorta/IVC, Duodenum (D2–D4), Pancreas, Ureters, Colon (ascending/descending), Kidneys, Esophagus, Rectum"),
    ("<b>Meckel's diverticulum – Rule of 2's:</b> 2% population, 2 feet from ileocaecal valve, 2 inches long, 2 types ectopic tissue, 2:1 male:female, usually presents < 2 years"),
    ("<b>McBurney's point:</b> 1/3 of the way from Anterior Superior Iliac Spine (ASIS) to the umbilicus"),
    ("<b>Inguinal hernia:</b> 'MDs don't Lie': Medial = Direct; Lateral = Indirect"),
    ("<b>Femoral canal contents (NAVL – lateral to medial):</b> Nerve, Artery, Vein, Lymphatics (femoral canal is medial – 'L' for Lymph & Lacunar ligament)"),
]
for m in mnems:
    story.append(Paragraph(f"β€’ {m}", S("mb", fontSize=9, fontName="Helvetica", textColor=C_DGRAY,
                                        leftIndent=14, spaceAfter=3, leading=13)))
story.append(sp(6))

# ── FOOTER ────────────────────────────────────────────────────────────────────
story.append(HRFlowable(width=W, thickness=1, color=C_LGRAY))
story.append(sp(4))
story.append(Paragraph(
    "Abdomen Anatomy Quick Revision  |  Based on Gray's Anatomy for Students, Chapter 4  |  Generated by Orris Medical AI",
    sFooter))

# ── PAGE NUMBERS ──────────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    canvas.setFont("Helvetica", 8)
    canvas.setFillColor(colors.HexColor("#AAAAAA"))
    canvas.drawRightString(A4[0] - 1.5*cm, 1.0*cm, f"Page {doc.page}")
    canvas.drawString(1.5*cm, 1.0*cm, "Abdomen Anatomy Quick Revision")
    canvas.restoreState()

doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print("PDF generated:", OUTPUT)
Running Command

cd /home/daytona/workspace/abdomen-anatomy && python generate_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/abdomen-anatomy/Abdomen_Anatomy_Quick_Revision.pdf

Your Abdomen PDF is ready! Download it here:

Abdomen Anatomy Quick Revision

PDF Document Β· PDF


What's inside (5 pages, color-coded):

SectionColorContents
1. Regions & BoundariesNavy9 abdominal regions table with organs, 4-quadrant system with clinical uses
2. Abdominal WallGreen9 layers (skin to peritoneum), rectus sheath above/below arcuate line, all 5 muscles (origin/insertion/nerve/action), inguinal canal in full detail, hernia types
3. PeritoneumTealIntraperitoneal vs retroperitoneal organs, greater/lesser omentum, epiploic foramen, peritoneal pouches, all key ligaments
4. GI TractOrange/RedStomach parts & blood supply, duodenum 4 parts with relations, jejunum vs ileum features, large intestine from caecum to rectum, Meckel's diverticulum
5. Liver, Biliary & PancreasBrownLiver lobes & Couinaud segments, biliary system, Calot's triangle, pancreas parts/ducts/zones
6. Spleen & KidneysPurpleSpleen "1Γ—3Γ—5Γ—7Γ—9Γ—11" rule, kidney relations, 3 ureteric narrowings, adrenal gland zones
7. Blood VesselsRedFull aortic branch table (T12β†’L4), portal venous system + 4 porto-systemic anastomoses, IVC tributaries
8. NervesBlueT7–T12 dermatomes, lumbar plexus table, autonomic supply (vagus vs pelvic splanchnics, splenic flexure watershed)
9. Posterior WallGreenPsoas, iliacus, quadratus lumborum; vertebral level landmarks (T8 to L5)
10. Clinical High-YieldsRed12 clinical scenarios (appendicitis, pancreatitis, AAA, hernias, portal HTN, etc.)
MnemonicsPurple10 memory aids including SAD PUCKER, Rule of 2's, T8/T10/T12 diaphragm openings

Make me a pdf for lower limbs summary for quick revision

Running Command

mkdir -p /home/daytona/workspace/lower-limb-anatomy && ls /home/daytona/workspace/

Writing File

~/lower-limb-anatomy/generate_pdf.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT

OUTPUT = "/home/daytona/workspace/lower-limb-anatomy/Lower_Limb_Anatomy_Quick_Revision.pdf"

# ── Colour palette ─────────────────────────────────────────────────────────
C_NAVY    = colors.HexColor("#1A3560")
C_BLUE    = colors.HexColor("#2C6FAC")
C_LBLUE   = colors.HexColor("#D6E8F7")
C_ORANGE  = colors.HexColor("#D4680A")
C_LORANGE = colors.HexColor("#FDE9D9")
C_GREEN   = colors.HexColor("#1E6B3C")
C_LGREEN  = colors.HexColor("#D4EDDA")
C_PURPLE  = colors.HexColor("#5B3F8C")
C_LPURPLE = colors.HexColor("#EDE3F7")
C_RED     = colors.HexColor("#B03020")
C_LRED    = colors.HexColor("#FAD7D3")
C_TEAL    = colors.HexColor("#0E6B7A")
C_LTEAL   = colors.HexColor("#D1ECF1")
C_DGRAY   = colors.HexColor("#343A40")
C_LGRAY   = colors.HexColor("#F4F5F7")
C_YELLOW  = colors.HexColor("#856404")
C_LYELLOW = colors.HexColor("#FFF3CD")
C_MAROON  = colors.HexColor("#7B2D00")
C_LMAROON = colors.HexColor("#FAEBD7")
WHITE     = colors.white

W = A4[0] - 3*cm   # usable width

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

sTitle    = S("sTitle",    fontSize=26, fontName="Helvetica-Bold",  textColor=WHITE,  alignment=TA_CENTER, spaceAfter=4)
sSubtitle = S("sSubtitle", fontSize=13, fontName="Helvetica",       textColor=WHITE,  alignment=TA_CENTER, spaceAfter=2)
sSource   = S("sSource",   fontSize=9,  fontName="Helvetica-Oblique", textColor=colors.HexColor("#B8D4F0"), alignment=TA_CENTER)
sSectionHead = S("sSHead", fontSize=13, fontName="Helvetica-Bold", textColor=WHITE,  spaceBefore=8, spaceAfter=4, leftIndent=8, leading=17)
sSubHead  = S("sSubHead",  fontSize=10.5, fontName="Helvetica-Bold", textColor=C_NAVY, spaceBefore=6, spaceAfter=2)
sBody     = S("sBody",     fontSize=9.5,  fontName="Helvetica",      textColor=C_DGRAY, spaceAfter=3, leading=14)
sBullet   = S("sBullet",   fontSize=9,    fontName="Helvetica",      textColor=C_DGRAY, leftIndent=14, spaceAfter=2, leading=13)
sTableHead= S("sTH",       fontSize=8.5,  fontName="Helvetica-Bold", textColor=WHITE,   alignment=TA_CENTER)
sTC       = S("sTC",       fontSize=8,    fontName="Helvetica",      textColor=C_DGRAY, alignment=TA_LEFT, leading=11)
sTCB      = S("sTCB",      fontSize=8,    fontName="Helvetica-Bold", textColor=C_NAVY,  alignment=TA_LEFT, leading=11)
sFooter   = S("sFooter",   fontSize=7.5,  fontName="Helvetica-Oblique", textColor=colors.HexColor("#999999"), alignment=TA_CENTER)

# ── Helpers ────────────────────────────────────────────────────────────────
def banner(text, bg, icon=""):
    label = f"{icon}  {text}" if icon else text
    t = Table([[Paragraph(label, sSectionHead)]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,-1), bg),
        ("TOPPADDING",    (0,0),(-1,-1), 6),
        ("BOTTOMPADDING", (0,0),(-1,-1), 6),
        ("LEFTPADDING",   (0,0),(-1,-1), 10),
    ]))
    return t

def ibox(text, bg=C_LYELLOW, border=C_YELLOW):
    t = Table([[Paragraph(text, S("ib", fontSize=8.8, fontName="Helvetica", textColor=C_YELLOW, leading=13))]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,-1), bg),
        ("BOX",           (0,0),(-1,-1), 1, border),
        ("TOPPADDING",    (0,0),(-1,-1), 6),
        ("BOTTOMPADDING", (0,0),(-1,-1), 6),
        ("LEFTPADDING",   (0,0),(-1,-1), 10),
    ]))
    return t

def two(rows, header=None, hbg=C_BLUE, w1=0.35):
    c1, c2 = W*w1, W*(1-w1)
    data = []
    if header:
        data.append([Paragraph(header[0], sTableHead), Paragraph(header[1], sTableHead)])
    for r in rows:
        data.append([Paragraph(r[0], sTCB), Paragraph(r[1], sTC)])
    t = Table(data, colWidths=[c1, c2])
    st = [
        ("GRID",          (0,0),(-1,-1), 0.4, colors.HexColor("#CCCCCC")),
        ("ROWBACKGROUNDS",(0, 1 if header else 0),(-1,-1), [WHITE, C_LGRAY]),
        ("TOPPADDING",    (0,0),(-1,-1), 4),
        ("BOTTOMPADDING", (0,0),(-1,-1), 4),
        ("LEFTPADDING",   (0,0),(-1,-1), 6),
        ("VALIGN",        (0,0),(-1,-1), "TOP"),
    ]
    if header:
        st += [("BACKGROUND",(0,0),(-1,0), hbg)]
    t.setStyle(TableStyle(st))
    return t

def multi(rows, cw, header=None, hbg=C_BLUE):
    data = []
    if header:
        data.append([Paragraph(h, sTableHead) for h in header])
    for r in rows:
        data.append([Paragraph(str(c), sTC) for c in r])
    t = Table(data, colWidths=cw)
    st = [
        ("GRID",          (0,0),(-1,-1), 0.4, colors.HexColor("#CCCCCC")),
        ("ROWBACKGROUNDS",(0, 1 if header else 0),(-1,-1), [WHITE, C_LGRAY]),
        ("TOPPADDING",    (0,0),(-1,-1), 4),
        ("BOTTOMPADDING", (0,0),(-1,-1), 4),
        ("LEFTPADDING",   (0,0),(-1,-1), 5),
        ("VALIGN",        (0,0),(-1,-1), "TOP"),
        ("FONTSIZE",      (0,0),(-1,-1), 7.8),
        ("ALIGN",         (0,0),(-1,-1), "LEFT"),
    ]
    if header:
        st += [
            ("BACKGROUND", (0,0),(-1,0), hbg),
            ("TEXTCOLOR",  (0,0),(-1,0), WHITE),
            ("FONTNAME",   (0,0),(-1,0), "Helvetica-Bold"),
            ("FONTSIZE",   (0,0),(-1,0), 8.2),
        ]
    t.setStyle(TableStyle(st))
    return t

def sp(n=6): return Spacer(1, n)

# ══════════════════════════════════════════════════════════════════════════════
doc = SimpleDocTemplate(OUTPUT, pagesize=A4,
    leftMargin=1.5*cm, rightMargin=1.5*cm,
    topMargin=1.8*cm, bottomMargin=1.8*cm,
    title="Lower Limb Anatomy Quick Revision", author="Orris Medical")
story = []

# ── COVER ─────────────────────────────────────────────────────────────────────
cover = Table([[
    Paragraph("LOWER LIMB ANATOMY", sTitle),
    Paragraph("Quick Revision Guide", sSubtitle),
    Paragraph("Based on Gray's Anatomy for Students  |  Chapters 6 & 7", sSource),
]], colWidths=[W])
cover.setStyle(TableStyle([
    ("BACKGROUND",(0,0),(-1,-1), C_NAVY),
    ("TOPPADDING",(0,0),(-1,-1), 18),
    ("BOTTOMPADDING",(0,0),(-1,-1), 18),
    ("LEFTPADDING",(0,0),(-1,-1), 14),
]))
story.append(cover); story.append(sp(14))

# ── INDEX ─────────────────────────────────────────────────────────────────────
idx = Table([[
    Paragraph("TOPIC INDEX", S("ih", fontSize=10, fontName="Helvetica-Bold", textColor=WHITE, alignment=TA_CENTER)),
    Paragraph(
        "1. Bones &amp; Landmarks   β€’   2. Joints   β€’   3. Gluteal Region   β€’   4. Thigh   "
        "β€’   5. Knee &amp; Popliteal Fossa   β€’   6. Leg   β€’   7. Foot   β€’   8. Blood Vessels   "
        "β€’   9. Nerves   β€’   10. Dermatomes &amp; Surface Anatomy   β€’   11. Clinical High-Yields",
        S("ib2", fontSize=9, fontName="Helvetica", textColor=WHITE, alignment=TA_CENTER, leading=14))
]], colWidths=[W])
idx.setStyle(TableStyle([
    ("BACKGROUND",(0,0),(-1,-1), C_BLUE),
    ("TOPPADDING",(0,0),(-1,-1), 6),
    ("BOTTOMPADDING",(0,0),(-1,-1), 8),
    ("LEFTPADDING",(0,0),(-1,-1), 12),
]))
story.append(idx); story.append(sp(14))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 1 – BONES & LANDMARKS
# ══════════════════════════════════════════════════════════════════════════════
story.append(banner("1. BONES & BONY LANDMARKS", C_NAVY, "🦴"))
story.append(sp(6))
story.append(Paragraph(
    "The lower limb consists of the <b>hip bone</b> (pelvic girdle), <b>femur</b>, <b>patella</b>, "
    "<b>tibia</b>, <b>fibula</b>, <b>tarsal bones</b>, <b>metatarsals</b>, and <b>phalanges</b>.", sBody))
story.append(sp(5))

bone_rows = [
    ["BONE", "KEY LANDMARKS / FEATURES", "CLINICAL RELEVANCE"],
    ["Femur",
     "Head, neck, greater & lesser trochanters, intertrochanteric line/crest, shaft, medial/lateral condyles, epicondyles, linea aspera (posterior), adductor tubercle",
     "Neck-shaft angle 126Β° (coxa vara <120Β°, valga >135Β°). Neck fracture: common in elderly osteoporotic women"],
    ["Patella",
     "Largest sesamoid bone; triangular; embedded in quadriceps tendon; articulates with femur only",
     "Patella alta/baja. Patella fracture: transverse (quadriceps pull) or comminuted (direct blow)"],
    ["Tibia",
     "Medial bone of leg; weight-bearing. Tibial plateau (medial & lateral condyles), tibial tuberosity (patellar ligament), anterior crest (shin), medial malleolus",
     "Tibial shaft: subcutaneous anteromedially β†’ stress fractures, shin splints"],
    ["Fibula",
     "Lateral non-weight-bearing bone. Head (common fibular nerve), neck, shaft, lateral malleolus",
     "Common fibular nerve vulnerable at fibular neck (foot drop). Lateral malleolus most common ankle fracture"],
    ["Tarsals (7)",
     "Calcaneus (largest), talus (no muscle attachments, only ligaments), navicular, cuboid, medial/intermediate/lateral cuneiforms",
     "Calcaneal fracture: fall from height (axial load). Stress fractures: navicular, 2nd metatarsal"],
    ["Metatarsals (5)",
     "Base, shaft, head. MT1 = widest, shortest; MT2 = longest (index of foot)",
     "5th MT base: peroneus brevis avulsion fracture (Jones fracture vs pseudo-Jones)"],
    ["Phalanges",
     "2 in hallux (great toe), 3 in others; proximal, middle (absent in hallux), distal",
     "Hallux valgus, mallet toe, hammer toe deformities"],
]
story.append(multi(bone_rows, [W*0.15, W*0.45, W*0.40], header=bone_rows[0], hbg=C_NAVY))
story.append(sp(8))

story.append(Paragraph("Key Angles & Axes", sSubHead))
story.append(two([
    ("Neck-shaft angle (femur)",   "126Β° normal. Coxa vara: <120Β° (limb short). Coxa valga: >135Β° (genu varum)"),
    ("Angle of femoral anteversion","Normal ~15Β°; increased in children (in-toeing gait)"),
    ("Q-angle (quadriceps angle)", "ASIS β†’ centre of patella β†’ tibial tuberosity; normal ~15Β° F, ~10Β° M. Increased β†’ patellar instability"),
    ("Tibiofemoral angle",         "~6Β° valgus (physiological); genu valgum (knock-knee) vs genu varum (bow-leg)"),
    ("Longitudinal arch",          "Medial (high) supported by plantar aponeurosis, FHL, FDL, spring ligament. Loss = flat foot"),
], hbg=C_NAVY))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 2 – JOINTS
# ══════════════════════════════════════════════════════════════════════════════
story.append(banner("2. JOINTS OF THE LOWER LIMB", C_GREEN, "πŸ”—"))
story.append(sp(6))

story.append(Paragraph("Hip Joint", sSubHead))
story.append(two([
    ("Type",         "Synovial – ball & socket; most stable joint in body"),
    ("Articulation", "Head of femur (2/3 sphere) into acetabulum deepened by acetabular labrum"),
    ("Capsule",      "Attached to acetabular rim, intertrochanteric line anteriorly, neck posteriorly (mid-neck) β†’ posterior neck is extracapsular"),
    ("Ligaments",    "Iliofemoral (Y-ligament of Bigelow – strongest in body; resists hyperextension), Pubofemoral (resists abduction), Ischiofemoral (resists internal rotation)"),
    ("Ligamentum teres","Carries artery to head of femur (obturator artery, posterior branch); important in childhood but less critical in adults"),
    ("Blood supply to head", "Medial circumflex femoral artery (MCFA) – main. Lateral circumflex femoral (LCFA). Obturator artery (ligamentum teres)"),
    ("Movements",    "Flexion (0–120Β°), Extension (0–15Β°), Abduction (0–45Β°), Adduction (0–30Β°), Medial rotation (0–45Β°), Lateral rotation (0–45Β°)"),
    ("Relations",    "Anteriorly: femoral nerve, femoral artery. Posteriorly: sciatic nerve (remember when giving IM injections)"),
], hbg=C_GREEN))
story.append(sp(4))
story.append(ibox("⚠ CLINICAL: Femoral neck fractures interrupt MCFA β†’ avascular necrosis of femoral head. Posterior dislocation β†’ sciatic nerve injury (foot drop) + avascular necrosis."))
story.append(sp(8))

story.append(Paragraph("Knee Joint", sSubHead))
story.append(two([
    ("Type",          "Synovial – modified hinge (allows some rotation in flexion); largest joint in body"),
    ("Articulations", "Tibiofemoral (medial & lateral) + patellofemoral (3 compartments)"),
    ("Capsule",       "Extensive fibrous capsule; bursa = suprapatellar pouch (communicates with joint)"),
    ("Collateral ligs","Medial (tibial) collateral lig (MCL): attached to medial meniscus. Lateral (fibular) collateral lig (LCL): NOT attached to lateral meniscus"),
    ("Cruciate ligs", "ACL (anteromedial tibial β†’ lateral femoral condyle): prevents anterior tibial shift; taut in extension. PCL (posterolateral tibial β†’ medial femoral condyle): prevents posterior tibial shift; taut in flexion"),
    ("Menisci",       "Medial meniscus: C-shaped, peripheral, tightly attached β†’ more commonly torn. Lateral: O-shaped, loosely attached β†’ less commonly torn"),
    ("Bursae",        "Prepatellar (kneeling), infrapatellar (clergy knee), semimembranosus, Baker's cyst (popliteal)"),
    ("Locking mechanism", "In full extension: lateral femoral condyle rotates medially β†’ 'screws home'. Unlocking: popliteus (laterally rotates femur on fixed tibia)"),
], hbg=C_GREEN))
story.append(sp(4))
story.append(ibox("🧠 UNHAPPY TRIAD (O'Donoghue): ACL + MCL + Medial meniscus – typically from lateral blow to knee. MCL and medial meniscus injured together because MCL is attached to medial meniscus."))
story.append(sp(8))

story.append(Paragraph("Ankle (Talocrural) Joint", sSubHead))
story.append(two([
    ("Type",         "Synovial hinge; mortise & tenon; tibia + fibula form mortise around talus"),
    ("Movements",    "Dorsiflexion (pulling toes up, 0–20Β°) + Plantarflexion (pointing toes, 0–50Β°) only"),
    ("Medial (deltoid) lig", "Very strong; 4 parts; attaches medial malleolus to talus/calcaneus/navicular; resists eversion. Rarely torn – often avulses medial malleolus instead"),
    ("Lateral ligament", "3 parts: ATFL (anterior talofibular – most commonly sprained), CFL (calcaneofibular), PTFL (posterior talofibular – strongest)"),
    ("Stability",    "Dorsiflexion = most stable (talus is wider anteriorly fills mortise). Plantarflexion = unstable β†’ most sprains occur"),
], hbg=C_GREEN))
story.append(sp(8))

story.append(Paragraph("Subtalar & Other Foot Joints", sSubHead))
story.append(two([
    ("Subtalar joint",       "Talocalcaneal; inversion/eversion occur here (NOT at ankle)"),
    ("Midtarsal (Chopart)",  "Talonavicular + calcaneocuboid joints; further inversion/eversion"),
    ("Lisfranc joint",       "Tarsometatarsal joints; Lisfranc ligament = medial cuneiform to MT2 base; disruption β†’ unstable foot"),
    ("MTP joints",           "Metatarsophalangeal; flexion/extension + abduction/adduction"),
    ("IP joints",            "Hinge joints; flexion/extension only"),
], hbg=C_GREEN))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 3 – GLUTEAL REGION
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(banner("3. GLUTEAL REGION", C_ORANGE, "πŸ’ͺ"))
story.append(sp(6))

glut_rows = [
    ["MUSCLE", "ORIGIN", "INSERTION", "NERVE", "ACTION"],
    ["Gluteus maximus",   "Ilium (posterior), sacrum, coccyx, sacrotuberous lig", "IT band (upper 3/4), gluteal tuberosity (lower 1/4)", "Inferior gluteal (L5–S2)", "Powerful hip extensor; lateral rotator. Main action in climbing stairs/rising from chair"],
    ["Gluteus medius",    "Outer ilium (between anterior & posterior lines)", "Greater trochanter (lateral surface)", "Superior gluteal (L4–S1)", "Abducts thigh; anterior fibres medially rotate; essential for Trendelenburg gait"],
    ["Gluteus minimus",   "Outer ilium (between anterior & inferior lines)", "Greater trochanter (anterior surface)", "Superior gluteal (L4–S1)", "Abducts + medially rotates thigh; stabilises pelvis in single-leg stance"],
    ["Tensor fascia lata","ASIS, iliac crest", "IT band (β†’ Gerdy's tubercle tibia)", "Superior gluteal (L4–S1)", "Abducts + medially rotates hip; tenses IT band; stabilises knee"],
    ["Piriformis",        "Anterior sacrum (S2–S4)", "Greater trochanter (apex)", "S1–S2", "Laterally rotates thigh (primary); abducts when hip flexed"],
    ["Obturator internus","Inner obturator membrane, hip bone", "Greater trochanter (medial)", "Nerve to OI (L5–S1)", "Lateral rotator of thigh; stabilises femoral head in acetabulum"],
    ["Gemellus superior", "Ischial spine", "Greater trochanter (tendon of OI)", "Nerve to OI (L5–S2)", "Lateral rotator"],
    ["Gemellus inferior", "Ischial tuberosity", "Greater trochanter (tendon of OI)", "Nerve to QF (L4–S1)", "Lateral rotator"],
    ["Quadratus femoris", "Ischial tuberosity", "Intertrochanteric crest", "Nerve to QF (L4–S1)", "Lateral rotator; adducts thigh"],
    ["Obturator externus","Outer obturator membrane, hip bone", "Trochanteric fossa", "Obturator nerve (L3–L4)", "Lateral rotator of thigh"],
]
story.append(multi(glut_rows, [W*0.16, W*0.20, W*0.18, W*0.16, W*0.30], header=glut_rows[0], hbg=C_ORANGE))
story.append(sp(5))
story.append(ibox("🧠 Deep 6 lateral rotators mnemonic: 'Please Go On Giving Good Outcomes' = Piriformis, Gemellus superior, Obturator internus, Gemellus inferior, Obturator externus, Quadratus femoris"))
story.append(sp(6))

story.append(Paragraph("Greater Sciatic Foramen Contents", sSubHead))
story.append(two([
    ("Above piriformis",  "Superior gluteal artery & vein, Superior gluteal nerve"),
    ("Below piriformis",  "Inferior gluteal a/v/n, Sciatic nerve, Posterior cutaneous n. of thigh, Pudendal n. (then re-enters via lesser sciatic foramen), Internal pudendal a/v, Nerve to obturator internus, Nerve to quadratus femoris"),
], hbg=C_ORANGE))
story.append(sp(4))
story.append(ibox("⚠ TRENDELENBURG SIGN: Pelvis droops to opposite side when standing on affected leg β†’ indicates weak hip abductors (Gmed/Gmin) or superior gluteal nerve damage, or hip pathology. Limp: trunk leans to AFFECTED side to compensate (Trendelenburg gait)."))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 4 – THIGH
# ══════════════════════════════════════════════════════════════════════════════
story.append(banner("4. THIGH – COMPARTMENTS & MUSCLES", C_PURPLE, "🦡"))
story.append(sp(6))

story.append(Paragraph("Anterior Compartment – Extensors of Knee / Flexors of Hip", sSubHead))
ant_rows = [
    ["MUSCLE", "ORIGIN", "INSERTION", "NERVE", "ACTION"],
    ["Iliacus",      "Iliac fossa, sacrum", "Lesser trochanter (with psoas)", "Femoral (L2–L3)", "Hip flexion"],
    ["Psoas major",  "T12–L5 bodies & TPs", "Lesser trochanter (with iliacus)", "L1–L3 direct branches", "Hip flexion; lateral flexion of trunk"],
    ["Sartorius",    "ASIS",    "Medial tibia (pes anserinus)", "Femoral (L2–L3)", "Hip: flexion, abduction, lateral rotation. Knee: flexion"],
    ["Rectus femoris","AIIS, acetabular rim (reflected head)", "Tibial tuberosity via patellar lig", "Femoral (L2–L4)", "Extends knee; flexes hip (only quad that crosses hip)"],
    ["Vastus lateralis","Greater trochanter, linea aspera", "Tibial tuberosity (lateral)", "Femoral (L2–L4)", "Extends knee; prevents medial dislocation of patella"],
    ["Vastus medialis","Intertrochanteric line, linea aspera", "Tibial tuberosity (medial) – VMO fibers key", "Femoral (L2–L4)", "Extends knee; prevents lateral dislocation of patella"],
    ["Vastus intermedius","Anterior shaft of femur", "Tibial tuberosity (deep)", "Femoral (L2–L4)", "Extends knee"],
    ["Pectineus",    "Pectineal line of pubis", "Pectineal line of femur", "Femoral & obturator (L2–L3)", "Hip flexion + adduction"],
]
story.append(multi(ant_rows, [W*0.14, W*0.20, W*0.18, W*0.16, W*0.32], header=ant_rows[0], hbg=C_PURPLE))
story.append(sp(6))

story.append(Paragraph("Medial Compartment – Adductors", sSubHead))
med_rows = [
    ["MUSCLE", "ORIGIN", "INSERTION", "NERVE", "ACTION"],
    ["Adductor longus", "Body of pubis", "Linea aspera (middle 1/3 of femur)", "Obturator (L2–L4)", "Adducts + medially rotates"],
    ["Adductor brevis",  "Inferior pubic ramus", "Upper linea aspera", "Obturator (L2–L4)", "Adducts + medially rotates"],
    ["Adductor magnus",  "Ischiopubic ramus (adductor part) + ischial tuberosity (hamstring part)", "Linea aspera + adductor tubercle", "Obturator (L2–L4) adductor part; Tibial part of sciatic (L4) hamstring part", "Adducts (powerful); hamstring part extends hip"],
    ["Gracilis",         "Inferior pubic ramus + ischiopubic ramus", "Medial tibia (pes anserinus)", "Obturator (L2–L3)", "Adducts thigh; flexes & medially rotates knee"],
    ["Obturator externus","Outer obturator membrane", "Trochanteric fossa", "Obturator (L3–L4)", "Lateral rotator of hip"],
]
story.append(multi(med_rows, [W*0.14, W*0.22, W*0.18, W*0.20, W*0.26], header=med_rows[0], hbg=C_PURPLE))
story.append(sp(4))
story.append(ibox("🧠 ADDUCTOR HIATUS: Gap in adductor magnus where femoral vessels pass from adductor canal (anterior thigh) into popliteal fossa (posterior)."))
story.append(sp(6))

story.append(Paragraph("Posterior Compartment – Hamstrings (Hip extensors / Knee flexors)", sSubHead))
ham_rows = [
    ["MUSCLE", "ORIGIN", "INSERTION", "NERVE", "ACTION"],
    ["Biceps femoris (long head)", "Ischial tuberosity", "Head of fibula, lateral tibial condyle", "Tibial part of sciatic (L5–S2)", "Extends hip, flexes knee, laterally rotates knee"],
    ["Biceps femoris (short head)", "Linea aspera (lower 1/3)", "Head of fibula", "Common fibular part of sciatic (L5–S2)", "Flexes knee, laterally rotates knee"],
    ["Semitendinosus",  "Ischial tuberosity", "Medial tibia (pes anserinus)", "Tibial part of sciatic (L5–S2)", "Extends hip, flexes & medially rotates knee"],
    ["Semimembranosus", "Ischial tuberosity", "Posterior medial tibial condyle; oblique popliteal lig; popliteus fascia", "Tibial part of sciatic (L5–S2)", "Extends hip, flexes & medially rotates knee"],
]
story.append(multi(ham_rows, [W*0.18, W*0.18, W*0.22, W*0.16, W*0.26], header=ham_rows[0], hbg=C_PURPLE))
story.append(sp(4))
story.append(ibox("🧠 PES ANSERINUS ('goose's foot'): Sartorius + Gracilis + Semitendinosus insert together on medial tibia. Bursitis here causes medial knee pain."))
story.append(sp(8))

story.append(Paragraph("Femoral Triangle", sSubHead))
story.append(two([
    ("Boundaries",   "Superior: inguinal ligament. Lateral: sartorius. Medial: adductor longus. Floor: iliopsoas (lateral) + pectineus (medial). Roof: fascia lata + cribriform fascia"),
    ("Contents (NAVEL – lateral to medial)", "Nerve (femoral), Artery (femoral), Vein (femoral), Empty space, Lymphatics (femoral canal with Cloquet's node)"),
    ("Apex",         "Leads into adductor (Hunter's) canal"),
], hbg=C_PURPLE))
story.append(sp(6))

story.append(Paragraph("Adductor (Hunter's) Canal", sSubHead))
story.append(two([
    ("Location",    "Middle 1/3 of thigh; subsartorial canal"),
    ("Boundaries",  "Anteromedial: sartorius & vastomedial fascia. Posteromedial: adductor longus & magnus. Lateral: vastus medialis"),
    ("Contents",    "Femoral artery, femoral vein (posterior to artery), saphenous nerve (medial cutaneous branch of femoral n.), nerve to vastus medialis, descending genicular artery"),
    ("Ends at",     "Adductor hiatus (gap in adductor magnus) β†’ popliteal fossa"),
], hbg=C_PURPLE))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 5 – KNEE & POPLITEAL FOSSA
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(banner("5. KNEE & POPLITEAL FOSSA", C_TEAL, "🦡"))
story.append(sp(6))

story.append(Paragraph("Popliteal Fossa", sSubHead))
story.append(two([
    ("Shape",       "Diamond-shaped depression posterior to knee"),
    ("Boundaries",  "Superomedial: semimembranosus + semitendinosus. Superolateral: biceps femoris. Inferomedial: medial head of gastrocnemius. Inferolateral: lateral head of gastrocnemius + plantaris"),
    ("Floor",       "Popliteal surface of femur, posterior capsule of knee joint, popliteus muscle"),
    ("Roof",        "Deep fascia (popliteal fascia); small saphenous vein pierces here; posterior cutaneous nerve of thigh"),
    ("Contents (superficial to deep, medial to lateral)", "Common fibular nerve (lateral), tibial nerve (medial), popliteal vein (between), popliteal artery (deepest). Also: popliteal lymph nodes, fat"),
    ("Baker's cyst","Semimembranosus bursa or gastrocnemius-semimembranosus bursa communicates with joint; seen in OA/RA; can rupture mimicking DVT"),
], hbg=C_TEAL))
story.append(sp(6))

story.append(Paragraph("Popliteus Muscle", sSubHead))
story.append(two([
    ("Origin",    "Lateral femoral condyle (lateral surface) + arcuate popliteal ligament"),
    ("Insertion", "Posterior tibial surface (above soleal line)"),
    ("Nerve",     "Tibial nerve (L4–S1)"),
    ("Action",    "'Unlocks' the knee from full extension by laterally rotating femur on fixed tibia (first 20Β° of flexion); also retracts lateral meniscus during knee flexion"),
], hbg=C_TEAL))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 6 – LEG
# ══════════════════════════════════════════════════════════════════════════════
story.append(banner("6. LEG – COMPARTMENTS & MUSCLES", C_RED, "🦡"))
story.append(sp(6))

story.append(Paragraph("Anterior Compartment – Dorsiflexors & Extensors (Deep fibular nerve L4–L5)", sSubHead))
ant_leg = [
    ["MUSCLE", "ORIGIN", "INSERTION", "ACTION"],
    ["Tibialis anterior",  "Lateral tibial condyle, tibia shaft (upper 2/3)", "Medial cuneiform, MT1 base (medial & plantar)", "Dorsiflexion + inversion (main dorsiflexor)"],
    ["Extensor digitorum longus (EDL)", "Lateral tibial condyle, fibula (upper 3/4)", "Dorsal expansion of toes 2–5 (middle & distal phalanges)", "Extends toes 2–5; dorsiflexion; eversion"],
    ["Extensor hallucis longus (EHL)", "Middle fibula, interosseous membrane", "Distal phalanx of hallux (dorsal)", "Extends hallux; dorsiflexion; assists inversion"],
    ["Fibularis (peroneus) tertius", "Lower fibula, interosseous membrane", "MT5 base (dorsal)", "Dorsiflexion + eversion; weakest muscle"],
]
story.append(multi(ant_leg, [W*0.20, W*0.24, W*0.24, W*0.32], header=ant_leg[0], hbg=C_RED))
story.append(sp(6))

story.append(Paragraph("Lateral Compartment – Evertors (Superficial fibular nerve L5–S1)", sSubHead))
lat_leg = [
    ["MUSCLE", "ORIGIN", "INSERTION", "ACTION"],
    ["Fibularis (peroneus) longus", "Upper fibula (lateral surface)", "Medial cuneiform + MT1 base (plantar, crosses sole obliquely)", "Eversion (primary); plantarflexion; supports lateral longitudinal arch & transverse arch"],
    ["Fibularis (peroneus) brevis", "Lower fibula (lateral surface)", "MT5 base (styloid process)", "Eversion; plantarflexion"],
]
story.append(multi(lat_leg, [W*0.20, W*0.25, W*0.23, W*0.32], header=lat_leg[0], hbg=C_RED))
story.append(sp(4))
story.append(ibox("⚠ Fibularis brevis tendon avulsion at MT5 base = 'pseudo-Jones fracture' (from inversion injury). True Jones fracture = stress fracture of MT5 diaphysis (proximal 1.5 cm) – poor blood supply, often requires fixation."))
story.append(sp(6))

story.append(Paragraph("Posterior Compartment – Superficial (Tibial nerve S1–S2)", sSubHead))
sup_post = [
    ["MUSCLE", "ORIGIN", "INSERTION", "ACTION"],
    ["Gastrocnemius (medial head)", "Medial femoral condyle (posterior)", "Calcaneus via Achilles tendon", "Plantarflexion (powerful) + knee flexion"],
    ["Gastrocnemius (lateral head)","Lateral femoral condyle (posterior)", "Calcaneus via Achilles tendon", "Plantarflexion + knee flexion"],
    ["Soleus",     "Posterior head + neck of fibula; soleal line of tibia", "Calcaneus via Achilles tendon", "Plantarflexion (main postural muscle – standing); 'peripheral heart' pump"],
    ["Plantaris",  "Lateral supracondylar line of femur", "Medial calcaneus via long thin tendon", "Weak plantarflexion + knee flexion; vestigial"],
]
story.append(multi(sup_post, [W*0.22, W*0.24, W*0.22, W*0.32], header=sup_post[0], hbg=C_RED))
story.append(sp(4))
story.append(ibox("🧠 TRICEPS SURAE = Gastrocnemius + Soleus (+ Plantaris). Achilles tendon = strongest tendon in body; inserts into posterior calcaneus. Rupture: Thompson (Simmonds) test positive – squeezing calf doesn't produce plantarflexion."))
story.append(sp(6))

story.append(Paragraph("Posterior Compartment – Deep (Tibial nerve L4–S2)", sSubHead))
deep_post = [
    ["MUSCLE", "ORIGIN", "INSERTION", "ACTION"],
    ["Popliteus",           "Lateral femoral condyle, arcuate lig", "Posterior tibia (above soleal line)", "Unlocks knee; retracts lateral meniscus"],
    ["Flexor hallucis longus (FHL)", "Posterior fibula (lower 2/3)", "Distal phalanx of hallux (plantar)", "Flexes hallux (toe-off in gait); plantarflexion; supports medial arch; 'Cinderella muscle' of ballet"],
    ["Flexor digitorum longus (FDL)", "Posterior tibia (middle 1/3)", "Distal phalanges of toes 2–5 (plantar)", "Flexes toes 2–5; plantarflexion; supports medial arch"],
    ["Tibialis posterior", "Posterior interosseous membrane, fibula, tibia", "Navicular tuberosity (primary); all other tarsals & metatarsals", "Inversion (primary); plantarflexion; supports medial arch; prevents flat foot"],
]
story.append(multi(deep_post, [W*0.17, W*0.23, W*0.22, W*0.38], header=deep_post[0], hbg=C_RED))
story.append(sp(4))
story.append(ibox("🧠 Tom, Dick And Very Nervous Harry (medial malleolus order, anteriorβ†’posterior): Tibialis posterior, flexor Digitorum longus, posterior tibial Artery, tibial Vein, tibial Nerve, flexor Hallucis longus"))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 7 – FOOT
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(banner("7. FOOT – MUSCLES, ARCHES & SOLE", C_MAROON, "🦢"))
story.append(sp(6))

story.append(Paragraph("Intrinsic Muscles of the Foot – 4 Layers (Plantar Surface)", sSubHead))
foot_rows = [
    ["LAYER", "MUSCLES", "NERVE", "ACTION"],
    ["Layer 1 (most superficial)",
     "Abductor hallucis, Flexor digitorum brevis (FDB), Abductor digiti minimi",
     "Medial plantar n. (AbH, FDB); Lateral plantar n. (AbDM)",
     "FDB: flexes toes 2–5 (PIP). AbH: abducts hallux (supports medial arch). AbDM: abducts little toe"],
    ["Layer 2",
     "Quadratus plantae (+ FDL tendons), Lumbricals (4) – from FDL tendons",
     "Lateral plantar n. (QP, L3–L4 lumb.); Medial plantar n. (L1 lumb.)",
     "QP: straightens oblique FDL pull. Lumbricals: flex MTP, extend IP joints (as in hand)"],
    ["Layer 3",
     "Flexor hallucis brevis (FHB), Adductor hallucis (oblique + transverse), Flexor digiti minimi brevis",
     "Medial plantar n. (FHB); Lateral plantar n. (AdH, FDMB)",
     "FHB: flexes hallux at MTP. AdH: adducts hallux; transverse arch support. FDMB: flexes little toe"],
    ["Layer 4 (deepest)",
     "Dorsal interossei (4) – DAB, Plantar interossei (3) – PAD",
     "Deep branch of lateral plantar nerve",
     "Dorsal interossei: abduct toes from 2nd ray. Plantar interossei: adduct toes toward 2nd ray. Both: flex MTP, extend IP"],
]
story.append(multi(foot_rows, [W*0.13, W*0.32, W*0.22, W*0.33], header=foot_rows[0], hbg=C_MAROON))
story.append(sp(6))

story.append(Paragraph("Arches of the Foot", sSubHead))
arch_rows = [
    ("Medial longitudinal arch",   "Calcaneus β†’ talus β†’ navicular β†’ 3 cuneiforms β†’ MT 1–3 (highest arch). Maintained by: plantar aponeurosis, FHL, FDL, tibialis posterior, spring (plantar calcaneonavicular) ligament, peroneus longus"),
    ("Lateral longitudinal arch",  "Calcaneus β†’ cuboid β†’ MT 4–5 (lower arch, bears weight). Maintained by: plantar aponeurosis, fibularis longus, fibularis brevis"),
    ("Transverse arch",            "Cuboid + 3 cuneiforms + MT bases form transverse arch. Maintained by: adductor hallucis (transverse head), peroneus longus, tibialis posterior"),
    ("Plantar aponeurosis",        "From calcaneal tuberosity β†’ flexor sheaths of all 5 toes. Tension increases on toe extension (windlass mechanism). Injury β†’ plantar fasciitis (heel pain)"),
    ("Flat foot (pes planus)",     "Loss of medial arch; usually flexible (corrects on tiptoe). Tibialis posterior tendon dysfunction = most common acquired cause"),
    ("High arch (pes cavus)",      "Exaggerated arch; associated with neuromuscular disease (CMT, Friedrich's ataxia, spina bifida)"),
]
story.append(two(arch_rows, header=["ARCH / STRUCTURE", "DETAILS"], hbg=C_MAROON))
story.append(sp(6))

story.append(Paragraph("Tarsal Tunnel (Medial – under flexor retinaculum)", sSubHead))
story.append(Paragraph(
    "Under flexor retinaculum (medial malleolus β†’ calcaneus). Contains: <b>Tom Dick And Very Nervous Harry</b> = "
    "Tibialis posterior tendon, FDL tendon, posterior tibial Artery, posterior tibial Vein, tibial Nerve, FHL tendon. "
    "Compression β†’ tarsal tunnel syndrome (medial plantar numbness).", sBody))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 8 – BLOOD VESSELS
# ══════════════════════════════════════════════════════════════════════════════
story.append(banner("8. BLOOD VESSELS OF THE LOWER LIMB", C_BLUE, "🩸"))
story.append(sp(6))

story.append(Paragraph("Arterial Supply", sSubHead))
art_rows = [
    ["ARTERY", "ORIGIN", "COURSE / SUPPLY"],
    ["Common femoral a.",       "External iliac a. (below inguinal lig)", "Enters femoral triangle; gives profunda femoris then becomes superficial femoral a."],
    ["Profunda femoris a.",     "Common femoral a. (3–5 cm below inguinal lig)", "Main supply to thigh. Gives: medial & lateral circumflex femoral aa. (supply hip joint & femoral neck), 3–4 perforating branches (supply hamstrings)"],
    ["Medial circumflex femoral","Profunda femoris (usually)", "Deep branch β†’ femoral neck β†’ main supply to femoral head. Vulnerable in femoral neck fracture β†’ AVN"],
    ["Lateral circumflex femoral","Profunda femoris", "Ascending (anastomosis with MCFA), transverse, descending (to vastus lateralis)"],
    ["Superficial femoral a.",  "Continuation of common femoral a.", "Runs in adductor canal; becomes popliteal a. at adductor hiatus"],
    ["Popliteal a.",            "Continuation of femoral a. at adductor hiatus", "Deepest structure in popliteal fossa. Gives genicular branches (cruciate anastomosis). Divides at lower border of popliteus"],
    ["Anterior tibial a.",      "Popliteal a.",  "Passes through gap in interosseous membrane to anterior compartment β†’ becomes dorsalis pedis a. at ankle"],
    ["Dorsalis pedis a.",       "Anterior tibial a. at ankle", "Between EHL & EDL tendons; palpable lateral to EHL. β†’ Arcuate a. β†’ dorsal metatarsal aa. β†’ dorsal digital aa. + deep plantar branch to plantar arch"],
    ["Posterior tibial a.",     "Popliteal a.",  "Posterior compartment; gives fibular (peroneal) a. (largest branch); enters tarsal tunnel; divides into medial & lateral plantar aa."],
    ["Fibular (peroneal) a.",   "Posterior tibial a.", "Lateral compartment adjacent to fibula; perforating branches to lateral malleolus; supplies fibularis muscles"],
    ["Medial plantar a.",       "Posterior tibial a.", "Supplies medial sole and hallux; smaller of two terminal branches"],
    ["Lateral plantar a.",      "Posterior tibial a.", "Supplies lateral sole; forms plantar arch (with deep branch of dorsalis pedis) β†’ plantar metatarsal arteries"],
]
story.append(multi(art_rows, [W*0.22, W*0.20, W*0.58], header=art_rows[0], hbg=C_BLUE))
story.append(sp(6))

story.append(Paragraph("Cruciate Anastomosis (around hip) & Genicular Anastomosis (around knee)", sSubHead))
story.append(two([
    ("Cruciate anastomosis", "Around hip: medial circumflex femoral + lateral circumflex femoral + inferior gluteal + 1st perforating branch of profunda. Maintains blood flow after femoral artery ligation."),
    ("Genicular anastomosis","Around knee: 5 genicular branches of popliteal a. (medial/lateral superior & inferior + middle) + descending genicular from femoral + anterior/posterior tibial recurrent aa. Protects during popliteal artery injury."),
], hbg=C_BLUE))
story.append(sp(6))

story.append(Paragraph("Venous Drainage", sSubHead))
story.append(two([
    ("Deep veins",     "Follow arteries; tibial veins β†’ popliteal vein β†’ femoral vein β†’ external iliac vein. Valves prevent reflux."),
    ("Superficial veins","Great saphenous vein (GSV): medial side, from medial foot β†’ anterior to medial malleolus β†’ medial leg β†’ medial thigh β†’ saphenofemoral junction (4 cm below inguinal ligament on medial thigh) β†’ femoral vein. Longest vein in body. Used for coronary bypass grafts."),
    ("Small saphenous vein (SSV)", "From lateral foot β†’ posterior to lateral malleolus β†’ posterior leg β†’ saphenopopliteal junction (variable level, ~behind knee) β†’ popliteal vein."),
    ("Perforating veins","Connect superficial to deep; one-way valves (blood flows inward). Incompetent perforators β†’ varicose veins."),
    ("Saphena varix",   "Dilatation of GSV at saphenofemoral junction; pulsatile, disappears on lying, cough impulse; confused with femoral hernia"),
], hbg=C_BLUE))
story.append(sp(4))
story.append(ibox("⚠ FEMORAL VEIN is medial to femoral artery. When cannulating the femoral vein, go medial to the arterial pulse. Remember: NAVEL lateral to medial in femoral triangle."))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 9 – NERVES
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(banner("9. NERVES OF THE LOWER LIMB", C_TEAL, "🧠"))
story.append(sp(6))

nerve_rows = [
    ["NERVE", "ROOTS", "COURSE", "MOTOR", "SENSORY / CLINICAL"],
    ["Femoral nerve",
     "L2–L4",
     "Emerges from lateral border of psoas β†’ under inguinal lig lateral to femoral a. β†’ divides into anterior & posterior divisions in femoral triangle",
     "Anterior division: sartorius, pectineus. Posterior division: quadriceps (via muscular branches), articularis genus",
     "Anterior cutaneous branches (medial thigh). Saphenous nerve (terminal sensory branch): medial leg & foot. Damage β†’ weak knee extension, absent knee jerk, sensory loss medial leg"],
    ["Obturator nerve",
     "L2–L4",
     "Medial border of psoas β†’ obturator foramen β†’ divides into anterior & posterior divisions on obturator externus",
     "Anterior: adductor longus, brevis, gracilis, pectineus. Posterior: adductor magnus (adductor part), obturator externus",
     "Medial thigh (variable). Injury: weak adduction, sensory loss medial thigh. Obturator hernia: compresses β†’ Howship-Romberg sign (medial thigh pain on hip medial rotation)"],
    ["Sciatic nerve",
     "L4–S3",
     "Largest nerve in body; exits pelvis via greater sciatic foramen (below piriformis); descends between greater trochanter & ischial tuberosity; divides into tibial & common fibular at apex of popliteal fossa (or higher)",
     "Posterior thigh (hamstrings & adductor magnus hamstring part); all below knee via divisions",
     "Posterior thigh skin (posterior cutaneous n.). Injury: foot drop + absent ankle jerk"],
    ["Tibial nerve",
     "L4–S3",
     "Medial component of sciatic; descends through popliteal fossa (most superficial); enters posterior compartment between 2 heads of gastrocnemius; passes under flexor retinaculum",
     "All posterior leg muscles; all intrinsic foot muscles (via medial & lateral plantar nn.)",
     "Sural nerve (lateral calf & foot), medial & lateral plantar nn. (sole of foot). Injury: loss of plantarflexion + toe flexion; claw toes; sensory loss sole"],
    ["Common fibular (peroneal) nerve",
     "L4–S2",
     "Lateral component of sciatic; winds around head & neck of fibula (most vulnerable point); divides into superficial & deep fibular nn.",
     "Superficial: fibularis longus & brevis. Deep: all anterior leg muscles + EDB",
     "Lateral leg (superficial) + web space of 1st toe (deep). Injury at fibular neck β†’ FOOT DROP (loss of dorsiflexion + eversion) + sensory loss dorsum of foot"],
    ["Deep fibular nerve",
     "L4–L5",
     "Anterior compartment of leg alongside anterior tibial artery β†’ dorsum of foot",
     "Tibialis anterior, EDL, EHL, fibularis tertius, extensor digitorum brevis",
     "Only skin in 1st web space (dorsum)"],
    ["Superficial fibular nerve",
     "L5–S1",
     "Lateral compartment β†’ pierces fascia in distal 1/3 of leg",
     "Fibularis longus & brevis",
     "Dorsum of foot except 1st web space"],
    ["Sural nerve",
     "L5–S2",
     "Formed by medial sural cutaneous (tibial) + peroneal communicating branch (common fibular); descends posterior to lateral malleolus",
     "None",
     "Lateral leg (distal 1/3) + lateral foot. Used as nerve graft donor site"],
    ["Saphenous nerve",
     "L3–L4",
     "Terminal sensory branch of femoral n.; in adductor canal β†’ emerges medial knee β†’ medial leg",
     "None",
     "Medial leg from knee to medial malleolus & medial foot. Longest cutaneous branch of femoral n."],
    ["Lateral cutaneous nerve of thigh",
     "L2–L3",
     "Passes under/through inguinal lig near ASIS β†’ lateral thigh",
     "None",
     "Lateral thigh. Compression at ASIS β†’ meralgia paraesthetica (burning lateral thigh pain)"],
]
story.append(multi(nerve_rows,
    [W*0.16, W*0.09, W*0.20, W*0.20, W*0.35],
    header=nerve_rows[0], hbg=C_TEAL))
story.append(sp(4))
story.append(ibox("⚠ FOOT DROP: Due to common fibular nerve injury at fibular neck. Causes: fibula fracture, tight plaster cast, prolonged squatting/leg crossing. HIGH STEPPING GAIT to clear foot off ground."))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 10 – DERMATOMES & SURFACE ANATOMY
# ══════════════════════════════════════════════════════════════════════════════
story.append(banner("10. DERMATOMES, REFLEXES & SURFACE ANATOMY", C_NAVY, "πŸ“"))
story.append(sp(6))

story.append(Paragraph("Key Dermatomes", sSubHead))
derm_rows = [
    ("L1",  "Inguinal ligament region, upper scrotum/labia"),
    ("L2",  "Anterior & medial thigh (femoral triangle)"),
    ("L3",  "Medial thigh, knee region"),
    ("L4",  "Medial leg, medial malleolus, medial foot (big toe side) – 'L4 is on the floor'"),
    ("L5",  "Lateral leg, dorsum of foot, great toe & middle toes (web space 1) – 'L5 walks on 5 toes'"),
    ("S1",  "Lateral border of foot, small toe, heel, sole, posterior calf – S1 = Little toe"),
    ("S2",  "Posterior thigh, back of knee"),
    ("S3–S5","Perianal, perineal region, genitalia"),
]
story.append(two(derm_rows, header=["ROOT", "AREA"], hbg=C_NAVY, w1=0.12))
story.append(sp(6))

story.append(Paragraph("Deep Tendon Reflexes", sSubHead))
story.append(two([
    ("Knee jerk (patellar reflex)",  "L3, L4 – femoral nerve"),
    ("Ankle jerk (Achilles reflex)", "S1, S2 – tibial nerve"),
    ("Plantar reflex",               "S1 – lateral aspect of sole; normal = plantarflexion (down). Babinski sign = dorsiflexion (up) = upper motor neuron lesion"),
], hbg=C_NAVY))
story.append(sp(6))

story.append(Paragraph("Myotomes (Key Movements to Test)", sSubHead))
myo_rows = [
    ("L1–L2", "Hip flexion (iliopsoas)"),
    ("L2–L3", "Hip adduction (adductors)"),
    ("L3–L4", "Knee extension (quadriceps)"),
    ("L4",    "Ankle dorsiflexion (tibialis anterior)"),
    ("L4–L5", "Great toe extension (EHL)"),
    ("L5",    "Hip abduction (gluteus medius); ankle inversion (tibialis posterior)"),
    ("S1",    "Ankle plantarflexion (gastrocnemius-soleus); hip extension (gluteus maximus)"),
    ("S1–S2", "Knee flexion (hamstrings)"),
]
story.append(two(myo_rows, header=["ROOT", "MOVEMENT / MUSCLE"], hbg=C_NAVY, w1=0.15))
story.append(sp(6))

story.append(Paragraph("Important Surface Landmarks", sSubHead))
surf_rows = [
    ("Greater trochanter",  "Lateral hip; ~10 cm below iliac crest; landmark for sciatic nerve & hip injection (upper outer quadrant of buttock)"),
    ("Head of fibula",      "Lateral knee; common fibular nerve winds around it (vulnerable here)"),
    ("Tibial tuberosity",   "Below patella; patellar ligament inserts here; Osgood-Schlatter disease"),
    ("Medial malleolus",    "Medial ankle; tibial nerve, posterior tibial artery, tibialis posterior tendon pass posterior to it"),
    ("Lateral malleolus",   "Fibula; extends 1 cm lower than medial malleolus; lateral ligament complex attaches here"),
    ("Navicular tuberosity","Medial foot; tibialis posterior inserts here; tender in tibialis posterior tendinopathy"),
    ("Femoral pulse",       "Midpoint of inguinal ligament (ASIS to pubic symphysis). Not mid-inguinal point which is mid ASIS to pubic tubercle"),
    ("Popliteal pulse",     "Centre of popliteal fossa; hard to feel (deep); press hard with knee slightly flexed"),
    ("Posterior tibial pulse","Behind medial malleolus"),
    ("Dorsalis pedis pulse","Lateral to EHL tendon on dorsum of foot between MT1 & MT2"),
]
story.append(two(surf_rows, header=["LANDMARK", "DETAILS"], hbg=C_NAVY))
story.append(sp(10))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 11 – CLINICAL HIGH-YIELDS
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(banner("11. CLINICAL HIGH-YIELDS", C_RED, "πŸ₯"))
story.append(sp(6))

clin_rows = [
    ["CLINICAL TOPIC", "ANATOMY BASIS", "KEY POINT"],
    ["Femoral neck fracture",
     "Medial circumflex femoral artery (MCFA) supplies femoral head via retinacular vessels",
     "Intracapsular β†’ disrupts MCFA β†’ avascular necrosis. Garden classification. Extracapsular (intertrochanteric) β†’ lower AVN risk"],
    ["Hip dislocation (posterior)",
     "Posterior capsule is weakest; femoral head displaces posteriorly",
     "Sciatic nerve injury (20%). Hip in flexion, adduction, internal rotation. Emergency reduction within 6 hrs to prevent AVN"],
    ["Knee ligament injuries",
     "ACL most commonly torn in sport. MCL often from lateral blow. Unhappy triad = ACL+MCL+medial meniscus",
     "Anterior drawer/Lachman test (ACL). Valgus stress test (MCL). McMurray test (meniscus). MRI gold standard"],
    ["DVT (Deep Vein Thrombosis)",
     "Deep leg veins, especially calf/popliteal/femoral/iliac. One-way valves + calf muscle pump",
     "Virchow's triad: stasis, hypercoagulability, endothelial damage. Homan's sign unreliable. Wells score + D-dimer + USS Doppler"],
    ["Varicose veins",
     "Saphenofemoral or saphenopopliteal junction incompetence; deep-to-superficial perforator valve failure",
     "GSV most common. Trendelenburg test / Duplex USS. Complications: lipodermatosclerosis, venous ulcers (medial gaiter area – L3–L4 distribution of saphenous nerve)"],
    ["Compartment syndrome",
     "Leg has 4 compartments enclosed by tight fascia. Pressure >30 mmHg or within 30 mmHg of diastolic β†’ ischaemia",
     "6 P's: Pain (on passive stretch), Pressure, Paralysis, Paresthesia, Pallor, Pulselessness. Emergency fasciotomy of ALL 4 compartments"],
    ["Foot drop",
     "Common fibular nerve at fibular neck (L4–S2); drops at foot, loss of dorsiflexion + eversion",
     "High stepping gait. Test: active dorsiflexion. EMG/NCS to localise. Splint + investigate cause (plaster cast, fracture, nerve compression)"],
    ["Sciatica",
     "L4/L5/S1/S2/S3 roots forming sciatic nerve; most commonly L4–L5 disc prolapse or L5–S1 prolapse",
     "Straight leg raise test (SLR) positive at 30–70Β°. L4–L5 disc: L5 root β†’ EHL weakness, L4–L5 dermatomal loss. L5–S1: S1 root β†’ absent ankle jerk, S1 loss"],
    ["Meralgia paraesthetica",
     "Lateral femoral cutaneous nerve (L2–L3) compressed at ASIS under inguinal ligament",
     "Burning/tingling lateral thigh; no weakness; common in obesity, tight belts, pregnancy. Conservative usually resolves"],
    ["Plantar fasciitis",
     "Plantar aponeurosis from calcaneal tuberosity; windlass mechanism",
     "Heel pain worst in morning (first steps). Calcaneal spur on X-ray (incidental). Treatment: stretching, orthotics, steroid injection"],
    ["Achilles tendon rupture",
     "Triceps surae via Achilles (calcaneal) tendon; watershed zone 2–6 cm above insertion",
     "Thompson/Simmonds test. Gap palpable. Management: conservative (cast) or surgical repair; surgical has lower re-rupture rate"],
    ["Posterior tibial tendon dysfunction",
     "Tibialis posterior tendon main support of medial arch",
     "'Too many toes' sign; acquired flat foot; progressive collapse. Stages I–IV. Manage with orthotics then reconstruction/fusion"],
]
ct = Table(clin_rows, colWidths=[W*0.20, W*0.32, W*0.48])
ct.setStyle(TableStyle([
    ("BACKGROUND",    (0,0),(-1,0), C_RED),
    ("TEXTCOLOR",     (0,0),(-1,0), WHITE),
    ("FONTNAME",      (0,0),(-1,0), "Helvetica-Bold"),
    ("FONTSIZE",      (0,0),(-1,-1), 7.5),
    ("GRID",          (0,0),(-1,-1), 0.4, colors.HexColor("#CCCCCC")),
    ("ROWBACKGROUNDS",(0,1),(-1,-1), [WHITE, C_LGRAY]),
    ("TOPPADDING",    (0,0),(-1,-1), 4),
    ("BOTTOMPADDING", (0,0),(-1,-1), 4),
    ("LEFTPADDING",   (0,0),(-1,-1), 5),
    ("ALIGN",         (0,0),(-1,-1), "LEFT"),
    ("VALIGN",        (0,0),(-1,-1), "TOP"),
]))
story.append(ct)
story.append(sp(10))

# ── MNEMONICS ─────────────────────────────────────────────────────────────────
story.append(banner("MNEMONICS & MEMORY AIDS", colors.HexColor("#2A1A50")))
story.append(sp(6))
mnems = [
    ("<b>Femoral triangle contents (NAVEL – lateral β†’ medial):</b>  Nerve, Artery, Vein, Empty space (femoral canal), Lymphatics"),
    ("<b>Deep 6 lateral rotators of hip:</b>  'Please Go On Giving Good Outcomes' = Piriformis, Gemellus superior, Obturator internus, Gemellus inferior, Obturator externus, Quadratus femoris"),
    ("<b>Pes anserinus (medial tibia):</b>  'Say Grace before Tea' = Sartorius, Gracilis, Semitendinosus"),
    ("<b>Tarsal tunnel contents (medial malleolus order):</b>  'Tom, Dick And Very Nervous Harry' = Tibialis posterior, flexor Digitorum longus, posterior tibial Artery, tibial Vein, tibial Nerve, flexor Hallucis longus"),
    ("<b>Dermatomes quick guide:</b>  L4 = kneeling on the floor (medial malleolus, big toe). L5 = standing on 5 toes (1st web space dorsum). S1 = sitting on the sole (sole, heel, little toe)"),
    ("<b>Dorsiflexors of ankle (deep fibular nerve):</b>  'The Ecstatic Elephants Fight Pretty Hard' = Tibialis anterior, EDL, EHL, Fibularis tertius, Popliteus (deep leg muscles – bonus)"),
    ("<b>Unhappy triad of knee:</b>  ACL + MCL + Medial meniscus (MCL attached to medial meniscus = both torn together by lateral blow)"),
    ("<b>Anterior tibial artery β†’ Dorsalis pedis:</b>  Passes between EHL and EDL on dorsum of foot; feel pulse lateral to EHL tendon between MT1 and MT2"),
    ("<b>Reflexes:</b>  S1, 2 buckle my shoe (Achilles). L3, 4 kick the door (knee jerk). L1, 2 squeeze the tube (cremasteric). C5, 6 pick up sticks (biceps). C7, 8 open the gate (triceps)"),
    ("<b>Compartments of leg (4):</b>  'ALPS' = Anterior (deep fibular n., tibialis ant., EDL, EHL), Lateral (superficial fibular n., fibularis longus & brevis), Posterior-superficial (gastrocnemius, soleus), Posterior-deep (tibial n., tibialis post., FDL, FHL)"),
]
for m in mnems:
    story.append(Paragraph(f"β€’ {m}", S("mb", fontSize=8.8, fontName="Helvetica",
                                        textColor=C_DGRAY, leftIndent=14, spaceAfter=3, leading=13)))
story.append(sp(6))

# ── FOOTER ────────────────────────────────────────────────────────────────────
story.append(HRFlowable(width=W, thickness=1, color=C_LGRAY))
story.append(sp(4))
story.append(Paragraph(
    "Lower Limb Anatomy Quick Revision  |  Based on Gray's Anatomy for Students, Chapters 6 & 7  |  Generated by Orris Medical AI",
    sFooter))

def on_page(canvas, doc):
    canvas.saveState()
    canvas.setFont("Helvetica", 8)
    canvas.setFillColor(colors.HexColor("#AAAAAA"))
    canvas.drawRightString(A4[0] - 1.5*cm, 1.0*cm, f"Page {doc.page}")
    canvas.drawString(1.5*cm, 1.0*cm, "Lower Limb Anatomy Quick Revision")
    canvas.restoreState()

doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print("PDF generated:", OUTPUT)
Running Command

cd /home/daytona/workspace/lower-limb-anatomy && python generate_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/lower-limb-anatomy/Lower_Limb_Anatomy_Quick_Revision.pdf

Your Lower Limb PDF is ready! Download it here:

Lower Limb Anatomy Quick Revision

PDF Document Β· PDF


What's inside (6 pages, color-coded):

SectionColorContents
1. Bones & LandmarksNavyAll 7 bones with key landmarks, angles (Q-angle, neck-shaft angle, tibiofemoral angle), clinical relevance
2. JointsGreenHip joint (ligaments, blood supply, AVN risk), knee joint (cruciate & collateral ligaments, menisci, Unhappy Triad), ankle (deltoid vs lateral ligaments), subtalar & foot joints
3. Gluteal RegionOrangeAll 10 gluteal muscles (origin/insertion/nerve/action), Deep 6 lateral rotators, greater sciatic foramen contents, Trendelenburg sign
4. ThighPurpleAll anterior/medial/posterior compartment muscles (full tables), femoral triangle (NAVEL), adductor canal, pes anserinus
5. Knee & Popliteal FossaTealPopliteal fossa boundaries/contents, Baker's cyst, popliteus muscle (unlocking mechanism)
6. LegRedAll 4 compartments – anterior (dorsiflexors), lateral (evertors), posterior superficial (triceps surae + Achilles), posterior deep (Tom Dick And Very Nervous Harry)
7. FootMaroon4 layers of intrinsic muscles, 3 arches with supports, plantar aponeurosis, tarsal tunnel, flat foot vs pes cavus
8. Blood VesselsBlueFull arterial tree (femoral β†’ profunda β†’ popliteal β†’ tibial β†’ dorsalis pedis), cruciate & genicular anastomoses, GSV/SSV venous drainage
9. NervesTealComplete nerve table (10 nerves): roots, course, motor, sensory, and clinical injury pattern for each
10. Dermatomes & Surface AnatomyNavyL1–S5 dermatomes, knee/ankle reflexes, myotomes, all palpable pulses & landmarks
11. Clinical High-YieldsRed12 cases: femoral neck fracture, DVT, compartment syndrome, foot drop, sciatica, plantar fasciitis, Achilles rupture, etc.
MnemonicsDeep Purple10 memory aids including NAVEL, Deep 6, Tom Dick, ALPS compartments, dermatome rhymes
This is a shared conversation. Sign in to Orris to start your own chat.