Make me pdf on anatomy of lower limb venous drainage

Reading File
Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Finding Sources
Reading File
Reading File
Finding Sources
Reading File
Finding Sources
Reading File
Running Command

ls -la /home/daytona/workspace/ 2>/dev/null || mkdir -p /home/daytona/workspace && echo "created"

Running Command

mkdir -p /home/daytona/workspace/lower-limb-venous && python3 -c "from reportlab.lib.pagesizes import A4; print('reportlab ok')"

Writing File

~/lower-limb-venous/build_pdf.py

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

OUTPUT = "/home/daytona/workspace/lower-limb-venous/Lower_Limb_Venous_Drainage.pdf"

# ── COLORS ──────────────────────────────────────────────────────────
DARK_BLUE   = colors.HexColor("#1A3A5C")
MID_BLUE    = colors.HexColor("#2E6DA4")
LIGHT_BLUE  = colors.HexColor("#D6E8F7")
ACCENT      = colors.HexColor("#E84545")
GOLD        = colors.HexColor("#C8990A")
LIGHT_GRAY  = colors.HexColor("#F4F6F9")
BORDER_GRAY = colors.HexColor("#CCCCCC")
WHITE       = colors.white

# ── STYLES ───────────────────────────────────────────────────────────
base = getSampleStyleSheet()

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

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

SUBTITLE_STYLE = S("Subtitle",
    fontName="Helvetica", fontSize=14, textColor=LIGHT_BLUE,
    alignment=TA_CENTER, leading=18, spaceAfter=6)

META_STYLE = S("Meta",
    fontName="Helvetica-Oblique", fontSize=10, textColor=LIGHT_BLUE,
    alignment=TA_CENTER, leading=14)

H1 = S("H1",
    fontName="Helvetica-Bold", fontSize=15, textColor=WHITE,
    leading=18, spaceAfter=4, spaceBefore=8,
    backColor=DARK_BLUE, borderPad=6,
    leftIndent=-12, rightIndent=-12)

H2 = S("H2",
    fontName="Helvetica-Bold", fontSize=12, textColor=DARK_BLUE,
    leading=15, spaceBefore=10, spaceAfter=3,
    borderPad=0)

H3 = S("H3",
    fontName="Helvetica-BoldOblique", fontSize=11, textColor=MID_BLUE,
    leading=14, spaceBefore=8, spaceAfter=2)

BODY = S("Body",
    fontName="Helvetica", fontSize=10, textColor=colors.HexColor("#222222"),
    leading=15, spaceAfter=6, alignment=TA_JUSTIFY)

BULLET = S("Bullet",
    fontName="Helvetica", fontSize=10, textColor=colors.HexColor("#222222"),
    leading=14, spaceAfter=3, leftIndent=14, bulletIndent=4,
    alignment=TA_LEFT)

CAPTION = S("Caption",
    fontName="Helvetica-Oblique", fontSize=9, textColor=colors.HexColor("#555555"),
    leading=12, spaceAfter=4, alignment=TA_CENTER)

BOX_TEXT = S("BoxText",
    fontName="Helvetica", fontSize=10, textColor=DARK_BLUE,
    leading=14, spaceAfter=3, leftIndent=6)

BOX_TITLE = S("BoxTitle",
    fontName="Helvetica-Bold", fontSize=11, textColor=DARK_BLUE,
    leading=14, spaceAfter=4, leftIndent=6)

FOOTER_STYLE = S("Footer",
    fontName="Helvetica-Oblique", fontSize=8, textColor=colors.HexColor("#888888"),
    alignment=TA_CENTER)

TABLE_HEADER = S("TableHeader",
    fontName="Helvetica-Bold", fontSize=10, textColor=WHITE,
    alignment=TA_CENTER, leading=13)

TABLE_CELL = S("TableCell",
    fontName="Helvetica", fontSize=9, textColor=colors.HexColor("#222222"),
    alignment=TA_LEFT, leading=13)

TABLE_CELL_C = S("TableCellC",
    fontName="Helvetica", fontSize=9, textColor=colors.HexColor("#222222"),
    alignment=TA_CENTER, leading=13)

# ── HELPERS ──────────────────────────────────────────────────────────
def section_header(text):
    """Full-width colored section header band."""
    return Table(
        [[Paragraph(text, H1)]],
        colWidths=[17.5*cm],
        style=TableStyle([
            ("BACKGROUND", (0,0), (-1,-1), DARK_BLUE),
            ("LEFTPADDING",  (0,0), (-1,-1), 12),
            ("RIGHTPADDING", (0,0), (-1,-1), 12),
            ("TOPPADDING",   (0,0), (-1,-1), 6),
            ("BOTTOMPADDING",(0,0), (-1,-1), 6),
            ("ROUNDEDCORNERS", [4]),
        ])
    )

def info_box(title, items, color=LIGHT_BLUE):
    """Shaded info box with bullet items."""
    rows = [[Paragraph(title, BOX_TITLE)]]
    for item in items:
        rows.append([Paragraph(f"• {item}", BOX_TEXT)])
    t = Table(rows, colWidths=[16.5*cm])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), color),
        ("LEFTPADDING",  (0,0), (-1,-1), 10),
        ("RIGHTPADDING", (0,0), (-1,-1), 10),
        ("TOPPADDING",   (0,0), (-1,-1), 6),
        ("BOTTOMPADDING",(0,0), (-1,-1), 4),
        ("LINEABOVE",   (0,0), (-1,0), 2, MID_BLUE),
        ("BOX",         (0,0), (-1,-1), 1, BORDER_GRAY),
    ]))
    return t

