Explain each and everything about the anatomy of hepatic venous portal system with best images. Also explain the clinical correlates. Then make a colorful pdf of the whole content

Reading File
Finding Sources
Finding Sources
Finding Sources
Searching the Web

hepatic portal venous system anatomy tributaries clinical correlates

Reading File
Reading File
Reading File
Reading File
Loading Image
Reading File
Reading File
Finding Sources
Loading Image
Loading Image
Loading Image
Loading Image
Reading File
Finding Sources
Reading File
Reading File
Running Command

mkdir -p /home/daytona/workspace/portal-venous-system && ls /home/daytona/worksp…

Writing File

~/portal-venous-system/build_pdf.py

#!/usr/bin/env python3
"""
Build a colorful, image-rich PDF on the Hepatic Venous Portal System.
Uses reportlab for full control over layout, colors, and typography.
"""

import requests
import io
import os
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import mm, cm
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle,
    PageBreak, HRFlowable, KeepTogether
)
from reportlab.platypus.flowables import BalancedColumns
from reportlab.pdfgen import canvas
from reportlab.lib.colors import HexColor, Color
from PIL import Image as PILImage

# ─── Color Palette ────────────────────────────────────────────────────────────
DEEP_BLUE    = HexColor('#1A3A5C')
MID_BLUE     = HexColor('#2E6DA4')
LIGHT_BLUE   = HexColor('#D6E8F7')
TEAL         = HexColor('#1B7A8A')
TEAL_LIGHT   = HexColor('#D0F0F4')
ORANGE       = HexColor('#E8640D')
ORANGE_LIGHT = HexColor('#FDEBD0')
GREEN        = HexColor('#217A3C')
GREEN_LIGHT  = HexColor('#D5EFD0')
RED          = HexColor('#C0392B')
RED_LIGHT    = HexColor('#FADBD8')
PURPLE       = HexColor('#6C3483')
PURPLE_LIGHT = HexColor('#EBD8F5')
GOLD         = HexColor('#D4AC0D')
GOLD_LIGHT   = HexColor('#FEF9E7')
GRAY_DARK    = HexColor('#2C3E50')
GRAY_MID     = HexColor('#566573')
GRAY_LIGHT   = HexColor('#F2F3F4')
WHITE        = colors.white

W, H = A4  # 595 x 842 pts

OUT = '/home/daytona/workspace/portal-venous-system/Hepatic_Portal_Venous_System.pdf'

# ─── Download helper ──────────────────────────────────────────────────────────
def dl_image(url, max_w, max_h):
    """Download image URL and return a ReportLab Image object scaled to fit."""
    try:
        r = requests.get(url, timeout=15)
        r.raise_for_status()
        img_data = io.BytesIO(r.content)
        pil = PILImage.open(img_data)
        iw, ih = pil.size
        ratio = min(max_w / iw, max_h / ih)
        return Image(io.BytesIO(r.content), width=iw*ratio, height=ih*ratio)
    except Exception as e:
        print(f"Warning: could not load {url}: {e}")
        return None

# ─── Page template with colored header/footer ────────────────────────────────
class ColoredPage:
    def __init__(self, title):
        self.title = title

    def __call__(self, c: canvas.Canvas, doc):
        c.saveState()
        # Top banner
        c.setFillColor(DEEP_BLUE)
        c.rect(0, H - 22*mm, W, 22*mm, fill=1, stroke=0)
        c.setFillColor(WHITE)
        c.setFont('Helvetica-Bold', 11)
        c.drawCentredString(W/2, H - 14*mm, self.title)
        # Bottom footer
        c.setFillColor(DEEP_BLUE)
        c.rect(0, 0, W, 12*mm, fill=1, stroke=0)
        c.setFillColor(WHITE)
        c.setFont('Helvetica', 8)
        c.drawCentredString(W/2, 4*mm, f'Page {doc.page}  |  Hepatic Venous Portal System  |  Medical Anatomy & Clinical Correlates')
        c.restoreState()

# ─── Styles ───────────────────────────────────────────────────────────────────
def make_styles():
    styles = getSampleStyleSheet()
    s = {}

    s['cover_title'] = ParagraphStyle(
        'cover_title', fontName='Helvetica-Bold', fontSize=32,
        textColor=WHITE, alignment=TA_CENTER, leading=40, spaceAfter=6)
    s['cover_subtitle'] = ParagraphStyle(
        'cover_subtitle', fontName='Helvetica', fontSize=15,
        textColor=HexColor('#D6E8F7'), alignment=TA_CENTER, leading=22, spaceAfter=4)
    s['cover_author'] = ParagraphStyle(
        'cover_author', fontName='Helvetica-Oblique', fontSize=11,
        textColor=GOLD, alignment=TA_CENTER, leading=16)

    s['chapter'] = ParagraphStyle(
        'chapter', fontName='Helvetica-Bold', fontSize=20,
        textColor=WHITE, alignment=TA_LEFT, leading=26, spaceAfter=2,
        spaceBefore=4, leftIndent=4)
    s['section'] = ParagraphStyle(
        'section', fontName='Helvetica-Bold', fontSize=14,
        textColor=DEEP_BLUE, alignment=TA_LEFT, leading=20,
        spaceBefore=10, spaceAfter=4, borderPad=2)
    s['subsection'] = ParagraphStyle(
        'subsection', fontName='Helvetica-Bold', fontSize=11,
        textColor=TEAL, alignment=TA_LEFT, leading=16,
        spaceBefore=6, spaceAfter=3)
    s['body'] = ParagraphStyle(
        'body', fontName='Helvetica', fontSize=10,
        textColor=GRAY_DARK, alignment=TA_JUSTIFY, leading=15,
        spaceBefore=3, spaceAfter=3)
    s['body_bold'] = ParagraphStyle(
        'body_bold', fontName='Helvetica-Bold', fontSize=10,
        textColor=GRAY_DARK, alignment=TA_LEFT, leading=15,
        spaceBefore=2, spaceAfter=2)
    s['bullet'] = ParagraphStyle(
        'bullet', fontName='Helvetica', fontSize=10,
        textColor=GRAY_DARK, alignment=TA_LEFT, leading=15,
        leftIndent=14, spaceBefore=2, spaceAfter=2,
        firstLineIndent=-10)
    s['caption'] = ParagraphStyle(
        'caption', fontName='Helvetica-Oblique', fontSize=8.5,
        textColor=GRAY_MID, alignment=TA_CENTER, leading=12,
        spaceBefore=2, spaceAfter=6)
    s['highlight'] = ParagraphStyle(
        'highlight', fontName='Helvetica-Bold', fontSize=10,
        textColor=DEEP_BLUE, alignment=TA_LEFT, leading=15,
        leftIndent=10, rightIndent=10, spaceBefore=4, spaceAfter=4)
    s['toc_title'] = ParagraphStyle(
        'toc_title', fontName='Helvetica-Bold', fontSize=13,
        textColor=DEEP_BLUE, alignment=TA_LEFT, leading=18, spaceAfter=6)
    s['toc_item'] = ParagraphStyle(
        'toc_item', fontName='Helvetica', fontSize=11,
        textColor=GRAY_DARK, alignment=TA_LEFT, leading=18, leftIndent=10)
    return s

# ─── Chapter heading block ────────────────────────────────────────────────────
def chapter_block(text, color=DEEP_BLUE, text_color=WHITE):
    return Table(
        [[Paragraph(text, ParagraphStyle('ch', fontName='Helvetica-Bold',
                    fontSize=16, textColor=text_color, leading=22))]],
        colWidths=[W - 40*mm],
        style=TableStyle([
            ('BACKGROUND', (0,0), (-1,-1), color),
            ('ROUNDEDCORNERS', [5]),
            ('TOPPADDING', (0,0), (-1,-1), 8),
            ('BOTTOMPADDING', (0,0), (-1,-1), 8),
            ('LEFTPADDING', (0,0), (-1,-1), 12),
            ('RIGHTPADDING', (0,0), (-1,-1), 12),
        ])
    )

# ─── Colored info box ─────────────────────────────────────────────────────────
def info_box(content_rows, bg_color, border_color, styles):
    """content_rows: list of Paragraph objects"""
    data = [[p] for p in content_rows]
    t = Table(data, colWidths=[W - 44*mm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), bg_color),
        ('BOX', (0,0), (-1,-1), 1.5, border_color),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
        ('LEFTPADDING', (0,0), (-1,-1), 10),
        ('RIGHTPADDING', (0,0), (-1,-1), 10),
    ]))
    return t

# ─── Key fact box ─────────────────────────────────────────────────────────────
def key_fact(title, body, s, bg=GOLD_LIGHT, border=GOLD):
    rows = [
        Paragraph(f'<b>{title}</b>', ParagraphStyle('kft', fontName='Helvetica-Bold',
                  fontSize=10, textColor=GRAY_DARK, leading=14)),
        Paragraph(body, ParagraphStyle('kfb', fontName='Helvetica', fontSize=9.5,
                  textColor=GRAY_DARK, leading=14, alignment=TA_JUSTIFY)),
    ]
    return info_box(rows, bg, border, s)

# ─── Clinical box ─────────────────────────────────────────────────────────────
def clinical_box(title, body, s):
    rows = [
        Paragraph(f'🔴  {title}', ParagraphStyle('cbt', fontName='Helvetica-Bold',
                  fontSize=10, textColor=RED, leading=14)),
        Paragraph(body, ParagraphStyle('cbb', fontName='Helvetica', fontSize=9.5,
                  textColor=GRAY_DARK, leading=14, alignment=TA_JUSTIFY)),
    ]
    return info_box(rows, RED_LIGHT, RED, s)

# ─── Two-column image row ─────────────────────────────────────────────────────
def two_img(img1, cap1, img2, cap2, s):
    if img1 and img2:
        data = [[img1, img2],
                [Paragraph(cap1, s['caption']), Paragraph(cap2, s['caption'])]]
        cw = (W - 44*mm) / 2 - 3*mm
        t = Table(data, colWidths=[cw, cw], hAlign='CENTER')
        t.setStyle(TableStyle([
            ('ALIGN', (0,0), (-1,-1), 'CENTER'),
            ('VALIGN', (0,0), (-1,-1), 'TOP'),
            ('LEFTPADDING', (0,0), (-1,-1), 3),
            ('RIGHTPADDING', (0,0), (-1,-1), 3),
            ('TOPPADDING', (0,0), (-1,-1), 2),
            ('BOTTOMPADDING', (0,0), (-1,-1), 2),
        ]))
        return t
    elif img1:
        return img1
    elif img2:
        return img2
    return Spacer(1, 1)