def highlight_box(title, body_text, bg=LIGHT_BLUE, border=MID_BLUE):
    rows = [
        [Paragraph(title, BOX_TITLE)],
        [Paragraph(body_text, BOX_TEXT)],
    ]
    t = Table(rows, colWidths=[16.5*cm])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), bg),
        ("LEFTPADDING",  (0,0), (-1,-1), 10),
        ("RIGHTPADDING", (0,0), (-1,-1), 10),
        ("TOPPADDING",   (0,0), (-1,-1), 6),
        ("BOTTOMPADDING",(0,0), (-1,-1), 6),
        ("LINEABOVE",   (0,0), (-1,0), 2, border),
        ("BOX",         (0,0), (-1,-1), 1, border),
    ]))
    return t

def two_col_table(left_items, right_items, left_title, right_title):
    """Two column comparison table."""
    header = [Paragraph(left_title, TABLE_HEADER), Paragraph(right_title, TABLE_HEADER)]
    rows = [header]
    max_len = max(len(left_items), len(right_items))
    for i in range(max_len):
        l = Paragraph(f"• {left_items[i]}", TABLE_CELL) if i < len(left_items) else Paragraph("", TABLE_CELL)
        r = Paragraph(f"• {right_items[i]}", TABLE_CELL) if i < len(right_items) else Paragraph("", TABLE_CELL)
        rows.append([l, r])
    t = Table(rows, colWidths=[8.5*cm, 8.5*cm])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0), (-1,0), DARK_BLUE),
        ("BACKGROUND",   (0,1), (-1,-1), LIGHT_GRAY),
        ("ROWBACKGROUNDS",(0,1),(-1,-1),[LIGHT_GRAY, WHITE]),
        ("LEFTPADDING",  (0,0), (-1,-1), 8),
        ("RIGHTPADDING", (0,0), (-1,-1), 8),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
        ("BOX",          (0,0), (-1,-1), 1, BORDER_GRAY),
        ("INNERGRID",    (0,0), (-1,-1), 0.5, BORDER_GRAY),
        ("VALIGN",       (0,0), (-1,-1), "TOP"),
    ]))
    return t

def data_table(headers, rows_data, col_widths=None):
    all_rows = [[Paragraph(h, TABLE_HEADER) for h in headers]]
    for row in rows_data:
        all_rows.append([Paragraph(str(c), TABLE_CELL) for c in row])
    if col_widths is None:
        col_widths = [17.5*cm/len(headers)]*len(headers)
    t = Table(all_rows, colWidths=col_widths)
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0), (-1,0), DARK_BLUE),
        ("ROWBACKGROUNDS",(0,1),(-1,-1),[LIGHT_GRAY, WHITE]),
        ("LEFTPADDING",  (0,0), (-1,-1), 7),
        ("RIGHTPADDING", (0,0), (-1,-1), 7),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
        ("BOX",          (0,0), (-1,-1), 1, BORDER_GRAY),
        ("INNERGRID",    (0,0), (-1,-1), 0.5, BORDER_GRAY),
        ("VALIGN",       (0,0), (-1,-1), "TOP"),
    ]))
    return t

# ── COVER PAGE ───────────────────────────────────────────────────────
def cover_page():
    story = []

    # Blue banner
    cover_table = Table(
        [[Paragraph("ANATOMY OF", SUBTITLE_STYLE),],
         [Paragraph("Lower Limb Venous Drainage", TITLE_STYLE)],
         [Paragraph("A Comprehensive Anatomical Reference", SUBTITLE_STYLE)],
         [Spacer(1, 8)],
         [Paragraph("Based on Gray's Anatomy for Students • Bailey &amp; Love's Surgery • Schwartz's Surgery", META_STYLE)],
        ],
        colWidths=[17.5*cm],
        rowHeights=[18, 50, 24, 10, 16]
    )
    cover_table.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), DARK_BLUE),
        ("LEFTPADDING",  (0,0), (-1,-1), 20),
        ("RIGHTPADDING", (0,0), (-1,-1), 20),
        ("TOPPADDING",   (0,0), (-1,-1), 20),
        ("BOTTOMPADDING",(0,0), (-1,-1), 16),
        ("VALIGN",       (0,0), (-1,-1), "MIDDLE"),
    ]))
    story.append(cover_table)
    story.append(Spacer(1, 18))

    # TOC box
    toc_items = [
        ("1", "Overview & Classification of Venous System"),
        ("2", "Superficial Venous System"),
        ("3", "Great Saphenous Vein (GSV)"),
        ("4", "Small Saphenous Vein (SSV)"),
        ("5", "Deep Venous System"),
        ("6", "Perforating (Communicating) Veins"),
        ("7", "Venous Valves & Hemodynamics"),
        ("8", "Venous Drainage Pathway Summary"),
        ("9", "Clinical Correlations"),
        ("10", "Key Anatomical Landmarks"),
    ]
    toc_rows = [[Paragraph("CONTENTS", TABLE_HEADER), Paragraph("SECTION", TABLE_HEADER)]]
    for num, title in toc_items:
        toc_rows.append([
            Paragraph(num, TABLE_CELL_C),
            Paragraph(title, TABLE_CELL)
        ])
    toc_t = Table(toc_rows, colWidths=[1.5*cm, 16*cm])
    toc_t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), MID_BLUE),
        ("ROWBACKGROUNDS",(0,1),(-1,-1),[LIGHT_GRAY, WHITE]),
        ("LEFTPADDING",   (0,0), (-1,-1), 8),
        ("RIGHTPADDING",  (0,0), (-1,-1), 8),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("BOX",           (0,0), (-1,-1), 1, BORDER_GRAY),
        ("INNERGRID",     (0,0), (-1,-1), 0.5, BORDER_GRAY),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("ALIGN",         (0,0), (0,-1), "CENTER"),
    ]))
    story.append(toc_t)
    story.append(Spacer(1, 16))

    # Bottom bar
    story.append(HRFlowable(width="100%", thickness=2, color=MID_BLUE))
    story.append(Spacer(1, 4))
    story.append(Paragraph("Medical Anatomy Series  |  Prepared May 2026", FOOTER_STYLE))
    story.append(PageBreak())
    return story