# ─── Main builder ─────────────────────────────────────────────────────────────
def build():
    s = make_styles()
    doc = SimpleDocTemplate(
        OUT, pagesize=A4,
        leftMargin=20*mm, rightMargin=20*mm,
        topMargin=28*mm, bottomMargin=18*mm,
        title='Hepatic Venous Portal System',
        author='Orris Medical',
        subject='Anatomy & Clinical Correlates'
    )
    page_cb = ColoredPage('HEPATIC VENOUS PORTAL SYSTEM — Anatomy & Clinical Correlates')
    story = []

    # ── COVER PAGE ────────────────────────────────────────────────────────────
    def cover(c, doc):
        c.saveState()
        # Full-page gradient-like background
        c.setFillColor(DEEP_BLUE)
        c.rect(0, 0, W, H, fill=1, stroke=0)
        # Accent strip
        c.setFillColor(MID_BLUE)
        c.rect(0, H*0.38, W, H*0.3, fill=1, stroke=0)
        # Gold bottom accent
        c.setFillColor(GOLD)
        c.rect(0, 0, W, 18*mm, fill=1, stroke=0)
        # Decorative circles
        c.setFillColor(Color(1,1,1,0.05))
        c.circle(W*0.15, H*0.85, 80, fill=1, stroke=0)
        c.circle(W*0.88, H*0.2, 100, fill=1, stroke=0)
        c.circle(W*0.5, H*0.5, 200, fill=0, stroke=1)
        c.setStrokeColor(Color(1,1,1,0.08))
        c.setLineWidth(1)
        # Title
        c.setFont('Helvetica-Bold', 36)
        c.setFillColor(WHITE)
        c.drawCentredString(W/2, H*0.72, 'HEPATIC VENOUS')
        c.drawCentredString(W/2, H*0.65, 'PORTAL SYSTEM')
        # Subtitle line
        c.setFillColor(GOLD)
        c.rect(W*0.25, H*0.62, W*0.5, 3, fill=1, stroke=0)
        # Subtitle
        c.setFont('Helvetica', 16)
        c.setFillColor(HexColor('#D6E8F7'))
        c.drawCentredString(W/2, H*0.56, 'Complete Anatomy, Physiology &')
        c.drawCentredString(W/2, H*0.52, 'Clinical Correlates')
        # Chapters listed
        c.setFont('Helvetica', 11)
        c.setFillColor(GOLD_LIGHT)
        topics = [
            '1. Overview & Formation of the Portal Vein',
            '2. Tributaries & Venous Drainage',
            '3. Intrahepatic Distribution & Liver Lobule',
            '4. Hepatic Veins',
            '5. Portosystemic (Porto-Caval) Anastomoses',
            '6. Hemodynamics & Physiology',
            '7. Clinical Correlates: Portal Hypertension',
            '8. Clinical Correlates: Varices, Caput Medusae & More',
            '9. Investigations & Imaging',
            '10. Management Principles',
        ]
        y = H*0.45
        for t in topics:
            c.drawCentredString(W/2, y, t)
            y -= 16
        # Footer
        c.setFillColor(WHITE)
        c.setFont('Helvetica-Bold', 9)
        c.drawCentredString(W/2, 10*mm, 'Sources: Gray\'s Anatomy | Guyton & Hall | Yamada\'s Gastroenterology | Color Atlas of Human Anatomy | Mulholland Surgery')
        c.restoreState()

    story.append(PageBreak())  # triggers cover via onFirstPage

    # ── TABLE OF CONTENTS ─────────────────────────────────────────────────────
    story.append(Spacer(1, 6*mm))
    story.append(chapter_block('TABLE OF CONTENTS', DEEP_BLUE))
    story.append(Spacer(1, 4*mm))
    toc_data = [
        ('1', 'Overview & Formation of the Portal Vein', '3'),
        ('2', 'Tributaries of the Portal Vein', '4'),
        ('3', 'Intrahepatic Distribution & Liver Lobule', '5'),
        ('4', 'Hepatic Veins', '6'),
        ('5', 'Portosystemic (Porto-Caval) Anastomoses', '7'),
        ('6', 'Hemodynamics & Physiology', '8'),
        ('7', 'Portal Hypertension', '9'),
        ('8', 'Varices, Caput Medusae & Hemorrhoids', '10'),
        ('9', 'Investigations & Imaging', '11'),
        ('10', 'Management Principles', '12'),
    ]
    for num, title, page in toc_data:
        story.append(Table(
            [[Paragraph(f'<b>{num}.</b>', ParagraphStyle('tn', fontName='Helvetica-Bold', fontSize=11, textColor=MID_BLUE, leading=16)),
              Paragraph(title, ParagraphStyle('tt', fontName='Helvetica', fontSize=11, textColor=GRAY_DARK, leading=16)),
              Paragraph(page, ParagraphStyle('tp', fontName='Helvetica', fontSize=11, textColor=GRAY_MID, leading=16, alignment=TA_CENTER))]],
            colWidths=[12*mm, (W-60*mm), 18*mm],
            style=TableStyle([
                ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
                ('BOTTOMPADDING', (0,0), (-1,-1), 2),
                ('TOPPADDING', (0,0), (-1,-1), 2),
                ('LINEBELOW', (0,0), (-1,-1), 0.5, HexColor('#BDC3C7')),
            ])
        ))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # CHAPTER 1 — OVERVIEW
    # ══════════════════════════════════════════════════════════════════════════
    story.append(chapter_block('Chapter 1: Overview & Formation of the Portal Vein', DEEP_BLUE))
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('What is the Hepatic Portal System?', s['section']))
    story.append(Paragraph(
        'The hepatic portal system is a unique vascular arrangement in which venous blood from the '
        'gastrointestinal (GI) tract, spleen, pancreas, and gallbladder is collected and delivered '
        'to the liver <i>before</i> it returns to the systemic circulation. This allows the liver to '
        'process absorbed nutrients, detoxify substances, and regulate metabolite levels in the blood. '
        'Unlike most veins in the body that drain directly into the heart, the portal vein feeds into '
        'a second capillary network — the hepatic sinusoids — making this a true portal circulation.',
        s['body']))
    story.append(Spacer(1, 3*mm))

    story.append(key_fact(
        'Key Definition — Portal Vein',
        'The hepatic portal vein (HPV) is a large venous trunk, approximately 5–8 cm long and 1–1.2 cm '
        'in diameter, formed by the confluence of the superior mesenteric vein (SMV) and the splenic '
        'vein (SV) posterior to the neck of the pancreas, at the level of L1–L2. It carries roughly '
        '1,050 mL/min of nutrient-rich, partially deoxygenated blood to the liver.',
        s))
    story.append(Spacer(1, 3*mm))

    story.append(Paragraph('Formation of the Portal Vein', s['section']))
    story.append(Paragraph(
        'The portal vein forms <b>behind the neck (head) of the pancreas</b> at the level of the '
        'transpyloric plane (L1). Specifically:', s['body']))
    bullets_ch1 = [
        '<b>Superior mesenteric vein (SMV)</b> — drains the small intestine, ascending and transverse colon, '
        'and the right side of the GI tract. Ascends in the root of the small bowel mesentery.',
        '<b>Splenic vein (SV)</b> — drains the spleen and receives the inferior mesenteric vein (IMV) '
        'before joining the SMV. Runs posterior to the body and tail of the pancreas.',
        'The <b>inferior mesenteric vein (IMV)</b> most commonly drains into the splenic vein (65%), '
        'less commonly into the SMV (30%), or at the junction itself (5%).',
    ]
    for b in bullets_ch1:
        story.append(Paragraph(f'• {b}', s['bullet']))

    story.append(Spacer(1, 3*mm))
    story.append(Paragraph('Course to the Liver', s['section']))
    story.append(Paragraph(
        'After formation, the portal vein ascends in the <b>hepatoduodenal ligament</b> — the free '
        'edge of the lesser omentum — accompanied by the hepatic artery proper (to its left) and the '
        'common bile duct (to its right). This arrangement forms the boundaries of the <b>epiploic '
        'foramen of Winslow</b>. The portal vein lies dorsal (posterior) to both the bile duct and '
        'hepatic artery within this ligament. At the porta hepatis (liver hilum), it divides into '
        '<b>right</b> and <b>left</b> branches.', s['body']))

    story.append(Spacer(1, 4*mm))

    # Main overview image
    img_overview = dl_image(
        'https://d1j63owfs0b5j3.cloudfront.net/tutorial/finalImage/924-1761339493465.png',
        W - 44*mm, 130*mm)
    if img_overview:
        story.append(img_overview)
        story.append(Paragraph(
            'Fig. 1.1 — Complete schematic of the hepatic portal system showing the portal vein, '
            'its tributaries, the liver, and the drainage into hepatic veins and the IVC.',
            s['caption']))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # CHAPTER 2 — TRIBUTARIES
    # ══════════════════════════════════════════════════════════════════════════
    story.append(chapter_block('Chapter 2: Tributaries of the Portal Vein', TEAL))
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Primary Tributaries', s['section']))
    story.append(Paragraph(
        'The portal vein receives venous drainage from all of the unpaired abdominal organs. '
        'It has three main tributaries and several smaller direct tributaries:', s['body']))

    # Tributaries table
    trib_data = [
        ['Vein', 'Drains', 'Joins at'],
        ['Superior Mesenteric V.', 'Small intestine, ascending & transverse colon, pancreas head', 'Behind pancreatic neck (forms HPV)'],
        ['Splenic V.', 'Spleen, pancreas body & tail', 'Behind pancreatic neck (forms HPV)'],
        ['Inferior Mesenteric V.', 'Descending colon, sigmoid colon, rectum (upper)', 'Usually into splenic vein'],
        ['Left Gastric (Coronary) V.', 'Lesser curvature of stomach, lower esophagus', 'Directly into HPV trunk'],
        ['Right Gastric V.', 'Lesser curvature of stomach (pyloric region)', 'Directly into HPV trunk'],
        ['Cystic V.', 'Gallbladder', 'Directly into right branch HPV'],
        ['Para-umbilical VV.', 'Anterior abdominal wall (ligamentum teres)', 'Left branch HPV'],
        ['Posterior Sup. Pancreatico-duodenal V.', 'Head of pancreas, duodenum', 'Directly into HPV trunk'],
    ]
    trib_table = Table(
        trib_data,
        colWidths=[(W-44*mm)*0.3, (W-44*mm)*0.4, (W-44*mm)*0.3],
        repeatRows=1
    )
    trib_table.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), DEEP_BLUE),
        ('TEXTCOLOR', (0,0), (-1,0), WHITE),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE', (0,0), (-1,-1), 9),
        ('FONTNAME', (1,1), (0,-1), 'Helvetica'),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [WHITE, LIGHT_BLUE]),
        ('GRID', (0,0), (-1,-1), 0.5, HexColor('#BDC3C7')),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('LEFTPADDING', (0,0), (-1,-1), 5),
        ('RIGHTPADDING', (0,0), (-1,-1), 5),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ]))
    story.append(trib_table)
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Tributaries of the Superior Mesenteric Vein (SMV)', s['subsection']))
    smv_bullets = [
        'Jejunal and ileal veins (from small intestine)',
        'Right gastro-omental (gastroepiploic) vein',
        'Ileocolic vein',
        'Right colic vein',
        'Middle colic vein',
        'Pancreaticoduodenal veins',
        'Pancreatic veins',
    ]
    for b in smv_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))

    story.append(Paragraph('Tributaries of the Splenic Vein', s['subsection']))
    sv_bullets = [
        'Pancreatic veins (multiple short branches from pancreas body and tail)',
        'Short gastric veins (from fundus of stomach)',
        'Left gastro-omental (gastroepiploic) vein',
        'Inferior mesenteric vein (in ~65% of cases)',
    ]
    for b in sv_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))

    story.append(Spacer(1, 4*mm))
    # Netter image
    img_netter = dl_image(
        'https://www.netterimages.com/images/vpv/000/000/037/37957-0550x0475.jpg',
        W - 44*mm, 120*mm)
    if img_netter:
        story.append(img_netter)
        story.append(Paragraph(
            'Fig. 2.1 — Netter\'s classic illustration of the portal venous system showing all tributaries '
            'and portocaval anastomoses. Color coding: blue = SMV territory; purple = splenic/gastric; '
            'grey = caval tributaries. (© Elsevier / Netter)',
            s['caption']))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # CHAPTER 3 — INTRAHEPATIC DISTRIBUTION
    # ══════════════════════════════════════════════════════════════════════════
    story.append(chapter_block('Chapter 3: Intrahepatic Distribution & Liver Lobule', MID_BLUE))
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Branching at the Porta Hepatis', s['section']))
    story.append(Paragraph(
        'At the porta hepatis (liver hilum), the portal vein divides into:', s['body']))
    branch_bullets = [
        '<b>Right branch</b> — enters the right lobe and divides into <b>anterior</b> (segments V, VIII) '
        'and <b>posterior</b> (segments VI, VII) segmental branches.',
        '<b>Left branch</b> — courses horizontally (transverse part), then turns anteriorly (umbilical part). '
        'It supplies segments II, III, and IV, and receives the para-umbilical veins at its genu (bend). '
        'It also gives branches to the caudate lobe (segment I).',
    ]
    for b in branch_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))

    story.append(Spacer(1, 3*mm))
    story.append(Paragraph('Couinaud Liver Segments & Portal Supply', s['section']))
    couinaud_data = [
        ['Couinaud Segment', 'Name', 'Portal Supply'],
        ['I', 'Caudate lobe', 'Both right & left branches'],
        ['II', 'Left posterior-superior', 'Left branch'],
        ['III', 'Left posterior-inferior', 'Left branch'],
        ['IV (IVa, IVb)', 'Left medial (quadrate)', 'Left branch'],
        ['V', 'Right anterior-inferior', 'Right anterior branch'],
        ['VI', 'Right posterior-inferior', 'Right posterior branch'],
        ['VII', 'Right posterior-superior', 'Right posterior branch'],
        ['VIII', 'Right anterior-superior', 'Right anterior branch'],
    ]
    ct = Table(couinaud_data, colWidths=[(W-44*mm)*0.18, (W-44*mm)*0.45, (W-44*mm)*0.37], repeatRows=1)
    ct.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), TEAL),
        ('TEXTCOLOR', (0,0), (-1,0), WHITE),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE', (0,0), (-1,-1), 9),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [WHITE, TEAL_LIGHT]),
        ('GRID', (0,0), (-1,-1), 0.5, HexColor('#BDC3C7')),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
        ('ALIGN', (0,0), (0,-1), 'CENTER'),
        ('LEFTPADDING', (0,0), (-1,-1), 5),
        ('RIGHTPADDING', (0,0), (-1,-1), 5),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ]))
    story.append(ct)
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('The Liver Lobule — Microanatomy', s['section']))
    story.append(Paragraph(
        'Within the liver, portal blood flows through a specialized microanatomy:', s['body']))
    lobule_bullets = [
        '<b>Portal triad (portal tract)</b> — each corner of a classic hexagonal liver lobule contains '
        'a portal arteriole (branch of hepatic artery), a portal venule (branch of portal vein), and '
        'a bile ductule. This is the functional unit of delivery.',
        '<b>Sinusoids</b> — portal blood and hepatic arterial blood mix in the sinusoids, which are '
        'specialized, leaky capillaries lined by sinusoidal endothelial cells. They are surrounded '
        'by hepatocytes in cord-like plates.',
        '<b>Space of Disse</b> — the perisinusoidal space between sinusoidal endothelium and hepatocytes. '
        'Plasma filters here for metabolite exchange. Contains hepatic stellate cells (Ito cells).',
        '<b>Kupffer cells</b> — resident macrophages lining the sinusoids that phagocytose bacteria, '
        'antigens, and particles from portal blood.',
        '<b>Central vein (terminal hepatic venule)</b> — blood exits sinusoids into central veins, '
        'which coalesce to form hepatic veins.',
        '<b>Blood flow direction</b> — flows from the portal tract (periphery) toward the central vein '
        '(zone 3 being most susceptible to hypoxia in zone-based injury).',
    ]
    for b in lobule_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))

    story.append(Spacer(1, 4*mm))
    img_lobule = dl_image(
        'https://cdn.orris.care/cdss_images/75bfbe5791a751fd403ddc27d48e7b440931ebe227c7c33cf23678df3e9d850b.png',
        W - 44*mm, 100*mm)
    if img_lobule:
        story.append(img_lobule)
        story.append(Paragraph(
            'Fig. 3.1 — Diagram of a liver lobule showing the portal triad (portal vein branch, '
            'hepatic artery branch, bile duct), hepatic sinusoids, space of Disse, Kupffer cells, '
            'and central vein. (Source: Guyton & Hall Textbook of Medical Physiology)',
            s['caption']))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # CHAPTER 4 — HEPATIC VEINS
    # ══════════════════════════════════════════════════════════════════════════
    story.append(chapter_block('Chapter 4: Hepatic Veins', GREEN))
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('The Hepatic Veins', s['section']))
    story.append(Paragraph(
        'The hepatic veins drain blood from the liver sinusoids into the inferior vena cava (IVC). '
        'They represent the outflow tract of the hepatic portal system.', s['body']))

    hv_data = [
        ['Hepatic Vein', 'Territory Drained', 'Drainage into IVC'],
        ['Right hepatic vein (RHV)', 'Right posterior sector (segs VI & VII)', 'Separate ostium, right side of IVC'],
        ['Middle hepatic vein (MHV)', 'Right anterior & left medial sectors (segs V, VIII, IV)', 'Often joins LHV or separate'],
        ['Left hepatic vein (LHV)', 'Left lateral sector (segs II & III)', 'Often joins MHV before IVC'],
        ['Caudate lobe veins', 'Caudate lobe (seg I)', 'Multiple small veins directly into IVC'],
    ]
    hvt = Table(hv_data, colWidths=[(W-44*mm)*0.28, (W-44*mm)*0.4, (W-44*mm)*0.32], repeatRows=1)
    hvt.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), GREEN),
        ('TEXTCOLOR', (0,0), (-1,0), WHITE),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE', (0,0), (-1,-1), 9),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [WHITE, GREEN_LIGHT]),
        ('GRID', (0,0), (-1,-1), 0.5, HexColor('#BDC3C7')),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
        ('LEFTPADDING', (0,0), (-1,-1), 5),
        ('RIGHTPADDING', (0,0), (-1,-1), 5),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ]))
    story.append(hvt)
    story.append(Spacer(1, 4*mm))

    story.append(key_fact(
        'Clinical Importance of Caudate Lobe Venous Drainage',
        'Because the caudate lobe has separate, direct drainage into the IVC, it is spared in '
        'Budd-Chiari syndrome (hepatic vein thrombosis). On imaging, the caudate lobe appears '
        'hypertrophied while the rest of the liver shows congestion and atrophy — a pathognomonic '
        'finding on CT/MRI.', s))

    story.append(Spacer(1, 3*mm))
    img_mra = dl_image(
        'https://cdn.orris.care/cdss_images/bf70109e0db740b7e2fabfad73665b459bb3e7f8bc0580fc74c325b008d0b1e1.png',
        W - 44*mm, 100*mm)
    if img_mra:
        story.append(img_mra)
        story.append(Paragraph(
            'Fig. 4.1 — MR angiography (coronal MIP) showing the portal venous system in vivo. '
            'SMV = superior mesenteric vein; MPV = main portal vein; RPV/LPV = right/left portal '
            'vein; RHV/MHV/LHV = right/middle/left hepatic veins. (Source: Yamada\'s Gastroenterology)',
            s['caption']))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # CHAPTER 5 — PORTOSYSTEMIC ANASTOMOSES
    # ══════════════════════════════════════════════════════════════════════════
    story.append(chapter_block('Chapter 5: Portosystemic (Porto-Caval) Anastomoses', PURPLE))
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('What Are Portosystemic Anastomoses?', s['section']))
    story.append(Paragraph(
        'Portosystemic anastomoses are natural connections between the portal venous system and the '
        'systemic venous (caval) circulation. Under normal conditions, these connections are small '
        'and carry minimal blood. However, when portal pressure rises (portal hypertension), blood '
        'is diverted through these collaterals, causing them to dilate dramatically — with life-threatening '
        'consequences.', s['body']))

    story.append(Spacer(1, 3*mm))
    story.append(Paragraph('The Four Main Sites of Porto-Caval Anastomosis', s['section']))

    anast_data = [
        ['Site', 'Portal Component', 'Systemic Component', 'Clinical Result'],
        ['1. Lower Esophagus\n(most dangerous)', 'Left gastric (coronary) vein →\nesophageal veins', 'Azygos vein →\nSVC', 'Esophageal varices\n(rupture → fatal hemorrhage)'],
        ['2. Umbilicus / Anterior Abdominal Wall', 'Para-umbilical veins →\nleft portal vein', 'Superficial epigastric veins →\nSVC/IVC', 'Caput medusae\n(visible dilated veins)'],
        ['3. Rectum / Anal Canal', 'Superior rectal vein →\nIMV → portal', 'Middle & inferior rectal veins →\ninternal iliac → IVC', 'Rectal/anorectal varices\n(± hemorrhoids)'],
        ['4. Retroperitoneum\n(Retzius veins)', 'Retroperitoneal bowel veins', 'Lumbar/renal veins →\nIVC', 'Retroperitoneal collaterals\n(large spontaneous shunts)'],
    ]
    at = Table(anast_data, colWidths=[(W-44*mm)*0.2, (W-44*mm)*0.27, (W-44*mm)*0.27, (W-44*mm)*0.26], repeatRows=1)
    at.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), PURPLE),
        ('TEXTCOLOR', (0,0), (-1,0), WHITE),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE', (0,0), (-1,-1), 8.5),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [WHITE, PURPLE_LIGHT]),
        ('GRID', (0,0), (-1,-1), 0.5, HexColor('#BDC3C7')),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('LEFTPADDING', (0,0), (-1,-1), 4),
        ('RIGHTPADDING', (0,0), (-1,-1), 4),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ]))
    story.append(at)
    story.append(Spacer(1, 3*mm))

    story.append(Paragraph('Additional Anastomotic Sites', s['subsection']))
    extra_bullets = [
        '<b>Bare area of the liver</b> — where the liver contacts the diaphragm directly (without peritoneum), '
        'small veins communicate between the portal system and diaphragmatic/phrenic veins.',
        '<b>Retroperitoneal gut areas</b> — where ascending and descending colon and duodenum contact the '
        'posterior abdominal wall.',
        '<b>Posterior surface of the pancreas</b> — pancreatic veins anastomose with retroperitoneal veins.',
    ]
    for b in extra_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))

    story.append(Spacer(1, 4*mm))
    # Color Atlas diagram
    img_atlas = dl_image(
        'https://cdn.orris.care/cdss_images/d002d197a81742a43346164e79eeec6cfba5784fdfcc002399ee32fc7f7820de.png',
        W - 44*mm, 120*mm)
    if img_atlas:
        story.append(img_atlas)
        story.append(Paragraph(
            'Fig. 5.1 — Color Atlas of Human Anatomy. Panel A: liver segments (anterior & posterior). '
            'Panel B: vessels and bile ducts at the porta hepatis. Panel C: portal venous system and '
            'collateral circulation showing the three main portocaval anastomotic sites (I = esophageal, '
            'II = paraumbilical, III = rectal). (Source: Thieme Color Atlas)',
            s['caption']))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # CHAPTER 6 — HEMODYNAMICS
    # ══════════════════════════════════════════════════════════════════════════
    story.append(chapter_block('Chapter 6: Hemodynamics & Physiology', ORANGE))
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Portal Blood Flow — Key Numbers', s['section']))

    phys_data = [
        ['Parameter', 'Normal Value'],
        ['Total hepatic blood flow', '~1,350 mL/min (27% of cardiac output)'],
        ['Portal vein contribution', '~1,050 mL/min (75–80% of total hepatic flow)'],
        ['Hepatic artery contribution', '~300 mL/min (20–25% of total hepatic flow)'],
        ['Portal vein pressure', '5–10 mmHg (normally 7–10 mmHg)'],
        ['Hepatic vein pressure (IVC)', '~0–5 mmHg'],
        ['Portal–hepatic venous gradient', '~9 mmHg normally'],
        ['Pressure gradient for portal HTN', '>10 mmHg (clinically significant portal hypertension)'],
        ['Pressure for variceal bleed risk', '>12 mmHg'],
    ]
    pt = Table(phys_data, colWidths=[(W-44*mm)*0.55, (W-44*mm)*0.45], repeatRows=1)
    pt.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), ORANGE),
        ('TEXTCOLOR', (0,0), (-1,0), WHITE),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE', (0,0), (-1,-1), 9.5),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [WHITE, ORANGE_LIGHT]),
        ('GRID', (0,0), (-1,-1), 0.5, HexColor('#BDC3C7')),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
        ('RIGHTPADDING', (0,0), (-1,-1), 6),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ]))
    story.append(pt)
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Hepatic Arterial Buffer Response', s['subsection']))
    story.append(Paragraph(
        'The liver uses a compensatory mechanism called the <b>Hepatic Arterial Buffer Response (HABR)</b>: '
        'when portal flow decreases, the hepatic artery dilates reflexively to maintain total hepatic '
        'perfusion. This is mediated by local adenosine washout. Conversely, when portal flow increases, '
        'hepatic arterial flow decreases. This compensation is absent in the reverse direction — '
        'decreased hepatic arterial flow does NOT cause compensatory portal flow increase.', s['body']))

    story.append(Spacer(1, 3*mm))
    story.append(Paragraph('Oxygen Delivery to Hepatocytes', s['subsection']))
    story.append(Paragraph(
        'Despite portal blood being partially deoxygenated (~85% O₂ saturation), the portal vein '
        'provides approximately <b>50–60% of the liver\'s oxygen supply</b> due to the sheer volume '
        'of blood delivered. The hepatic artery provides the remaining 40–50%. The liver lobule shows '
        'a metabolic gradient:', s['body']))
    zone_bullets = [
        '<b>Zone 1 (periportal)</b> — most oxygenated; site of gluconeogenesis, β-oxidation, amino acid '
        'metabolism, and urea synthesis. First affected by toxin exposure.',
        '<b>Zone 2 (midzonal)</b> — intermediate zone.',
        '<b>Zone 3 (centrilobular)</b> — least oxygenated; site of glycolysis and lipogenesis. Most '
        'vulnerable to ischemia, most susceptible to alcohol/drug toxicity, and where centrilobular '
        'necrosis occurs in right heart failure.',
    ]
    for b in zone_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # CHAPTER 7 — PORTAL HYPERTENSION
    # ══════════════════════════════════════════════════════════════════════════
    story.append(chapter_block('Chapter 7: Clinical Correlate — Portal Hypertension', RED))
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Definition & Classification', s['section']))
    story.append(info_box([
        Paragraph('<b>Portal Hypertension:</b> Sustained elevation of portal venous pressure above '
                  '<b>10 mmHg</b> (or hepatic venous pressure gradient [HVPG] > 5 mmHg; clinically '
                  'significant > 10 mmHg; variceal hemorrhage risk > 12 mmHg).',
                  ParagraphStyle('def', fontName='Helvetica', fontSize=10, textColor=GRAY_DARK,
                                 leading=15, alignment=TA_JUSTIFY))
    ], LIGHT_BLUE, MID_BLUE, s))
    story.append(Spacer(1, 3*mm))

    story.append(Paragraph('Classification by Level of Obstruction', s['subsection']))
    class_data = [
        ['Class', 'Level', 'Common Causes'],
        ['Pre-hepatic', 'Before the liver sinusoids', 'Portal vein thrombosis, splenic vein thrombosis, '
         'compression by tumour/nodes, congenital atresia'],
        ['Intra-hepatic\n(Presinusoidal)', 'Within liver, before sinusoids', 'Schistosomiasis (periportal fibrosis), '
         'primary biliary cholangitis (early), sarcoidosis, nodular regenerative hyperplasia'],
        ['Intra-hepatic\n(Sinusoidal)', 'At liver sinusoidal level', 'Cirrhosis (most common overall), '
         'alcoholic hepatitis, NASH/NAFLD, viral hepatitis'],
        ['Post-hepatic', 'Hepatic veins or IVC', 'Budd-Chiari syndrome, right heart failure, '
         'constrictive pericarditis, hepatic veno-occlusive disease (SOS)'],
    ]
    cdt = Table(class_data, colWidths=[(W-44*mm)*0.2, (W-44*mm)*0.25, (W-44*mm)*0.55], repeatRows=1)
    cdt.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), RED),
        ('TEXTCOLOR', (0,0), (-1,0), WHITE),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE', (0,0), (-1,-1), 8.5),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [WHITE, RED_LIGHT]),
        ('GRID', (0,0), (-1,-1), 0.5, HexColor('#BDC3C7')),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('LEFTPADDING', (0,0), (-1,-1), 4),
        ('RIGHTPADDING', (0,0), (-1,-1), 4),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ]))
    story.append(cdt)
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Pathophysiology of Portal Hypertension', s['section']))
    story.append(Paragraph(
        'The fundamental mechanism involves two components:', s['body']))
    path_bullets = [
        '<b>Increased vascular resistance</b> — In cirrhosis, hepatic stellate cells (activated by injury) '
        'deposit collagen in the space of Disse, compressing sinusoids. These activated stellate cells '
        'also contract (act like pericytes), further increasing resistance. Fibrous bands distort and '
        'compress portal venules.',
        '<b>Increased portal blood flow</b> — As a secondary mechanism, splanchnic vasodilation occurs '
        'due to elevated nitric oxide (NO), prostacyclin, and glucagon. This vasodilation increases '
        'splanchnic blood flow, worsening the already elevated portal pressure. This is the "forward "flow" '
        'hypothesis.',
    ]
    for b in path_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))

    story.append(Spacer(1, 3*mm))
    story.append(Paragraph('Consequences of Portal Hypertension', s['subsection']))
    consq_bullets = [
        '<b>Splenomegaly</b> — backpressure causes splenic enlargement; hypersplenism leads to thrombocytopenia, '
        'leukopenia, and anemia.',
        '<b>Ascites</b> — elevated portal pressure + hypoalbuminemia shifts Starling forces toward fluid '
        'accumulation in the peritoneal cavity.',
        '<b>Portosystemic collaterals / varices</b> — esophageal, gastric, rectal, and abdominal wall '
        'varices form (see Chapter 8).',
        '<b>Hepatic encephalopathy</b> — toxins (notably NH₃) bypass the liver through portosystemic '
        'shunts and enter systemic circulation, crossing the blood–brain barrier.',
        '<b>Hepatorenal syndrome</b> — profound splanchnic vasodilation with compensatory renal '
        'vasoconstriction leads to functional renal failure in end-stage cirrhosis.',
        '<b>Spontaneous bacterial peritonitis (SBP)</b> — translocation of gut bacteria across the '
        'intestinal wall (facilitated by portal hypertension) infects ascitic fluid.',
    ]
    for b in consq_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # CHAPTER 8 — VARICES & CAPUT MEDUSAE
    # ══════════════════════════════════════════════════════════════════════════
    story.append(chapter_block('Chapter 8: Varices, Caput Medusae & Hemorrhoids', PURPLE))
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Esophageal Varices', s['section']))
    story.append(clinical_box(
        'Esophageal Varices — Most Dangerous Complication',
        'When the left gastric (coronary) vein drains backward through esophageal submucosal veins '
        'into the azygos vein (systemic), these veins dilate to form esophageal varices. They appear '
        'in the lower third of the esophagus. Rupture causes massive upper GI hemorrhage with '
        'mortality approximately 20–40% per episode. Fatal in ~60% of cases if uncontrolled '
        '(Color Atlas of Human Anatomy). Recurrent bleeding risk is 60–70% within 1–2 years without '
        'treatment.', s))
    story.append(Spacer(1, 3*mm))
    esoph_bullets = [
        '<b>Anatomy</b>: Left gastric vein (portal) ↔ Esophageal veins ↔ Azygos vein (SVC)',
        '<b>Location</b>: Lower 3–4 cm of esophagus, just above the gastroesophageal junction',
        '<b>Detection</b>: Upper GI endoscopy (gold standard); classified Grades I–IV',
        '<b>Risk factor for bleeding</b>: Variceal size (large), red wale signs on endoscopy, severity of liver disease (Child-Pugh class)',
        '<b>Management</b>: Acute — vasoactive drugs (terlipressin, octreotide) + endoscopic band ligation (EBL) ± antibiotic prophylaxis. Secondary prophylaxis: non-selective beta-blockers (propranolol/carvedilol) + repeat EBL. Refractory: TIPS (transjugular intrahepatic portosystemic shunt)',
    ]
    for b in esoph_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))

    story.append(Spacer(1, 4*mm))
    story.append(Paragraph('Caput Medusae', s['section']))
    story.append(clinical_box(
        'Caput Medusae — Sign of Portal Hypertension',
        'Dilation of para-umbilical veins that radiate from the umbilicus across the abdominal wall. '
        'The para-umbilical veins (normally obliterated remnants of the fetal umbilical vein, running '
        'in the ligamentum teres / falciform ligament) communicate between the left portal vein and '
        'the superficial epigastric veins (SVC and IVC territories). In portal hypertension, blood '
        'flows outward from the umbilicus in all directions, producing the "head of Medusa" appearance.', s))
    story.append(Spacer(1, 3*mm))
    story.append(Paragraph(
        'The pattern of flow direction in the abdominal wall veins helps differentiate portal '
        'hypertension from IVC obstruction:', s['body']))
    veindif_data = [
        ['', 'Portal Hypertension', 'IVC Obstruction'],
        ['Flow above umbilicus', 'Upward (normal)', 'Upward (normal — toward SVC)'],
        ['Flow below umbilicus', 'Downward (normal)', 'Upward (reversed — bypassing IVC)'],
        ['Origin of dilation', 'Umbilicus (caput medusae)', 'Entire lateral abdominal wall'],
    ]
    vdt = Table(veindif_data, colWidths=[(W-44*mm)*0.3, (W-44*mm)*0.35, (W-44*mm)*0.35], repeatRows=1)
    vdt.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), PURPLE),
        ('TEXTCOLOR', (0,0), (-1,0), WHITE),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE', (0,0), (-1,-1), 9),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [WHITE, PURPLE_LIGHT]),
        ('GRID', (0,0), (-1,-1), 0.5, HexColor('#BDC3C7')),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
        ('LEFTPADDING', (0,0), (-1,-1), 5),
        ('RIGHTPADDING', (0,0), (-1,-1), 5),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ]))
    story.append(vdt)
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Rectal / Anorectal Varices & Hemorrhoids', s['section']))
    story.append(Paragraph(
        'The superior rectal vein (portal via IMV) anastomoses with the middle and inferior rectal '
        'veins (internal iliac → IVC). When portal pressure rises, the superior rectal vein distends, '
        'producing <b>anorectal varices</b>. These are distinct from hemorrhoids (which are enlarged '
        'anal cushions) but clinically present with rectal bleeding. Hemorrhoids may coexist.',
        s['body']))
    story.append(Spacer(1, 3*mm))

    story.append(Paragraph('Gastric Varices', s['section']))
    story.append(Paragraph(
        'Short gastric veins (from fundus, draining into splenic vein) and the left gastric vein '
        'both dilate in portal hypertension, forming <b>gastric varices</b> at the fundus and cardia. '
        'These are present in ~20% of portal hypertension patients. They bleed less often than '
        'esophageal varices but are harder to control once they do. <b>Cyanoacrylate glue injection</b> '
        'is preferred over band ligation for gastric varices.', s['body']))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # CHAPTER 9 — INVESTIGATIONS
    # ══════════════════════════════════════════════════════════════════════════
    story.append(chapter_block('Chapter 9: Investigations & Imaging of the Portal System', TEAL))
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Ultrasound with Doppler', s['section']))
    story.append(Paragraph(
        '<b>First-line investigation.</b> Assesses portal vein patency, direction of flow '
        '(hepatopetal vs. hepatofugal), portal vein diameter (>13 mm suggests portal hypertension), '
        'spleen size, ascites, and presence of collaterals. Doppler also measures flow velocities.',
        s['body']))

    story.append(Paragraph('CT & MR Angiography / Venography', s['section']))
    story.append(Paragraph(
        'Contrast-enhanced CT or MRI provides detailed 3D visualization of the portal system, '
        'including portal vein thrombosis, tumour encasement, collaterals, and hepatic vein patency. '
        '<b>MR venography (MRV)</b> with gadolinium allows simultaneous arterial and venous phase '
        'imaging. Essential for surgical planning (TIPS, liver transplant, hepatic resection).',
        s['body']))

    story.append(Paragraph('Measurement of Portal Venous Pressure', s['section']))
    press_bullets = [
        '<b>Hepatic Venous Pressure Gradient (HVPG)</b>: Gold standard. A balloon catheter is wedged '
        'in a hepatic vein (WHVP — wedged hepatic venous pressure, which approximates sinusoidal/portal '
        'pressure) and the free hepatic venous pressure (FHVP) is measured. HVPG = WHVP − FHVP. '
        'Normal < 5 mmHg; clinically significant portal HTN > 10 mmHg; bleed risk > 12 mmHg.',
        '<b>CO₂ wedged hepatic venography</b>: CO₂ injected into a wedged hepatic vein fills retrograde '
        'through sinusoids to portal vein branches, visualizing the portal system without contrast dye.',
        '<b>Direct percutaneous transhepatic portal vein measurement</b>: Rarely needed but gives exact '
        'portal pressure.',
    ]
    for b in press_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))

    story.append(Paragraph('Upper GI Endoscopy', s['section']))
    story.append(Paragraph(
        'Mandatory screening for varices in all patients with cirrhosis or portal hypertension. '
        'Allows visualization, grading, and treatment (band ligation, sclerotherapy) of esophageal '
        'and gastric varices.', s['body']))

    story.append(Spacer(1, 3*mm))
    story.append(key_fact(
        'Portal Vein Thrombosis (PVT)',
        'Acute PVT presents with abdominal pain, fever, and intestinal ischemia if severe. '
        'Chronic PVT leads to cavernous transformation (a network of collateral veins bypassing '
        'the thrombosed segment) and portal hypertension. Causes: cirrhosis, hypercoagulable states '
        '(JAK2 mutation in myeloproliferative disorders, antiphospholipid syndrome), sepsis, '
        'pancreatitis, abdominal surgery. Management: anticoagulation (LMWH/warfarin) for acute PVT; '
        'TIPS for symptomatic cavernous transformation.', s))
    story.append(PageBreak())

    # ══════════════════════════════════════════════════════════════════════════
    # CHAPTER 10 — MANAGEMENT
    # ══════════════════════════════════════════════════════════════════════════
    story.append(chapter_block('Chapter 10: Management Principles', ORANGE))
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('Non-pharmacological & Pharmacological Approaches', s['section']))
    mgmt_data = [
        ['Condition', 'First-Line Treatment', 'Second-Line / Alternatives'],
        ['Acute variceal\nhemorrhage', 'IV terlipressin or octreotide + endoscopic band ligation (EBL); IV antibiotics (norfloxacin/ceftriaxone)', 'Balloon tamponade (Sengstaken-Blakemore); TIPS; surgical shunts (rarely)'],
        ['Primary prophylaxis\n(prevent first bleed)', 'Non-selective beta-blockers (propranolol, carvedilol) OR EBL for high-risk varices', 'Combined NSBB + EBL if large varices'],
        ['Secondary prophylaxis\n(prevent re-bleed)', 'Non-selective beta-blockers + repeat EBL sessions', 'TIPS; surgical porto-caval or splenorenal shunt; liver transplant'],
        ['Ascites', 'Low-sodium diet + diuretics (spironolactone ± furosemide)', 'Large-volume paracentesis + IV albumin; TIPS; liver transplant'],
        ['Hepatic\nencephalopathy', 'Lactulose + rifaximin; treat precipitant; dietary protein adjustment', 'TIPS reduction; liver transplant'],
        ['Budd-Chiari\nsyndrome', 'Anticoagulation; treat underlying cause (e.g. JAK2 inhibitor)', 'Angioplasty/stenting; TIPS; liver transplant'],
    ]
    mt = Table(mgmt_data, colWidths=[(W-44*mm)*0.22, (W-44*mm)*0.4, (W-44*mm)*0.38], repeatRows=1)
    mt.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,0), ORANGE),
        ('TEXTCOLOR', (0,0), (-1,0), WHITE),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE', (0,0), (-1,-1), 8.5),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [WHITE, ORANGE_LIGHT]),
        ('GRID', (0,0), (-1,-1), 0.5, HexColor('#BDC3C7')),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('LEFTPADDING', (0,0), (-1,-1), 4),
        ('RIGHTPADDING', (0,0), (-1,-1), 4),
        ('TOPPADDING', (0,0), (-1,-1), 3),
        ('BOTTOMPADDING', (0,0), (-1,-1), 3),
    ]))
    story.append(mt)
    story.append(Spacer(1, 4*mm))

    story.append(Paragraph('TIPS — Transjugular Intrahepatic Portosystemic Shunt', s['section']))
    story.append(Paragraph(
        'TIPS creates an artificial communication <b>between a hepatic vein and an intrahepatic '
        'branch of the portal vein</b> using a metallic expandable stent, placed via the jugular '
        'vein under fluoroscopic guidance. This bypasses the high-resistance cirrhotic liver, '
        'reducing portal pressure dramatically. Indications: refractory variceal bleeding, '
        'refractory ascites, Budd-Chiari syndrome. Main complication: hepatic encephalopathy '
        '(30–40%) due to bypass of liver\'s detoxification function.', s['body']))

    story.append(Spacer(1, 3*mm))
    story.append(Paragraph('Surgical Shunts', s['section']))
    shunt_bullets = [
        '<b>Portacaval shunt</b> (end-to-side or side-to-side): Most effective at lowering portal pressure '
        'but high encephalopathy rate (30–50%). Rarely performed since TIPS.',
        '<b>Distal splenorenal shunt (Warren shunt)</b>: Anastomoses the distal splenic vein to the left '
        'renal vein, selectively decompressing the spleen/esophageal varices while preserving hepatic '
        'portal flow. Lower encephalopathy rate.',
        '<b>Mesocaval shunt</b>: SMV to IVC; useful when portal vein is thrombosed.',
        '<b>Liver transplantation</b>: Definitive treatment in end-stage liver disease. Cures both the '
        'underlying disease and portal hypertension.',
    ]
    for b in shunt_bullets:
        story.append(Paragraph(f'• {b}', s['bullet']))

    story.append(Spacer(1, 4*mm))
    story.append(HRFlowable(color=DEEP_BLUE, thickness=1.5, width='100%'))
    story.append(Spacer(1, 3*mm))
    story.append(Paragraph(
        '<b>Sources:</b> Gray\'s Anatomy for Students (9780323934237) | Guyton & Hall Textbook of Medical Physiology '
        '(9780443111013) | Yamada\'s Textbook of Gastroenterology 7e (9781119600169) | Color Atlas of Human '
        'Anatomy Vol 2 (9783132424487) | Mulholland & Greenfield\'s Surgery 7e (9781975143169) | Medical '
        'Physiology (9780323319737)',
        ParagraphStyle('src', fontName='Helvetica-Oblique', fontSize=8, textColor=GRAY_MID,
                       leading=12, alignment=TA_CENTER)))
    story.append(PageBreak())

    # ─── Build PDF ────────────────────────────────────────────────────────────
    doc.build(
        story,
        onFirstPage=cover,
        onLaterPages=page_cb
    )
    print(f'PDF built successfully: {OUT}')
    return OUT

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

cd /home/daytona/workspace/portal-venous-system && python build_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/portal-venous-system/Hepatic_Portal_Venous_System…

Here is the complete, comprehensive coverage of the hepatic venous portal system, followed by your downloadable PDF.

Hepatic Venous Portal System — Complete Overview


1. What Is the Hepatic Portal System?

The hepatic portal system is a special venous arrangement where blood from the GI tract, spleen, pancreas, and gallbladder is delivered to the liver before returning to the heart. This enables the liver to process absorbed nutrients, neutralize toxins, and regulate metabolites. It is one of only two portal circulations in the human body (the other being the hypothalamo-hypophyseal portal system).

2. Formation of the Portal Vein

The hepatic portal vein (HPV) forms posterior to the neck of the pancreas at the level of L1–L2 by the junction of:
  • Superior mesenteric vein (SMV) — right side
  • Splenic vein (SV) — left side
The inferior mesenteric vein (IMV) drains into the splenic vein in ~65%, into the SMV in ~30%, or at the SMV-SV junction in ~5%.
The portal vein is 5–8 cm long and 1–1.2 cm in diameter, carrying roughly 1,050 mL/min of blood.
Hepatic Portal System Overview

3. Course Through the Hepatoduodenal Ligament

The portal vein ascends in the hepatoduodenal ligament (free edge of lesser omentum):
  • Lies posterior to both the bile duct and hepatic artery
  • Common bile duct is to the right; hepatic artery proper is to the left
  • All three structures form the anterior boundary of the epiploic foramen of Winslow