# ── BUILD STORY ──────────────────────────────────────────────────────
def build_story():
    s = []

    # ── COVER ──
    s += cover_page()

    # ═══════════════════════════════════════════════════════════════
    # SECTION 1: OVERVIEW
    # ═══════════════════════════════════════════════════════════════
    s.append(section_header("1.  Overview & Classification"))
    s.append(Spacer(1, 8))

    s.append(Paragraph("Introduction", H2))
    s.append(Paragraph(
        "The venous system of the lower limb is responsible for returning deoxygenated blood "
        "from the tissues of the foot, leg, and thigh back to the heart. It is divided into three "
        "interconnected compartments: <b>superficial veins</b>, <b>deep veins</b>, and <b>perforating "
        "(communicating) veins</b>. Together these form a precisely valved network that works against "
        "gravity to propel blood cephalad.", BODY))

    s.append(Paragraph("The Three-Compartment Classification", H2))
    class_data = [
        ["Superficial Veins",
         "Lie above the deep fascia (superficial to fascia lata). Include the Great Saphenous Vein (GSV) and Small Saphenous Vein (SSV) and their tributaries.",
         "Varicose veins, SFJ/SPJ incompetence"],
        ["Deep Veins",
         "Travel with named arteries beneath the deep fascia. Include tibial, peroneal, popliteal, femoral, and iliac veins.",
         "Deep vein thrombosis (DVT)"],
        ["Perforating Veins",
         "Connect superficial to deep system, piercing the deep fascia. Valves normally permit one-way flow: superficial → deep.",
         "Venous ulcers, CVI"],
    ]
    s.append(data_table(
        ["System", "Description", "Clinical Relevance"],
        class_data,
        col_widths=[3.5*cm, 9.5*cm, 4.5*cm]
    ))
    s.append(Spacer(1, 10))

    s.append(highlight_box(
        "Key Functional Concept",
        "The venous system contains approximately 60% of the total blood volume at an average "
        "pressure of 5–10 mmHg. The muscle pump mechanism (particularly the calf muscle pump) "
        "and competent venous valves are the two primary drivers of venous return from the lower limb.",
        bg=colors.HexColor("#EAF4FB"), border=MID_BLUE
    ))
    s.append(Spacer(1, 12))

    # ═══════════════════════════════════════════════════════════════
    # SECTION 2: SUPERFICIAL SYSTEM
    # ═══════════════════════════════════════════════════════════════
    s.append(section_header("2.  Superficial Venous System"))
    s.append(Spacer(1, 8))

    s.append(Paragraph(
        "The superficial venous system lies above the uppermost fascial layer of the leg and thigh. "
        "It drains the skin and subcutaneous tissues. Crucially, both major superficial trunks "
        "lie within the 'saphenous envelope' — a compartment formed by the deep fascia below "
        "and the saphenous fascia (a condensation of superficial fascia) above. This anatomical "
        "relationship is important in surgical mapping with duplex ultrasound.", BODY))

    s.append(Paragraph("Dorsal Venous Arch — The Origin", H2))
    s.append(Paragraph(
        "As the sole of the foot is subject to significant mechanical pressure during ambulation, "
        "the majority of venous drainage of the foot is routed into the <b>dorsal venous arch</b>, "
        "which runs in the subcutaneous tissues over the metatarsal heads. This arch is the "
        "common origin for both the great and small saphenous veins:", BODY))

    s.append(info_box("Dorsal Venous Arch", [
        "Lies subcutaneously over the dorsum of the foot, at the level of the metatarsal heads.",
        "Medial end → gives rise to the Great Saphenous Vein (GSV).",
        "Lateral end → gives rise to the Small Saphenous Vein (SSV) via the lateral marginal vein.",
        "Communicates with the plantar venous plexus through inter-metatarsal spaces.",
    ], color=LIGHT_BLUE))
    s.append(Spacer(1, 10))

    # ═══════════════════════════════════════════════════════════════
    # SECTION 3: GREAT SAPHENOUS VEIN
    # ═══════════════════════════════════════════════════════════════
    s.append(section_header("3.  Great Saphenous Vein (GSV)"))
    s.append(Spacer(1, 8))

    s.append(Paragraph("Overview", H2))
    s.append(Paragraph(
        "The <b>Great Saphenous Vein</b> is the longest vein in the body and the most frequently "
        "affected vessel in superficial venous incompetence. It originates from the medial end "
        "of the dorsal venous arch (also called the dorsal pedal venous arch) and travels the "
        "entire length of the medial lower limb before draining into the femoral venous system "
        "at the groin.", BODY))

    s.append(Paragraph("Course — Foot to Groin", H2))
    course_gsv = [
        ["Foot", "Originates from medial end of dorsal venous arch. Ascends anterior to the medial malleolus."],
        ["Medial leg", "Ascends along medial aspect of leg, accompanied by the saphenous nerve (branch of femoral nerve). Lies medial to the tibia in the superficial tissues."],
        ["Knee", "Loops posteriorly at the level of the medial condyle of the femur (posterior knee) before continuing superiorly."],
        ["Thigh", "Courses medially in the superficial tissues of the medial thigh, running anterolateral to the GSV axis (AAGSV may be confused with GSV here)."],
        ["Groin / SFJ", "Passes through the saphenous opening (cribriform fascia) approximately 2.5–4 cm below and lateral to the pubic tubercle. Terminates in the common femoral vein at the saphenofemoral junction (SFJ)."],
    ]
    s.append(data_table(
        ["Region", "Description"],
        course_gsv,
        col_widths=[3.5*cm, 14*cm]
    ))
    s.append(Spacer(1, 8))

    s.append(Paragraph("Tributaries of the GSV at the Saphenofemoral Junction (SFJ)", H2))
    s.append(Paragraph(
        "Just before piercing the cribriform fascia at the saphenous opening, the GSV unites "
        "with several tributaries corresponding to branches of the common femoral artery. "
        "These are surgically important and must be ligated at high ligation:", BODY))
    s.append(info_box("GSV Tributaries Near SFJ", [
        "Superficial epigastric vein (drains lower abdominal wall superiorly)",
        "Superficial circumflex iliac vein (drains lateral hip/groin region)",
        "Superficial external pudendal vein (drains external genitalia)",
        "Deep external pudendal vein (occasionally joins the GSV or CFV directly)",
        "Anterior accessory GSV (AAGSV) — common tributary, may be mistaken for the GSV trunk",
    ], color=LIGHT_BLUE))
    s.append(Spacer(1, 6))

    s.append(Paragraph("Nerve Relationship", H2))
    s.append(Paragraph(
        "The <b>saphenous nerve</b> (terminal branch of the femoral nerve, L3–L4) accompanies the "
        "GSV from the medial knee to the ankle. It supplies cutaneous sensation to the medial "
        "side of the knee, leg, and medial border of the foot. This relationship has important "
        "surgical implications — the nerve is at risk of injury during GSV stripping, "
        "phlebectomy, or thermal ablation below the knee.", BODY))
    s.append(Spacer(1, 10))

    # ═══════════════════════════════════════════════════════════════
    # SECTION 4: SMALL SAPHENOUS VEIN
    # ═══════════════════════════════════════════════════════════════
    s.append(section_header("4.  Small Saphenous Vein (SSV)"))
    s.append(Spacer(1, 8))

    s.append(Paragraph("Overview", H2))
    s.append(Paragraph(
        "The <b>Small Saphenous Vein</b> (also called the short saphenous vein) originates from "
        "the lateral end of the dorsal venous arch, travels posteriorly around the lateral "
        "malleolus, and ascends through the posterior calf to typically terminate in the popliteal "
        "vein. Its termination is highly variable, making preoperative imaging mandatory.", BODY))

    s.append(Paragraph("Course", H2))
    course_ssv = [
        ["Foot", "Originates from lateral marginal vein / lateral end of dorsal venous arch."],
        ["Ankle", "Passes posterior to the lateral malleolus, accompanied by the sural nerve. Lies lateral to the calcaneal tendon."],
        ["Posterior calf", "Ascends in the posterior midline of the leg. In the proximal calf it sits in the groove between the medial and lateral heads of gastrocnemius."],
        ["Popliteal fossa", "Commonly pierces the popliteal fossa fascia to drain into the popliteal vein at the saphenopopliteal junction (SPJ). Termination level is highly variable — may be mid-calf to above the knee."],
    ]
    s.append(data_table(
        ["Region", "Description"],
        course_ssv,
        col_widths=[3.5*cm, 14*cm]
    ))
    s.append(Spacer(1, 8))

    s.append(Paragraph("Variations of SSV Termination", H2))
    s.append(info_box("SSV Termination Variants", [
        "Classic (most common): Drains into popliteal vein at the SPJ in the popliteal fossa.",
        "Low termination: SPJ below the popliteal crease (down to mid-calf level).",
        "Cranial extension of SSV: SSV extends cranially beyond the SPJ, piercing the fascia of the posterior thigh to drain into the deep system.",
        "Giacomini vein (thigh extension): SSV extends as the 'vein of Giacomini' to communicate with the GSV system — may join the GSV near the SFJ.",
        "No popliteal fossa termination: SSV continues entirely as described above without draining into the popliteal vein.",
    ], color=LIGHT_BLUE))
    s.append(Spacer(1, 8))

    s.append(Paragraph("Nerve Relationship", H2))
    s.append(Paragraph(
        "The <b>sural nerve</b> accompanies the SSV along the posterior calf and lateral malleolus. "
        "It supplies cutaneous sensation to the lateral malleolar region and lateral foot. "
        "The nerve is at risk during SSV stripping or phlebectomy.", BODY))
    s.append(Spacer(1, 10))

    # ═══════════════════════════════════════════════════════════════
    # SECTION 5: DEEP VENOUS SYSTEM
    # ═══════════════════════════════════════════════════════════════
    s.append(section_header("5.  Deep Venous System"))
    s.append(Spacer(1, 8))

    s.append(Paragraph(
        "The deep veins lie beneath the deep fascia and travel with named arteries as venae comitantes "
        "(paired companion veins). They carry the majority (~85–90%) of venous blood returning from "
        "the lower limb. From distal to proximal:", BODY))

    s.append(Paragraph("Foot & Ankle", H2))
    s.append(Paragraph(
        "The plantar venous arch and deep plantar digital veins drain the sole of the foot. "
        "These communicate with the dorsal venous arch and form the medial and lateral plantar veins, "
        "which accompany the plantar arteries.", BODY))

    s.append(Paragraph("Leg (Calf) Deep Veins", H2))
    s.append(Paragraph(
        "In the lower leg there are <b>three pairs of venae comitantes</b> accompanying the three "
        "crural arteries. These six veins intercommunicate via venous bridges:", BODY))
    leg_deep = [
        ["Anterior tibial veins (×2)", "Accompany anterior tibial artery in the anterior compartment. Pass superior to the interosseous membrane to join the popliteal vein."],
        ["Posterior tibial veins (×2)", "Accompany posterior tibial artery deep to the soleus. Most clinically significant for DVT in the calf. Receive the peroneal veins and drain into the popliteal vein."],
        ["Peroneal (fibular) veins (×2)", "Accompany peroneal artery in the deep posterior compartment. Drain into the posterior tibial or directly into the popliteal vein."],
    ]
    s.append(data_table(
        ["Vein", "Course & Drainage"],
        leg_deep,
        col_widths=[5*cm, 12.5*cm]
    ))
    s.append(Spacer(1, 6))

    s.append(info_box("Muscular/Sinusoidal Veins of the Calf", [
        "Soleal sinuses: Large, thin-walled venous sinuses within the soleus muscle. Major site of DVT origin. Drain into posterior tibial and peroneal veins.",
        "Gastrocnemius veins: Paired veins within each head of gastrocnemius. Drain directly into the popliteal vein.",
        "These intramuscular sinusoidal veins act as a 'venous reservoir' and are compressed by calf muscle contraction (calf muscle pump).",
    ], color=colors.HexColor("#EAF4FB")))
    s.append(Spacer(1, 8))

    s.append(Paragraph("Popliteal Vein", H2))
    s.append(Paragraph(
        "The six crural veins (anterior tibial, posterior tibial, and peroneal, paired) intercommunicate "
        "and converge in the popliteal fossa to form the <b>popliteal vein</b>. It also receives the "
        "soleal and gastrocnemius veins, and the SSV at the SPJ. The popliteal vein lies superficial "
        "and lateral to the popliteal artery in the popliteal fossa.", BODY))

    s.append(Paragraph("Femoral & Common Femoral Veins", H2))
    s.append(Paragraph(
        "The popliteal vein passes through the adductor hiatus (hiatus in adductor magnus) to enter "
        "the subsartorial (adductor) canal as the <b>femoral vein</b>. In the femoral triangle, it "
        "receives the <b>deep (profunda) femoral vein</b> to form the <b>common femoral vein (CFV)</b>. "
        "The femoral vein runs medial to the femoral artery within the femoral sheath.", BODY))

    s.append(Paragraph("Iliac & Caval System", H2))
    iliac_data = [
        ["Common femoral vein", "Formed by femoral vein + deep femoral vein in femoral triangle. GSV joins here at SFJ (~4 cm below and lateral to pubic tubercle)."],
        ["External iliac vein", "Continuation of CFV posterior to the inguinal ligament. Joins internal iliac vein to form common iliac vein."],
        ["Internal iliac vein", "Drains pelvic viscera and gluteal region. Joins external iliac at the pelvic brim."],
        ["Common iliac veins", "Right and left common iliac veins join at the right side of L5 vertebral body. Left common iliac vein passes posterior to the right common iliac artery (May-Thurner anatomy)."],
        ["Inferior vena cava (IVC)", "Formed by junction of two common iliac veins. Ascends to the right side of the aorta to drain into the right atrium. Valveless."],
    ]
    s.append(data_table(
        ["Vessel", "Key Points"],
        iliac_data,
        col_widths=[5*cm, 12.5*cm]
    ))
    s.append(Spacer(1, 10))

    # ═══════════════════════════════════════════════════════════════
    # SECTION 6: PERFORATING VEINS
    # ═══════════════════════════════════════════════════════════════
    s.append(section_header("6.  Perforating (Communicating) Veins"))
    s.append(Spacer(1, 8))

    s.append(Paragraph(
        "Perforating veins (also called communicating veins or perforators) traverse the deep fascia "
        "and connect the superficial and deep venous systems. They are distributed throughout the "
        "calf and thigh at inconstant anatomical sites. Each perforator is guarded by a valve that "
        "normally directs blood from superficial → deep.", BODY))

    s.append(Paragraph("Named and Clinically Important Perforators", H2))
    perf_data = [
        ["Cockett perforators\n(posterior tibial / paratibial)", "Medial lower leg", "3 perforators (~7.5, 13.5, 18.5 cm from floor). Connect posterior arch vein or GSV to posterior tibial veins. Most common site of perforator incompetence in venous ulcers."],
        ["Boyd perforator\n(paratibial)", "Medial upper calf (~10 cm below knee)", "Connects GSV or its tributaries to posterior tibial veins."],
        ["Dodd perforator\n(mid-thigh)", "Medial mid-thigh", "Connects GSV to the femoral vein in the adductor canal."],
        ["Hunterian perforator", "Medial upper thigh", "Connects GSV to femoral vein."],
        ["Gastrocnemius point perforators", "Posterior calf", "Connect SSV/posterior arch vein to gastrocnemius veins."],
        ["Soleal (intramuscular)", "Posterior lower leg", "Connect deep soleal sinuses to peroneal or posterior tibial veins."],
        ["Lateral leg perforators", "Lateral calf", "Connect lateral tributaries to peroneal veins; less clinically significant."],
    ]
    s.append(data_table(
        ["Perforator", "Location", "Connections"],
        perf_data,
        col_widths=[4.5*cm, 3.5*cm, 9.5*cm]
    ))
    s.append(Spacer(1, 8))

    s.append(highlight_box(
        "Perforator Incompetence",
        "When perforator valves fail, blood refluxes from the high-pressure deep system into the "
        "superficial veins (outward flow). This creates sustained venous hypertension in the skin "
        "and subcutaneous tissues of the medial ankle ('gaiter area'), contributing to lipodermatosclerosis "
        "and venous ulceration — the classic CEAP C6 presentation.",
        bg=colors.HexColor("#FEF3F3"), border=ACCENT
    ))
    s.append(Spacer(1, 10))

    # ═══════════════════════════════════════════════════════════════
    # SECTION 7: VALVES & HEMODYNAMICS
    # ═══════════════════════════════════════════════════════════════
    s.append(section_header("7.  Venous Valves & Hemodynamics"))
    s.append(Spacer(1, 8))

    s.append(Paragraph("Valve Anatomy", H2))
    s.append(Paragraph(
        "Each venous valve consists of <b>two thin cusps</b> of fine connective tissue covered by "
        "endothelium. Valves close in response to cephalad-to-caudal (retrograde) blood flow "
        "at a velocity of at least 30 cm/s. Valves are more numerous distally — there are "
        "more valves in the calf veins than in the femoral or iliac veins. The IVC, common "
        "iliac veins, portal venous system, and cranial sinuses are valveless.", BODY))

    s.append(Paragraph("Valve Distribution", H2))
    valve_data = [
        ["Tibial veins (anterior & posterior)", "10–15 valves per segment"],
        ["Peroneal veins", "8–12 valves"],
        ["Popliteal vein", "1–3 valves"],
        ["Femoral vein", "2–4 valves"],
        ["Common femoral vein", "0–1 valve (often absent)"],
        ["External iliac vein", "Usually absent"],
        ["Common iliac vein", "Absent"],
        ["Inferior vena cava", "Absent (valveless)"],
        ["GSV", "Multiple (10–20 along its course)"],
        ["SSV", "6–12 valves"],
    ]
    s.append(data_table(
        ["Vessel", "Approximate Valve Count"],
        valve_data,
        col_widths=[9*cm, 8.5*cm]
    ))
    s.append(Spacer(1, 8))

    s.append(Paragraph("Mechanisms of Venous Return", H2))
    s.append(info_box("Venous Return Mechanisms", [
        "Calf muscle pump: Contraction of soleus and gastrocnemius compresses intramuscular sinuses and deep veins, propelling blood proximally. Valves prevent reflux on relaxation. Most important mechanism during ambulation.",
        "Foot pump: Compression of plantar venous plexus during heel strike propels blood into the deep calf veins.",
        "Respiratory variation: Inspiration decreases intrathoracic pressure, creating a pressure gradient that aids venous return from the IVC.",
        "Cardiac suction (vis a fronte): Right atrial diastole creates slight suction aiding venous flow.",
        "Abdominal/muscular compression: Contraction of abdominal and thigh muscles contributes to proximal flow.",
        "Residual arterial pressure: Some kinetic energy transmitted from arterial side drives capillary flow into venules.",
    ], color=LIGHT_BLUE))
    s.append(Spacer(1, 10))

    # ═══════════════════════════════════════════════════════════════
    # SECTION 8: DRAINAGE PATHWAY SUMMARY
    # ═══════════════════════════════════════════════════════════════
    s.append(section_header("8.  Venous Drainage Pathway Summary"))
    s.append(Spacer(1, 8))

    s.append(Paragraph("Superficial Pathway (GSV Route)", H2))
    gsv_flow = [
        ["Dorsal venous arch (medial end)"],
        ["↓  Anterior to medial malleolus"],
        ["Great Saphenous Vein (medial leg, posterior knee loop, medial thigh)"],
        ["↓  Saphenous opening (~4 cm below pubic tubercle)"],
        ["Saphenofemoral Junction (SFJ)"],
        ["↓"],
        ["Common Femoral Vein  →  External Iliac Vein  →  Common Iliac Vein  →  IVC  →  Right Atrium"],
    ]
    flow_rows = [[Paragraph(step[0], TABLE_CELL)] for step in gsv_flow]
    ft = Table(flow_rows, colWidths=[17.5*cm])
    ft.setStyle(TableStyle([
        ("ROWBACKGROUNDS", (0,0), (-1,-1), [LIGHT_BLUE, WHITE, LIGHT_BLUE, WHITE, LIGHT_BLUE, WHITE, LIGHT_BLUE]),
        ("LEFTPADDING",  (0,0), (-1,-1), 14),
        ("RIGHTPADDING", (0,0), (-1,-1), 14),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
        ("BOX",          (0,0), (-1,-1), 1, MID_BLUE),
    ]))
    s.append(ft)
    s.append(Spacer(1, 8))

    s.append(Paragraph("Superficial Pathway (SSV Route)", H2))
    ssv_flow = [
        ["Dorsal venous arch (lateral end) / Lateral marginal vein"],
        ["↓  Posterior to lateral malleolus"],
        ["Small Saphenous Vein (posterior midline of calf, groove between gastrocnemius heads)"],
        ["↓  Pierces popliteal fossa fascia"],
        ["Saphenopopliteal Junction (SPJ)  →  Popliteal Vein"],
        ["↓  Through adductor hiatus"],
        ["Femoral Vein  →  Common Femoral Vein  →  External Iliac  →  IVC  →  Right Atrium"],
    ]
    flow_rows2 = [[Paragraph(step[0], TABLE_CELL)] for step in ssv_flow]
    ft2 = Table(flow_rows2, colWidths=[17.5*cm])
    ft2.setStyle(TableStyle([
        ("ROWBACKGROUNDS", (0,0), (-1,-1), [LIGHT_BLUE, WHITE, LIGHT_BLUE, WHITE, LIGHT_BLUE, WHITE, LIGHT_BLUE]),
        ("LEFTPADDING",  (0,0), (-1,-1), 14),
        ("RIGHTPADDING", (0,0), (-1,-1), 14),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
        ("BOX",          (0,0), (-1,-1), 1, MID_BLUE),
    ]))
    s.append(ft2)
    s.append(Spacer(1, 8))

    s.append(Paragraph("Deep Pathway", H2))
    deep_flow = [
        ["Plantar venous arch / Digital veins"],
        ["↓"],
        ["Anterior tibial veins  +  Posterior tibial veins  +  Peroneal veins"],
        ["↓  Convergence in popliteal fossa"],
        ["Popliteal Vein  (+ SSV, gastrocnemius veins, soleal veins)"],
        ["↓  Through adductor hiatus (adductor magnus)"],
        ["Femoral Vein  (+ GSV via SFJ)"],
        ["↓  + Deep femoral (profunda) vein"],
        ["Common Femoral Vein  →  External Iliac Vein  →  Common Iliac Vein  →  IVC  →  Right Atrium"],
    ]
    flow_rows3 = [[Paragraph(step[0], TABLE_CELL)] for step in deep_flow]
    ft3 = Table(flow_rows3, colWidths=[17.5*cm])
    ft3.setStyle(TableStyle([
        ("ROWBACKGROUNDS", (0,0), (-1,-1), [LIGHT_BLUE, WHITE]*5),
        ("LEFTPADDING",  (0,0), (-1,-1), 14),
        ("RIGHTPADDING", (0,0), (-1,-1), 14),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
        ("BOX",          (0,0), (-1,-1), 1, DARK_BLUE),
    ]))
    s.append(ft3)
    s.append(Spacer(1, 10))

    # ═══════════════════════════════════════════════════════════════
    # SECTION 9: CLINICAL CORRELATIONS
    # ═══════════════════════════════════════════════════════════════
    s.append(section_header("9.  Clinical Correlations"))
    s.append(Spacer(1, 8))

    s.append(two_col_table(
        left_items=[
            "Varicose veins — most commonly from GSV incompetence at SFJ",
            "Venous ulcers — at medial ankle from Cockett perforator incompetence",
            "DVT — most commonly originates in soleal sinuses and posterior tibial veins",
            "Saphenous nerve injury — during below-knee GSV stripping/ablation",
            "Sural nerve injury — during SSV stripping",
            "May-Thurner syndrome — left iliac vein compression by right iliac artery",
        ],
        right_items=[
            "GSV harvest for CABG — most widely used arterial bypass conduit",
            "SFJ ligation — essential step in high ligation and stripping",
            "EVLA / RFA — thermal ablation of GSV/SSV, now first-line for varicosities",
            "Foam sclerotherapy — for truncal and tributary veins",
            "Subfascial endoscopic perforator surgery (SEPS) — for incompetent perforators",
            "IVC filter — for DVT with contraindication to anticoagulation",
        ],
        left_title="Pathology",
        right_title="Surgical/Procedural Relevance"
    ))
    s.append(Spacer(1, 8))

    s.append(Paragraph("CEAP Classification of Chronic Venous Disease", H2))
    ceap_data = [
        ["C0", "No visible/palpable signs of venous disease"],
        ["C1", "Telangiectasia or reticular veins"],
        ["C2", "Varicose veins"],
        ["C3", "Oedema without skin changes"],
        ["C4a", "Pigmentation or eczema"],
        ["C4b", "Lipodermatosclerosis or atrophie blanche"],
        ["C5", "Healed venous ulcer"],
        ["C6", "Active venous ulcer"],
    ]
    s.append(data_table(
        ["CEAP Class", "Clinical Description"],
        ceap_data,
        col_widths=[3.5*cm, 14*cm]
    ))
    s.append(Spacer(1, 10))

    # ═══════════════════════════════════════════════════════════════
    # SECTION 10: KEY LANDMARKS
    # ═══════════════════════════════════════════════════════════════
    s.append(section_header("10.  Key Anatomical Landmarks"))
    s.append(Spacer(1, 8))

    landmarks_data = [
        ["Saphenofemoral junction (SFJ)", "~2.5–4 cm below and lateral to the pubic tubercle. GSV enters CFV here. Important surgical landmark for high ligation."],
        ["Saphenopopliteal junction (SPJ)", "Variable — most often at or just above the popliteal crease. Must be localized by duplex ultrasound before surgery."],
        ["Medial malleolus", "GSV passes anterior to this landmark; key for venous access and cannulation."],
        ["Lateral malleolus", "SSV passes posterior to this landmark; sural nerve lies alongside."],
        ["Adductor (Hunter's) canal", "Subsartorial canal where popliteal vein transitions to femoral vein after passing through adductor hiatus."],
        ["Cribriform fascia / Saphenous opening", "Ovoid opening in deep fascia of anterior thigh through which GSV passes to reach CFV."],
        ["Popliteal fossa", "SSV pierces the deep fascia of popliteal fossa to drain into the popliteal vein; gastrocnemius veins also join here."],
        ["Inguinal ligament", "CFV passes posterior to this to become the external iliac vein. Below = femoral triangle; above = pelvic inlet."],
    ]
    s.append(data_table(
        ["Landmark", "Significance"],
        landmarks_data,
        col_widths=[5.5*cm, 12*cm]
    ))
    s.append(Spacer(1, 12))

    # ── FOOTER / REFERENCES ──
    s.append(HRFlowable(width="100%", thickness=1.5, color=MID_BLUE))
    s.append(Spacer(1, 6))
    s.append(Paragraph(
        "<b>Sources:</b> Gray's Anatomy for Students (9780323934237) • Bailey &amp; Love's Short Practice of Surgery 28e (9780367548117) • "
        "Schwartz's Principles of Surgery 11e (9781259835346) • Imaging Anatomy Vol. 3 (9781626239845) • Sabiston Textbook of Surgery (9780443124341)",
        FOOTER_STYLE))
    s.append(Spacer(1, 4))
    s.append(Paragraph("Medical Anatomy Series  |  Prepared May 2026  |  For Educational Purposes Only", FOOTER_STYLE))

    return s