4. Tributaries — Full List

Three main tributaries (forming the portal vein):
  • Superior mesenteric vein
  • Splenic vein
  • Inferior mesenteric vein (draining into SV or SMV)
Direct tributaries joining the HPV trunk:
  • Left gastric (coronary) vein — most important clinically (forms esophageal varices)
  • Right gastric vein
  • Cystic vein (from gallbladder → right portal branch)
  • Para-umbilical veins (ligamentum teres → left portal branch)
  • Posterior superior pancreaticoduodenal vein
Tributaries of SMV: jejunal & ileal veins, right gastro-omental, ileocolic, right colic, middle colic, pancreaticoduodenal veins.
Tributaries of Splenic vein: short gastric veins, left gastro-omental vein, pancreatic veins.
(Source: Color Atlas of Human Anatomy, Thieme)

5. Intrahepatic Distribution

At the porta hepatis, the portal vein divides into:
  • Right branch → anterior (segments V, VIII) + posterior (segments VI, VII) branches
  • Left branch → gives caudate branches → umbilical part → segments II, III, IV
The caudate lobe (segment I) receives branches from both right and left portal veins and drains directly into the IVC — this explains its sparing in Budd-Chiari syndrome.
Within the lobule: Portal blood flows through the portal triad (portal venule + hepatic arteriole + bile ductule) → sinusoids → space of Disse (exchange) → central vein (terminal hepatic venule) → sublobular/hepatic veins → IVC.
Liver Lobule Microanatomy