# ── PAGE TEMPLATE ────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    w, h = A4
    # header bar
    canvas.setFillColor(DARK_BLUE)
    canvas.rect(0, h - 26, w, 26, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica-Bold", 9)
    canvas.drawString(20, h - 17, "ANATOMY OF LOWER LIMB VENOUS DRAINAGE")
    canvas.setFont("Helvetica", 9)
    canvas.drawRightString(w - 20, h - 17, f"Page {doc.page}")
    # footer line
    canvas.setStrokeColor(MID_BLUE)
    canvas.setLineWidth(1)
    canvas.line(20, 28, w - 20, 28)
    canvas.setFillColor(colors.HexColor("#888888"))
    canvas.setFont("Helvetica-Oblique", 7)
    canvas.drawCentredString(w / 2, 16, "Medical Anatomy Series  •  Educational Reference")
    canvas.restoreState()


# ── BUILD PDF ────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    rightMargin=2.0*cm,
    leftMargin=2.0*cm,
    topMargin=2.2*cm,
    bottomMargin=2.0*cm,
    title="Anatomy of Lower Limb Venous Drainage",
    author="Medical Anatomy Series",
    subject="Lower Limb Venous Anatomy",
)

story = build_story()
doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print(f"PDF created: {OUTPUT}")
Running Command