6. Hepatic Veins (Outflow)

Three main hepatic veins drain into the IVC just below the diaphragm:
VeinTerritory
Right hepatic veinSegments VI, VII
Middle hepatic veinSegments IV, V, VIII
Left hepatic veinSegments II, III
Caudate veins (multiple)Segment I → direct to IVC
MRA Portal & Hepatic Veins
(MR angiography showing SMV → MPV → RPV/LPV → RHV/MHV/LHV. Source: Yamada's Gastroenterology)

7. Portosystemic Anastomoses

These are the four key sites where the portal and systemic venous systems communicate:
Netter's Portal System with Anastomoses
SitePortal SideSystemic SideClinical Consequence
Lower esophagusLeft gastric veinAzygos → SVCEsophageal varices
UmbilicusPara-umbilical veinsSuperficial epigastric → SVC/IVCCaput medusae
RectumSuperior rectal → IMVMiddle & inferior rectal → IVCRectal varices / hemorrhoids
RetroperitoneumRetroperitoneal bowel veinsLumbar/renal → IVCRetroperitoneal collaterals
Additional minor sites: bare area of liver (diaphragm), retroperitoneal gut (ascending/descending colon).

8. Hemodynamics

  • Total hepatic flow: ~1,350 mL/min (27% of cardiac output)
  • Portal vein provides 75–80% of flow, hepatic artery 20–25%
  • Portal vein oxygen saturation ~85%; contributes ~50–60% of liver's O₂
  • Normal portal pressure: 5–10 mmHg; normal HVPG: < 5 mmHg
  • Clinically significant portal hypertension: HVPG > 10 mmHg
  • Variceal bleed risk threshold: HVPG > 12 mmHg
Hepatic Arterial Buffer Response (HABR): When portal flow falls, hepatic arterial flow increases reflexively (via adenosine washout) to preserve total hepatic perfusion.

9. Clinical Correlates

Portal Hypertension

  • Most common cause: cirrhosis (sinusoidal obstruction)
  • Classification: Pre-hepatic | Intra-hepatic (pre/sinusoidal) | Post-hepatic
  • Pathophysiology: ↑ resistance (stellate cell fibrosis/contraction) + ↑ portal blood flow (splanchnic vasodilation via NO, prostacyclin)
Consequences:
  • Splenomegaly → hypersplenism (↓ platelets, WBC, RBC)
  • Ascites (↑ portal pressure + ↓ albumin)
  • Esophageal/gastric varices → hemorrhage
  • Hepatic encephalopathy (NH₃ bypass)
  • Hepatorenal syndrome
  • Spontaneous bacterial peritonitis

Esophageal Varices

  • Left gastric vein ↔ esophageal veins ↔ azygos
  • Mortality 20–40% per bleed; fatal in ~60% if uncontrolled
  • Treatment: terlipressin/octreotide + endoscopic band ligation; TIPS for refractory bleeding

Caput Medusae

  • Para-umbilical veins dilate, radiating from umbilicus
  • Distinguishable from IVC obstruction by flow direction

Budd-Chiari Syndrome

  • Thrombosis of hepatic veins → post-hepatic portal hypertension
  • Caudate lobe spared (direct IVC drainage) — pathognomonic on imaging
  • Causes: myeloproliferative disorders (JAK2 mutation), antiphospholipid syndrome, OCP use

10. Key Investigations

  • Doppler US — first-line; portal vein diameter > 13 mm, flow direction
  • HVPG — gold standard pressure measurement (wedged hepatic venogram)
  • CT/MR venography — 3D visualization, surgical planning
  • Upper GI endoscopy — variceal detection, grading, and treatment

PDF Download

The complete 10-chapter PDF (2.6 MB, A4, fully colorful with tables, color-coded chapters, anatomy images, and clinical tables) is ready:

Hepatic Portal Venous System

PDF Document · PDF

The PDF contains:
  • Colorful cover page with deep blue gradient and gold accents
  • Table of contents (10 chapters)
  • 10 color-coded chapters - each with a distinct color scheme (deep blue, teal, orange, red, green, purple)
  • Anatomical images from Netter, Guyton & Hall, Yamada's Gastroenterology, Color Atlas of Human Anatomy, and MR angiography
  • Color-coded tables for tributaries, Couinaud segments, hemodynamics, anastomoses, management
  • Clinical highlight boxes for key correlates
  • Complete management table for portal hypertension and its complications
Sources: Gray's Anatomy for Students | Guyton & Hall Textbook of Medical Physiology | Yamada's Textbook of Gastroenterology 7e | Color Atlas of Human Anatomy Vol. 2 (Thieme) | Mulholland & Greenfield's Surgery 7e | Medical Physiology (Boron & Boulpaep)
This is a shared conversation. Sign in to Orris to start your own chat.