python3 /home/daytona/workspace/lower-limb-venous/build_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/lower-limb-venous/Lower_Limb_Venous_Drainage.pdf

Your PDF is ready! Here's the download link:

Lower Limb Venous Drainage

PDF Document · PDF


What's inside (10 sections, ~29 KB):
SectionContent
1. Overview & ClassificationThree-compartment system (superficial, deep, perforating), color-coded intro table
2. Superficial Venous SystemDorsal venous arch as the origin of both saphenous trunks
3. Great Saphenous Vein (GSV)Full course foot-to-groin, SFJ tributaries, saphenous nerve relationship
4. Small Saphenous Vein (SSV)Course, all termination variants (Giacomini vein, cranial extension), sural nerve
5. Deep Venous SystemTibial/peroneal veins, soleal sinuses, popliteal → femoral → iliac → IVC pathway
6. Perforating VeinsCockett, Boyd, Dodd, Hunterian perforators with locations and connections
7. Venous Valves & HemodynamicsValve counts per segment, calf/foot pump mechanisms
8. Drainage Pathway SummaryThree visual flow charts (GSV route, SSV route, deep route)
9. Clinical CorrelationsVaricose veins, DVT, EVLA/RFA, CEAP classification table
10. Key Anatomical LandmarksSFJ, SPJ, medial/lateral malleolus, adductor canal, inguinal ligament
Sources drawn from Gray's Anatomy for Students, Bailey & Love's Surgery (28e), and Schwartz's Principles of Surgery (11e).

Youre very good at your good , i really appretiate

Thank you, that really means a lot! 😊
Glad the PDF turned out well - venous anatomy can get complex with all the variants and named perforators, so I wanted to make sure everything was laid out clearly and in a logical flow.
Whenever you need another anatomy reference, a clinical topic, a study guide, or anything else - just ask. Happy to help!
This is a shared conversation. Sign in to Orris to start your own chat.