Explain the complete anatomy of the liver with the help of images. Also explain the clinical correlates along the content

Reading File
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Loading Image
Loading Image
Loading Image
Finding Sources
Finding Sources
Finding Sources
Reading File
Finding Sources
Reading File
Reading File
Loading Image
Reading File
Loading Image
Reading File
I now have comprehensive content from multiple authoritative textbooks along with 5 excellent images. Let me compile the complete answer.

Complete Anatomy of the Liver

Sources: Bailey & Love's Short Practice of Surgery 28th ed., Gray's Anatomy for Students, Guyton & Hall Textbook of Medical Physiology, Yamada's Textbook of Gastroenterology 7th ed., Miller's Anesthesia 10th ed.

1. Overview and General Features

The liver is the largest solid organ in the body, weighing approximately 1.5 kg (about 2% of total body weight) in the average adult. It sits in the right upper quadrant of the abdomen beneath the right hemidiaphragm. It is a metabolically indispensable organ - anhepatic humans survive only 24-48 hours. Uniquely, the liver is the only solid organ that regenerates, recovering up to 90-100% of its previous volume following resection.

2. Embryology

The primordial liver first appears at the end of gestational week 3 as the "hepatic diverticulum" - an outpouching of the distal foregut (future duodenum) composed of proliferating endodermal cells (hepatoblast cords). By week 4, these cords grow cranially into the septum transversum (a mesodermal plate). By week 5, capillary plexuses from the vitelline veins grow into the septum transversum and are enmeshed with the growing epithelial sheets to form the primitive hepatic sinusoids.
The cranial part of the diverticulum becomes the liver; the caudal bud becomes the gallbladder and cystic duct. The stalk of the diverticulum narrows to form the extrahepatic biliary system. The septum transversum mesoderm, stretched between the liver and abdominal wall, forms the falciform, coronary, and triangular ligaments and the Glisson capsule.
Clinical Correlate - Biliary Atresia: Failure of normal bile duct development during embryogenesis leads to biliary atresia, a progressive fibroinflammatory destruction of bile ducts presenting with conjugated hyperbilirubinemia in neonates. It is the most common indication for liver transplantation in children.

3. Ligaments and Peritoneal Reflections

The liver is covered by visceral peritoneum (serosa) with an underlying layer of connective tissue called Glisson's capsule. At the porta hepatis, the capsule envelops portal tracts (triads) carrying branches of the hepatic artery, portal vein, and bile ducts throughout the parenchyma.
Key ligaments include:
LigamentDescriptionClinical Relevance
Falciform ligamentRemnant of the umbilical vein; runs from umbilicus to interlobar fissure; attaches liver to anterior abdominal wallContains ligamentum teres (obliterated umbilical vein); recanalization in portal hypertension (caput medusae)
Left triangular ligamentSuperior surface of left lobe to diaphragmDivision mobilises liver off diaphragm for surgery
Right triangular ligamentRight lobe to undersurface of right hemidiaphragmDivision allows liver to rotate left for right hepatectomy
Lesser omentumBetween stomach and liver; contains hilar structures in its right free edge (hepatoduodenal ligament)Pringle maneuver: clamping the hepatoduodenal ligament controls hepatic inflow during surgery
Coronary ligamentPeritoneal reflections forming the bare area on the posterior surfaceThe bare area is in direct contact with the diaphragm; a site of secondary spread of tumors
Clinical Correlate - Pringle Maneuver: The hepatoduodenal ligament (right free edge of lesser omentum) contains the portal vein (posterior), hepatic artery (medial), and common bile duct (lateral) - this is the basis of the Pringle maneuver, where this ligament is compressed between the thumb and index finger to reduce hepatic inflow and control hemorrhage during liver surgery.

4. Gross Anatomy: Lobes and Surfaces

Traditional (Morphological) Division

The liver has four traditional lobes visible on the visceral surface:
  • Right lobe - the largest
  • Left lobe - smaller; separated from right by the falciform ligament anteriorly
  • Caudate lobe (segment I) - on the posterior surface, between the IVC and ligamentum venosum
  • Quadrate lobe - on the inferior surface, between the gallbladder and ligamentum teres

Surfaces

  • Diaphragmatic surface - convex, smooth, covered by peritoneum except at the bare area
  • Visceral surface - irregular; has impressions from adjacent organs (stomach, duodenum, right kidney, hepatic flexure of colon, gallbladder)
  • Posterior surface - bears the groove for the IVC

5. Couinaud's Segmental Anatomy (Functional)

The most surgically important system divides the liver into 8 independent functional segments (Couinaud's nomenclature), each with its own portal pedicle (portal vein branch + hepatic artery + bile duct) and hepatic venous drainage.
Couinaud's liver segments - functional division. (a) In situ, (b) ex vivo position showing segments I-VIII
Couinaud's Segments - Bailey & Love's Surgery 28th ed. (a) In-situ view showing portal venous branching and (b) ex vivo position with segments labeled I-VIII
Detailed color-coded Couinaud segments showing superior and inferior views
Couinaud's segments with color coding - superior (top) and visceral (bottom) views - Gray's Anatomy for Students
The principal plane (Cantlie's line) divides the liver into left and right halves of approximately equal size. This imaginary line passes through the gallbladder fossa to the IVC, containing the middle hepatic vein within it. Critically, this principal plane does NOT correspond to the falciform ligament.
SegmentNameLocation
ICaudate lobePosterior, between IVC and ligamentum venosum
IILateral superiorLeft lobe, superior
IIILateral inferior (left anterior lateral)Left lobe, inferior
IVMedial (quadrate)Between falciform and gallbladder fossa; IVa (superior) and IVb (inferior)
VAnterior medial inferiorRight lobe, anterior inferior
VIPosterior lateral inferiorRight lobe, posterior inferior
VIIPosterior lateral superiorRight lobe, posterior superior
VIIIPosterior medial superiorRight lobe, superior
Clinical Correlate - Hepatic Resection Surgery: Because segments have independent blood supply and bile drainage, surgeons can remove any individual segment or combination of segments without compromising the remnant liver's vascularity or biliary drainage. A right hepatectomy removes segments V, VI, VII, and VIII, leaving I, II, III, and IV. A left hepatectomy removes II, III, and IV. This segmental precision enables curative resection of hepatic metastases (e.g., from colorectal cancer).

6. Blood Supply - Dual Hepatic Circulation

The liver receives approximately 1350 mL/min of blood (27% of resting cardiac output) via a dual supply:
SupplySourceVolumeOxygen
Portal vein (80%)Venous drainage of GI tract + spleen~1050 mL/minNutrient-rich, partially deoxygenated
Hepatic artery (20%)Coeliac trunk via proper hepatic artery~300 mL/minOxygenated

Portal Vein

Formed by the confluence of the splenic vein and superior mesenteric vein behind the neck of the pancreas. The left branch has a longer (~2 cm) extrahepatic course and incorporates the ligamentum venosum (remnant of ductus venosus).
Portal pressure normally averages ~9 mmHg; hepatic vein pressure ~0 mmHg - a very low gradient (9 mmHg) drives flow through the sinusoids.
Intrahepatic branches of the portal vein showing right/left portal veins and segment distribution
Intrahepatic portal vein branches and their segmental distribution - Yamada's Gastroenterology 7th ed.

Hepatic Artery

  • Arises from the coeliac trunk as the common hepatic artery
  • Gives off the gastroduodenal artery, then becomes the proper hepatic artery
  • Divides into right and left hepatic arteries at a variable level
Arterial variations (surgically important):
  • The right hepatic artery may arise from the superior mesenteric artery (replaced right hepatic artery) - runs posterior to the common bile duct
  • The left hepatic artery may arise from the left gastric artery (replaced left hepatic artery) - runs in the lesser omentum
Clinical Correlate - Portal Hypertension: When portal pressure exceeds 10-12 mmHg (caused by cirrhosis, portal vein thrombosis, or hepatic vein obstruction), blood is shunted through portosystemic collaterals. Key collateral sites:
  • Gastro-oesophageal junction - oesophageal varices (risk of life-threatening haemorrhage)
  • Umbilical veins via ligamentum teres - caput medusae (dilated periumbilical veins visible on abdomen)
  • Superior/inferior haemorrhoidal veins - anorectal varices
  • Retroperitoneal and diaphragmatic - Retzius veins
Clinical Correlate - Hepatic Artery Anatomy in Surgery: Unrecognised arterial variants can lead to inadvertent ligation during cholecystectomy or hepatic resection, causing ischemic biliary strictures or liver infarction.

7. The Porta Hepatis and Hilum

The porta hepatis is a pronounced transverse fissure on the visceral surface of the liver. The hilar structures (running in the hepatoduodenal ligament) enter/exit here:
From anterior to posterior and medial to lateral:
  • Common bile duct - runs anterolaterally in the free edge
  • Hepatic artery proper - medial (left side)
  • Portal vein - posterior
The right and left hepatic ducts emerge at the hilum to form the common hepatic duct, which is joined by the cystic duct from the gallbladder to form the common bile duct (CBD).
Clinical Correlate - Calot's Triangle / Hepatocystic Triangle: Bounded by the cystic duct, common hepatic duct, and inferior edge of the liver. The cystic artery (usually from the right hepatic artery) runs within or near this triangle. Critical structure identification here is mandatory during cholecystectomy to avoid bile duct injuries - the most feared complication of laparoscopic cholecystectomy.

8. Venous Drainage

The liver drains via three main hepatic veins directly into the inferior vena cava (IVC) immediately below the diaphragm:
  • Right hepatic vein - drains segments V, VI, VII, VIII
  • Middle hepatic vein - drains segments IV, V, VIII (runs in the principal plane/Cantlie's line)
  • Left hepatic vein - drains segments II, III (and part of IV)
The caudate lobe (segment I) drains directly into the IVC via multiple short veins - this is why it is spared in Budd-Chiari syndrome.
Additionally, variable short inferior hepatic veins pass directly from the liver parenchyma to the anterior wall of the IVC.
The IVC occupies a groove on the posterior surface of the liver, and the suprahepatic IVC immediately traverses the diaphragm to enter the right atrium.
Clinical Correlate - Budd-Chiari Syndrome: Occlusion of hepatic veins (or IVC) causes congestive hepatopathy, acute liver failure, and ascites. The caudate lobe is typically spared (it drains directly into IVC) and may undergo compensatory hypertrophy - a characteristic radiological finding.
Clinical Correlate - Liver as a Blood Reservoir: The liver stores about 450 mL blood (~10% of total blood volume). In cardiac failure, hepatic venous pressure rises, the liver becomes engorged and tender (cardiac hepatomegaly). Chronic congestion may lead to cardiac cirrhosis ("nutmeg liver" macroscopically).

9. Lymphatic Drainage and Nerve Supply

Lymphatics: The liver produces abundant lymph (25-50% of thoracic duct lymph). Lymphatics drain:
  • Superficial to periportal nodes → coeliac nodes
  • Deep (from spaces of Disse) via interlobular lymphatics to the portal tracts and thence to hilar and mediastinal nodes
  • Some drain through the bare area directly to diaphragmatic lymph nodes
Innervation:
  • Sympathetic (T7-T10): postganglionic, innervate arteries, bile ducts, hepatocytes, Kupffer cells, and stellate cells
  • Parasympathetic: preganglionic fibers from the vagus nerve
  • Fibers enter via the hepatic plexus at the hilum
Clinical Correlate: Referred pain from the liver/biliary tree is felt in the right shoulder (via phrenic nerve, C3-C5) and the right subscapular region (T7-T10 dermatomes). Hepatic capsule stretch (from abscess, hepatomegaly, or acute hepatitis) causes right upper quadrant pain.

10. Microanatomy - The Liver Lobule

The liver contains 50,000-100,000 lobules, each a cylindrical structure ~2 mm in diameter and several mm in length.

Classical (Hexagonal) Lobule

Organized around a central vein (terminal hepatic venule), with six portal tracts at the periphery. Hepatocyte plates radiate like spokes of a wheel from the central vein to the portal tracts.

Rappaport's Acinus (Functional Unit)

The most physiologically meaningful unit. The liver acinus is a diamond-shaped area centered on the terminal portal venule and hepatic arteriole (portal triad axis), with two central veins at opposing poles.
Liver lobule structure showing lobular architecture, liver cell plates, sinusoids, bile canaliculi, Space of Disse, Kupffer cells, and lymphatics
Basic structure of the liver lobule - Guyton & Hall Medical Physiology
Hepatic acinus zones, sinusoidal ultrastructure (Space of Disse, Kupffer cells, stellate cells), and hepatocyte metabolic zonation
Liver acinus zones and hepatocyte metabolic zonation - Miller's Anesthesia 10th ed.

Acinar Zones and Oxygen Gradient

ZoneLocationOxygen TensionPredominant Metabolism
Zone 1 (periportal)Closest to portal triadHigh (60-65 mmHg)Gluconeogenesis, fatty acid oxidation, urea synthesis, oxidative phosphorylation, sulfation, GSH synthesis
Zone 2 (midzone)IntermediateIntermediateIntermediate functions
Zone 3 (perivenous/centrilobular)Closest to central veinLow (30-35 mmHg)Glycolysis, glycogen synthesis from glucose, lipogenesis, ketogenesis, glucuronidation, CYP450 metabolism
Clinical Correlates of Zonal Anatomy:
  • Zone 3 (centrilobular) injury - most susceptible to ischemic necrosis (hypoxia), and to toxins/drugs metabolized by CYP450 (e.g., paracetamol/acetaminophen toxicity - NAPQI generated by CYP2E1 in zone 3 → centrilobular necrosis; right heart failure → centrilobular congestion)
  • Zone 1 (periportal) injury - phosphorus poisoning, eclampsia, Reye syndrome
  • Zone 2 (midzonal) injury - yellow fever

11. Cellular Components of the Liver

Hepatocytes

  • Make up 75-80% of liver cell volume
  • Polygonal cells, 25-40 μm in diameter, with a single central nucleus
  • Three distinct plasma membrane domains:
    1. Sinusoidal (basolateral) - microvilli projecting into space of Disse; active endocytosis and secretion
    2. Lateral (intercellular) - forms bile canaliculi via hemicanaliculi of two adjacent cells with tight junctions
    3. Canalicular (apical) - bile secretion
  • Functions: metabolism, storage, bile production, detoxification, albumin synthesis, clotting factor synthesis

Sinusoidal Cells

Cell TypeRole
Sinusoidal endothelial cellsHighly fenestrated (pores ~1 μm diameter); allow free passage of plasma proteins and large molecules into space of Disse
Kupffer cellsResident hepatic macrophages; phagocytize bacteria, endotoxin, debris; innate immunity
Hepatic stellate cells (Ito cells)Located in space of Disse; store vitamin A (lipocytes); key in fibrogenesis when activated
Pit cellsLarge granular lymphocytes (NK cells); antitumor immunity

Space of Disse (Perisinusoidal Space)

The space between sinusoidal endothelium and hepatocytes. It contains:
  • Hepatic stellate cells
  • Collagen fibers (normally sparse)
  • Connects to lymphatic channels in interlobular septa
Clinical Correlate - Hepatic Fibrosis and Cirrhosis: In chronic liver injury (alcohol, viral hepatitis, NASH), activated hepatic stellate cells transform from fat-storing cells into myofibroblasts, depositing collagen and extracellular matrix. Progressive fibrosis distorts the sinusoidal architecture, increases resistance to portal flow (portal hypertension), and forms regenerative nodules - the hallmarks of cirrhosis. Fibrous tissue contracting around blood vessels greatly increases sinusoidal resistance, perpetuating portal hypertension. NAFLD/NASH is now the most common cause of chronic liver disease in industrialized countries.

12. Biliary System

Bile flows in a direction opposite to blood flow through the sinusoids:
Hepatocyte canaliculi → Canals of Hering (bile ductules) → Interlobular bile ducts (in portal tracts) → Right and left hepatic ducts → Common hepatic duct + cystic duct → Common bile duct (CBD) → Ampulla of Vater → Duodenum
The bile canaliculi are tiny channels formed between adjacent hepatocytes by hemicanaliculi sealed with tight junctions. They are completely surrounded by hepatocyte plasma membranes.
Clinical Correlate - Cholestasis: When bile flow is obstructed (intrahepatic or extrahepatic), bile acids accumulate within hepatocytes and canaliculi. Features include jaundice (conjugated hyperbilirubinaemia), pruritis (bile acid deposition in skin), pale stools, dark urine, and fat-soluble vitamin malabsorption. Causes include gallstones (choledocholithiasis), primary biliary cholangitis (PBC), primary sclerosing cholangitis (PSC), pancreatic head carcinoma, and drug-induced cholestasis.

13. Summary: Key Functions of the Liver

The liver performs a vast array of functions:
  • Metabolic: Glucose homeostasis (glycolysis, gluconeogenesis, glycogen storage), lipid metabolism (cholesterol synthesis, lipoprotein formation, beta-oxidation, ketogenesis), amino acid catabolism, urea synthesis
  • Synthetic: Albumin, clotting factors (I, II, V, VII, VIII, IX, X, XI), complement proteins, angiotensinogen, IGF-1
  • Detoxification: Drug metabolism via CYP450 system, alcohol metabolism, removal of gut endotoxins, bilirubin conjugation
  • Storage: Glycogen, vitamins A, D, E, K, B12, iron (ferritin), copper
  • Immunological: Kupffer cells remove gut-derived bacteria and endotoxin; produces acute-phase proteins
  • Endocrine: Produces IGF-1 (in response to GH), thrombopoietin, and metabolizes hormones

14. Key Clinical Correlates Summary

Anatomical FeatureClinical Significance
Dual blood supply (80/20)Liver is relatively resistant to arterial occlusion alone; portal venous thrombosis is more dangerous
Couinaud segmentsEnables precise anatomical resection for tumors
Zone 3 (centrilobular) locationParacetamol toxicity, ischemic hepatitis, congestive heart failure
Falciform/ligamentum teresRecanalization in portal hypertension → caput medusae
Caudate lobe drains directly to IVCSpared in Budd-Chiari; may hypertrophy compensatorily
Hepatocystic triangleCritical anatomy in cholecystectomy; bile duct injury risk
Hepatoduodenal ligamentBasis of Pringle maneuver for intraoperative hemorrhage control
Glisson's capsuleCapsule stretch → RUQ pain and referred right shoulder pain
Space of Disse + stellate cellsStellate cell activation → fibrosis → cirrhosis
Sinusoidal fenestrationsLoss of fenestrations (capillarization) in cirrhosis reduces hepatocyte function

Sources: Bailey & Love's Short Practice of Surgery 28th ed. | Gray's Anatomy for Students | Guyton & Hall Textbook of Medical Physiology | Yamada's Textbook of Gastroenterology 7th ed. | Miller's Anesthesia 10th ed.

Generate a pdf of it

Reading File
Running Command

ls /home/daytona/workspace/ && python3 -c "import weasyprint; print('weasyprint …

Running Command

mkdir -p /home/daytona/workspace/liver-anatomy-pdf && python3 -c " import urllib…

Writing File

~/liver-anatomy-pdf/generate_pdf.py

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

OUTPUT = "/home/daytona/workspace/liver-anatomy-pdf/Liver_Anatomy_Complete.pdf"
IMG_DIR = "/home/daytona/workspace/liver-anatomy-pdf"

# ── Page setup ────────────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=2*cm, rightMargin=2*cm,
    topMargin=2.5*cm, bottomMargin=2.5*cm,
    title="Complete Anatomy of the Liver",
    author="Orris Medical Education",
    subject="Liver Anatomy with Clinical Correlates"
)

W, H = A4
CONTENT_W = W - 4*cm

# ── Colour palette ─────────────────────────────────────────────────────────────
DARK_BLUE   = colors.HexColor("#1A3A5C")
MED_BLUE    = colors.HexColor("#2C6FAC")
LIGHT_BLUE  = colors.HexColor("#EBF4FF")
ACCENT_RED  = colors.HexColor("#C0392B")
ACCENT_GOLD = colors.HexColor("#D4A017")
CLINICAL_BG = colors.HexColor("#FFF8E7")
CLINICAL_BORDER = colors.HexColor("#E67E22")
TABLE_HEADER = colors.HexColor("#1A3A5C")
TABLE_ROW_ALT = colors.HexColor("#F0F6FF")
GREY_LINE   = colors.HexColor("#CCCCCC")
TEXT_DARK   = colors.HexColor("#1A1A1A")

# ── Styles ─────────────────────────────────────────────────────────────────────
base = getSampleStyleSheet()

title_style = ParagraphStyle("DocTitle",
    fontName="Helvetica-Bold", fontSize=26, textColor=DARK_BLUE,
    alignment=TA_CENTER, spaceAfter=6, leading=32)

subtitle_style = ParagraphStyle("DocSubtitle",
    fontName="Helvetica-Oblique", fontSize=13, textColor=MED_BLUE,
    alignment=TA_CENTER, spaceAfter=4, leading=18)

sources_style = ParagraphStyle("Sources",
    fontName="Helvetica", fontSize=8, textColor=colors.HexColor("#555555"),
    alignment=TA_CENTER, spaceAfter=2, leading=11)

h1_style = ParagraphStyle("H1",
    fontName="Helvetica-Bold", fontSize=16, textColor=DARK_BLUE,
    spaceBefore=18, spaceAfter=6, leading=20,
    borderPad=4)

h2_style = ParagraphStyle("H2",
    fontName="Helvetica-Bold", fontSize=13, textColor=MED_BLUE,
    spaceBefore=12, spaceAfter=4, leading=16)

h3_style = ParagraphStyle("H3",
    fontName="Helvetica-BoldOblique", fontSize=11, textColor=DARK_BLUE,
    spaceBefore=8, spaceAfter=3, leading=14)

body_style = ParagraphStyle("Body",
    fontName="Helvetica", fontSize=10, textColor=TEXT_DARK,
    spaceBefore=3, spaceAfter=3, leading=15, alignment=TA_JUSTIFY)

bullet_style = ParagraphStyle("Bullet",
    fontName="Helvetica", fontSize=10, textColor=TEXT_DARK,
    spaceBefore=2, spaceAfter=2, leading=14,
    leftIndent=16, firstLineIndent=-10)

clinical_title_style = ParagraphStyle("ClinTitle",
    fontName="Helvetica-Bold", fontSize=10, textColor=CLINICAL_BORDER,
    spaceBefore=2, spaceAfter=2, leading=14)

clinical_body_style = ParagraphStyle("ClinBody",
    fontName="Helvetica", fontSize=10, textColor=TEXT_DARK,
    spaceBefore=2, spaceAfter=2, leading=14, alignment=TA_JUSTIFY)

caption_style = ParagraphStyle("Caption",
    fontName="Helvetica-Oblique", fontSize=8.5, textColor=colors.HexColor("#444444"),
    alignment=TA_CENTER, spaceBefore=3, spaceAfter=6, leading=12)

# ── Helper functions ───────────────────────────────────────────────────────────

def section_header(num, text):
    """Returns a numbered section heading with blue left-border effect."""
    return [
        HRFlowable(width="100%", thickness=2, color=DARK_BLUE, spaceAfter=4),
        Paragraph(f"{num}. {text}", h1_style),
    ]

def sub_header(text):
    return Paragraph(text, h2_style)

def sub_sub_header(text):
    return Paragraph(text, h3_style)

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

def bullet(text):
    return Paragraph(f"• {text}", bullet_style)

def spacer(h=0.3):
    return Spacer(1, h*cm)

def clinical_box(title, text):
    """Orange-bordered clinical correlate box."""
    content = [
        Paragraph(f"🩺 Clinical Correlate: {title}", clinical_title_style),
        Paragraph(text, clinical_body_style),
    ]
    t = Table([[content]], colWidths=[CONTENT_W - 1*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), CLINICAL_BG),
        ('BOX', (0,0), (-1,-1), 1.5, CLINICAL_BORDER),
        ('LEFTPADDING', (0,0), (-1,-1), 10),
        ('RIGHTPADDING', (0,0), (-1,-1), 10),
        ('TOPPADDING', (0,0), (-1,-1), 8),
        ('BOTTOMPADDING', (0,0), (-1,-1), 8),
        ('ROUNDEDCORNERS', [4, 4, 4, 4]),
    ]))
    return [spacer(0.2), t, spacer(0.2)]

def make_table(headers, rows, col_widths=None):
    """Styled data table with alternating rows."""
    if col_widths is None:
        col_widths = [CONTENT_W / len(headers)] * len(headers)
    data = [[Paragraph(f"<b><font color='white'>{h}</font></b>", ParagraphStyle(
                'th', fontName='Helvetica-Bold', fontSize=9, textColor=colors.white,
                alignment=TA_CENTER, leading=12)) for h in headers]]
    for i, row in enumerate(rows):
        data.append([Paragraph(str(cell), ParagraphStyle(
            'td', fontName='Helvetica', fontSize=9, textColor=TEXT_DARK,
            leading=13, spaceBefore=1)) for cell in row])
    t = Table(data, colWidths=col_widths)
    style = [
        ('BACKGROUND', (0,0), (-1,0), TABLE_HEADER),
        ('GRID', (0,0), (-1,-1), 0.5, GREY_LINE),
        ('TOPPADDING', (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
        ('RIGHTPADDING', (0,0), (-1,-1), 6),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
    ]
    for i in range(1, len(data)):
        if i % 2 == 0:
            style.append(('BACKGROUND', (0,i), (-1,i), TABLE_ROW_ALT))
    t.setStyle(TableStyle(style))
    return [spacer(0.2), t, spacer(0.3)]

def img_block(filename, caption, max_w=None, max_h=8*cm):
    """Image with caption, scaled to fit."""
    path = os.path.join(IMG_DIR, filename)
    if not os.path.exists(path):
        return []
    from PIL import Image as PILImg
    with PILImg.open(path) as im:
        iw, ih = im.size
    mw = max_w or (CONTENT_W - 0.5*cm)
    scale = min(mw/iw, max_h/ih, 1.0)
    rw, rh = iw*scale, ih*scale
    img = Image(path, width=rw, height=rh)
    img.hAlign = 'CENTER'
    return [spacer(0.3), img, Paragraph(caption, caption_style), spacer(0.2)]

# ── Build story ────────────────────────────────────────────────────────────────
story = []

# ── Cover / Title Block ───────────────────────────────────────────────────────
story.append(spacer(1.5))
story.append(Paragraph("Complete Anatomy of the Liver", title_style))
story.append(Paragraph("With Clinical Correlates", subtitle_style))
story.append(spacer(0.4))
story.append(HRFlowable(width="80%", thickness=3, color=ACCENT_GOLD, hAlign='CENTER', spaceAfter=10))
story.append(spacer(0.4))
story.append(Paragraph(
    "Sources: Bailey &amp; Love's Short Practice of Surgery 28th ed. | Gray's Anatomy for Students | "
    "Guyton &amp; Hall Textbook of Medical Physiology | Yamada's Textbook of Gastroenterology 7th ed. | "
    "Miller's Anesthesia 10th ed.",
    sources_style))
story.append(spacer(2))

# ── Section 1: Overview ───────────────────────────────────────────────────────
story.extend(section_header("1", "Overview and General Features"))
story.append(body(
    "The liver is the <b>largest solid organ</b> in the body, weighing approximately 1.5 kg "
    "(about 2% of total body weight) in the average adult. It sits in the right upper quadrant "
    "of the abdomen beneath the right hemidiaphragm. It is a metabolically indispensable organ "
    "— anhepatic humans survive only 24–48 hours. Uniquely, the liver is the <b>only solid organ "
    "that regenerates</b>, recovering up to 90–100% of its previous volume following resection."
))
story.append(spacer())

# ── Section 2: Embryology ─────────────────────────────────────────────────────
story.extend(section_header("2", "Embryology"))
story.append(body(
    "The primordial liver first appears at the end of gestational <b>week 3</b> as the "
    "\"hepatic diverticulum\" — an outpouching of the distal foregut (future duodenum) "
    "composed of proliferating endodermal cells (hepatoblast cords). By week 4, these cords "
    "grow cranially into the <b>septum transversum</b>. By week 5, capillary plexuses from the "
    "vitelline veins are enmeshed with the growing epithelial sheets to form the "
    "<b>primitive hepatic sinusoids</b>."
))
story.append(body(
    "The cranial part of the diverticulum becomes the liver; the caudal bud becomes the "
    "<b>gallbladder and cystic duct</b>. The stalk narrows to form the extrahepatic biliary system. "
    "The septum transversum mesoderm forms the <b>falciform, coronary, triangular ligaments</b> "
    "and the <b>Glisson capsule</b>."
))
story.extend(clinical_box(
    "Biliary Atresia",
    "Failure of normal bile duct development during embryogenesis leads to biliary atresia — a "
    "progressive fibroinflammatory destruction of bile ducts presenting with conjugated "
    "hyperbilirubinemia in neonates. It is the most common indication for liver transplantation "
    "in children."
))

# ── Section 3: Ligaments ──────────────────────────────────────────────────────
story.extend(section_header("3", "Ligaments and Peritoneal Reflections"))
story.append(body(
    "The liver is covered by <b>visceral peritoneum (serosa)</b> with an underlying layer of "
    "connective tissue called <b>Glisson's capsule</b>. At the porta hepatis, the capsule "
    "envelops portal tracts carrying branches of the hepatic artery, portal vein, and bile ducts."
))
story.append(spacer(0.2))
story.extend(make_table(
    ["Ligament", "Description", "Clinical Relevance"],
    [
        ["Falciform ligament", "Remnant of the umbilical vein; runs from umbilicus to interlobar fissure", "Contains ligamentum teres; recanalization in portal hypertension → caput medusae"],
        ["Left triangular ligament", "Superior surface of left lobe to diaphragm", "Division mobilises liver from diaphragm for surgery"],
        ["Right triangular ligament", "Right lobe to right hemidiaphragm", "Division allows liver rotation left for right hepatectomy"],
        ["Lesser omentum / hepatoduodenal ligament", "Between stomach and liver; hilar structures in right free edge", "Basis of Pringle maneuver for hemorrhage control"],
        ["Coronary ligament / bare area", "Peritoneal reflections forming the bare area posteriorly", "Direct contact with diaphragm; site of secondary tumor spread"],
    ],
    col_widths=[4*cm, 6*cm, 6.5*cm]
))
story.extend(clinical_box(
    "Pringle Maneuver",
    "The hepatoduodenal ligament contains: portal vein (posterior), hepatic artery (medial), "
    "and common bile duct (lateral). Compressing this between thumb and index finger "
    "(Pringle maneuver) temporarily occludes hepatic inflow, controlling hemorrhage during "
    "liver surgery. Warm ischemia is generally tolerated for up to 60 minutes."
))

# ── Section 4: Gross Anatomy ──────────────────────────────────────────────────
story.extend(section_header("4", "Gross Anatomy: Lobes and Surfaces"))
story.append(sub_header("Traditional (Morphological) Division"))
story.append(body("The liver has <b>four traditional lobes</b> visible on the visceral surface:"))
for item in [
    "<b>Right lobe</b> — the largest",
    "<b>Left lobe</b> — smaller; separated from right by the falciform ligament anteriorly",
    "<b>Caudate lobe (segment I)</b> — posterior surface, between IVC and ligamentum venosum",
    "<b>Quadrate lobe</b> — inferior surface, between the gallbladder and ligamentum teres",
]:
    story.append(bullet(item))
story.append(spacer(0.3))
story.append(sub_header("Surfaces"))
story.extend(make_table(
    ["Surface", "Description"],
    [
        ["Diaphragmatic", "Convex, smooth, covered by peritoneum except at the bare area"],
        ["Visceral", "Irregular; impressions from stomach, duodenum, right kidney, hepatic flexure, gallbladder"],
        ["Posterior", "Bears the groove for the IVC"],
    ],
    col_widths=[5*cm, 11.5*cm]
))

# ── Section 5: Couinaud Segments ──────────────────────────────────────────────
story.extend(section_header("5", "Couinaud's Segmental Anatomy (Functional)"))
story.append(body(
    "The most surgically important classification divides the liver into <b>8 independent "
    "functional segments</b> (Couinaud's nomenclature), each with its own portal pedicle "
    "(portal vein branch + hepatic artery + bile duct) and independent hepatic venous drainage. "
    "The <b>principal plane (Cantlie's line)</b> divides the liver into left and right halves of "
    "approximately equal size — it runs from the gallbladder fossa to the IVC and contains the "
    "<b>middle hepatic vein</b>."
))
story.extend(img_block(
    "couinaud_segments.png",
    "Fig. 1 — Couinaud's Functional Segments (a) in-situ view and (b) ex vivo. "
    "(Source: Bailey & Love's Surgery 28th ed.)",
    max_h=9*cm
))
story.extend(img_block(
    "couinaud_color.png",
    "Fig. 2 — Color-coded Couinaud segments: superior (top) and visceral (bottom) views. "
    "(Source: Gray's Anatomy for Students)",
    max_h=11*cm
))
story.extend(make_table(
    ["Segment", "Name", "Location"],
    [
        ["I", "Caudate lobe", "Posterior, between IVC and ligamentum venosum"],
        ["II", "Lateral superior", "Left lobe, superior"],
        ["III", "Left anterior lateral / Lateral inferior", "Left lobe, inferior"],
        ["IV (IVa/IVb)", "Medial (Quadrate lobe)", "Between falciform ligament and gallbladder fossa"],
        ["V", "Anterior medial inferior", "Right lobe, anterior inferior"],
        ["VI", "Right anterior lateral / Posterior inferior", "Right lobe, posterior inferior"],
        ["VII", "Posterior lateral superior", "Right lobe, posterior superior"],
        ["VIII", "Posterior medial superior", "Right lobe, superior"],
    ],
    col_widths=[2.5*cm, 5.5*cm, 8.5*cm]
))
story.extend(clinical_box(
    "Hepatic Resection Surgery",
    "Because each Couinaud segment has an independent blood supply and bile drainage, surgeons "
    "can remove any individual segment or combination without compromising the remnant liver. "
    "A right hepatectomy removes segments V, VI, VII, and VIII, leaving I, II, III, and IV. "
    "A left hepatectomy removes II, III, and IV. This segmental precision enables curative "
    "resection of hepatic metastases (e.g., colorectal cancer) and is the basis of living-donor "
    "liver transplantation."
))

# ── Section 6: Blood Supply ───────────────────────────────────────────────────
story.extend(section_header("6", "Blood Supply — Dual Hepatic Circulation"))
story.append(body(
    "The liver receives approximately <b>1350 mL/min</b> of blood (27% of resting cardiac output) "
    "via a dual supply:"
))
story.extend(make_table(
    ["Supply", "Source", "Volume", "Character"],
    [
        ["Portal vein (80%)", "Venous drainage of GI tract + spleen", "~1050 mL/min", "Nutrient-rich, partially deoxygenated"],
        ["Hepatic artery (20%)", "Coeliac trunk → proper hepatic artery", "~300 mL/min", "Fully oxygenated"],
    ],
    col_widths=[3.5*cm, 5.5*cm, 3.5*cm, 4*cm]
))
story.append(sub_header("Portal Vein"))
story.append(body(
    "Formed by the confluence of the <b>splenic vein</b> and <b>superior mesenteric vein</b> "
    "behind the neck of the pancreas. Portal pressure normally ~9 mmHg; hepatic vein pressure ~0 mmHg. "
    "The left branch incorporates the <b>ligamentum venosum</b> (remnant of ductus venosus)."
))
story.extend(img_block(
    "portal_vein.png",
    "Fig. 3 — Intrahepatic branches of the portal vein showing right and left portal veins "
    "and their segmental distribution. (Source: Yamada's Gastroenterology 7th ed.)",
    max_h=8*cm
))
story.append(sub_header("Hepatic Artery"))
story.append(body(
    "Arises from the <b>coeliac trunk</b> as the common hepatic artery → gives off the "
    "gastroduodenal artery → becomes the <b>proper hepatic artery</b> → divides into "
    "<b>right and left hepatic arteries</b>."
))
story.append(body("<b>Surgically important arterial variations:</b>"))
for item in [
    "<b>Replaced right hepatic artery</b> arising from the superior mesenteric artery (SMA) — runs posterior to the CBD",
    "<b>Replaced left hepatic artery</b> arising from the left gastric artery — runs in the lesser omentum",
    "These variants occur in ~20–25% of individuals and must be identified before hepatic or biliary surgery",
]:
    story.append(bullet(item))
story.extend(clinical_box(
    "Portal Hypertension",
    "When portal pressure exceeds 10–12 mmHg, blood shunts through portosystemic collaterals. "
    "Key sites: (1) gastro-oesophageal junction — oesophageal varices (risk of life-threatening "
    "haemorrhage); (2) umbilical veins via ligamentum teres — caput medusae; "
    "(3) superior/inferior haemorrhoidal veins — anorectal varices; "
    "(4) retroperitoneal Retzius veins. Causes include cirrhosis, portal vein thrombosis, "
    "and hepatic vein obstruction (Budd-Chiari)."
))

# ── Section 7: Porta Hepatis ──────────────────────────────────────────────────
story.extend(section_header("7", "Porta Hepatis and Hilum"))
story.append(body(
    "The <b>porta hepatis</b> is a pronounced transverse fissure on the visceral surface. "
    "Hilar structures running in the <b>hepatoduodenal ligament</b> (right free edge of lesser omentum) "
    "enter/exit here:"
))
for item in [
    "<b>Common bile duct</b> — anterolateral",
    "<b>Hepatic artery proper</b> — medial (left side)",
    "<b>Portal vein</b> — posterior",
]:
    story.append(bullet(item))
story.append(body(
    "The right and left hepatic ducts emerge at the hilum to form the <b>common hepatic duct</b>, "
    "joined by the <b>cystic duct</b> from the gallbladder to form the <b>common bile duct (CBD)</b>."
))
story.extend(clinical_box(
    "Calot's Triangle / Hepatocystic Triangle",
    "Bounded by the cystic duct, common hepatic duct, and inferior edge of the liver. "
    "The cystic artery (usually from the right hepatic artery) runs within or near this triangle. "
    "Critical structure identification here is mandatory during cholecystectomy — inadvertent "
    "CBD injury is the most feared complication of laparoscopic cholecystectomy, with an "
    "incidence of 0.3–0.5%."
))

# ── Section 8: Venous Drainage ────────────────────────────────────────────────
story.extend(section_header("8", "Venous Drainage"))
story.append(body(
    "The liver drains via <b>three main hepatic veins</b> directly into the <b>IVC</b> "
    "immediately below the diaphragm:"
))
story.extend(make_table(
    ["Hepatic Vein", "Segments Drained", "Clinical Note"],
    [
        ["Right hepatic vein", "V, VI, VII, VIII", "Can be exposed fully outside the liver parenchyma"],
        ["Middle hepatic vein", "IV, V, VIII", "Runs in the principal plane (Cantlie's line)"],
        ["Left hepatic vein", "II, III (and part of IV)", "Joins middle to form a common trunk in ~80%"],
        ["Short caudate veins (multiple)", "Segment I (caudate lobe)", "Drain directly into IVC — spared in Budd-Chiari"],
    ],
    col_widths=[4*cm, 4.5*cm, 8*cm]
))
story.extend(clinical_box(
    "Budd-Chiari Syndrome",
    "Occlusion of hepatic veins (or IVC) causes congestive hepatopathy, acute liver failure, "
    "and massive ascites. The caudate lobe (segment I) is typically spared because it drains "
    "directly into the IVC via multiple short veins — compensatory caudate hypertrophy is a "
    "characteristic CT/MRI finding that helps confirm the diagnosis."
))
story.extend(clinical_box(
    "Cardiac Hepatomegaly",
    "The liver stores ~450 mL blood (~10% of total blood volume). In right heart failure, "
    "raised hepatic venous pressure causes hepatic congestion and tender hepatomegaly. "
    "Chronic congestion leads to centrilobular necrosis and ultimately 'cardiac cirrhosis' "
    "(macroscopic 'nutmeg liver' appearance with alternating red congested and pale necrotic zones)."
))

# ── Section 9: Lymphatics and Nerves ─────────────────────────────────────────
story.extend(section_header("9", "Lymphatic Drainage and Nerve Supply"))
story.append(sub_header("Lymphatics"))
story.append(body(
    "The liver produces <b>25–50% of thoracic duct lymph</b>. Drainage routes:"
))
for item in [
    "Superficial lymphatics → periportal nodes → coeliac nodes → cisterna chyli",
    "Deep lymphatics (from spaces of Disse) → interlobular channels → portal tracts → hilar nodes",
    "Bare area → diaphragmatic nodes → mediastinal nodes",
]:
    story.append(bullet(item))
story.append(sub_header("Innervation"))
story.extend(make_table(
    ["Type", "Origin", "Distribution"],
    [
        ["Sympathetic", "T7–T10 (postganglionic)", "Arteries, bile ducts, hepatocytes, Kupffer cells, stellate cells"],
        ["Parasympathetic", "Vagus nerve (preganglionic)", "Portal tracts, periportal hepatocytes"],
    ],
    col_widths=[3.5*cm, 5*cm, 8*cm]
))
story.extend(clinical_box(
    "Referred Pain from Liver/Biliary Tree",
    "Hepatic capsule stretch (from abscess, hepatomegaly, or acute hepatitis) causes right upper "
    "quadrant pain. Referred pain is felt in the right shoulder (phrenic nerve, C3–C5) and right "
    "subscapular region (T7–T10 dermatomes) — a classic presentation of biliary colic and "
    "subphrenic abscess."
))

# ── Section 10: Microanatomy ──────────────────────────────────────────────────
story.extend(section_header("10", "Microanatomy — The Liver Lobule"))
story.append(body(
    "The liver contains <b>50,000–100,000 lobules</b>, each a cylindrical structure ~2 mm "
    "in diameter and several mm in length."
))
story.append(sub_header("Classical (Hexagonal) Lobule"))
story.append(body(
    "Organized around a <b>central vein</b> (terminal hepatic venule), with six portal tracts "
    "at the periphery. Hepatocyte plates radiate like spokes of a wheel toward the central vein. "
    "Bile canaliculi run parallel to the sinusoids and drain bile <i>opposite</i> to the "
    "direction of blood flow."
))
story.extend(img_block(
    "lobule_structure.png",
    "Fig. 4 — Basic structure of a liver lobule showing hepatocyte plates, sinusoids, "
    "bile canaliculi, Space of Disse, Kupffer cells, and lymphatics. "
    "(Source: Guyton & Hall Medical Physiology)",
    max_h=9*cm
))
story.append(sub_header("Rappaport's Acinus (Functional Unit)"))
story.append(body(
    "The <b>liver acinus</b> is a diamond-shaped area centered on the <b>terminal portal venule "
    "and hepatic arteriole</b> (the portal triad axis), with two central veins at opposing poles. "
    "It is divided into three zones based on oxygen and nutrient delivery:"
))
story.extends = None
story.extend(make_table(
    ["Zone", "Location", "O₂ Tension", "Predominant Metabolism"],
    [
        ["Zone 1 (periportal)", "Closest to portal triad", "High (60–65 mmHg)", "Gluconeogenesis, fatty acid oxidation, urea synthesis, sulfation, GSH synthesis"],
        ["Zone 2 (midzone)", "Intermediate", "Intermediate", "Mixed; intermediate metabolic functions"],
        ["Zone 3 (perivenous/centrilobular)", "Closest to central vein", "Low (30–35 mmHg)", "Glycolysis, glycogen synthesis, lipogenesis, ketogenesis, glucuronidation, CYP450 drug metabolism"],
    ],
    col_widths=[3.5*cm, 3.5*cm, 3*cm, 6.5*cm]
))
story.extend(img_block(
    "acinus_zones.png",
    "Fig. 5 — (A) Hepatic acinus showing zones 1, 2, 3. (B) Sinusoidal ultrastructure with "
    "Space of Disse, stellate cells, Kupffer cells. (C) Hepatocyte metabolic zonation — "
    "periportal (pp) vs perivenous (pv) pathways. (Source: Miller's Anesthesia 10th ed.)",
    max_h=11*cm
))
story.extend(clinical_box(
    "Zone-Specific Liver Injury",
    "Zone 3 (centrilobular) injury — most susceptible to ischemia (lowest O₂) and to toxins "
    "metabolized by CYP450: paracetamol/acetaminophen toxicity (NAPQI via CYP2E1 → "
    "centrilobular necrosis), right heart failure (congestion → centrilobular necrosis). | "
    "Zone 1 (periportal) injury — phosphorus poisoning, eclampsia of pregnancy, Reye syndrome. | "
    "Zone 2 (midzonal) injury — yellow fever (classic midzonal necrosis, Councilman bodies)."
))

# ── Section 11: Cellular Components ──────────────────────────────────────────
story.extend(section_header("11", "Cellular Components"))
story.append(sub_header("Hepatocytes"))
story.append(body(
    "Hepatocytes make up <b>75–80%</b> of liver cell volume. They are polygonal cells, "
    "25–40 μm in diameter, with a single central nucleus. Three distinct plasma membrane domains:"
))
for item in [
    "<b>Sinusoidal (basolateral) surface</b> — microvilli projecting into the space of Disse; active endocytosis and secretion of plasma proteins",
    "<b>Lateral (intercellular) surface</b> — forms bile canaliculi via hemicanaliculi of two adjacent cells, sealed with tight junctions",
    "<b>Canalicular (apical) surface</b> — bile secretion into the bile canaliculus",
]:
    story.append(bullet(item))
story.append(spacer(0.3))
story.append(sub_header("Sinusoidal Non-Parenchymal Cells"))
story.extend(make_table(
    ["Cell Type", "Location", "Key Function"],
    [
        ["Sinusoidal endothelial cells", "Line sinusoids", "Highly fenestrated (pores ~1 μm) — allow free passage of plasma proteins and lipoproteins into Space of Disse"],
        ["Kupffer cells", "Within sinusoidal lumen", "Resident macrophages; phagocytize bacteria, endotoxin, foreign particles; innate hepatic immunity"],
        ["Hepatic stellate cells (Ito cells)", "Space of Disse", "Store vitamin A (80% of body's retinoids); activated → myofibroblasts → fibrosis/cirrhosis"],
        ["Pit cells", "Sinusoidal lumen", "Large granular lymphocytes (hepatic NK cells); antitumor and antiviral immunity"],
    ],
    col_widths=[4*cm, 4*cm, 8.5*cm]
))
story.append(sub_header("Space of Disse (Perisinusoidal Space)"))
story.append(body(
    "The space between the sinusoidal endothelium and hepatocytes. Contains hepatic stellate cells "
    "and sparse collagen fibers. Connects with interlobular lymphatics. Large fenestrations in "
    "the overlying endothelium allow even large plasma proteins (albumin, lipoproteins) to "
    "diffuse freely into this space, making the liver exceptionally efficient at processing "
    "blood-borne substances."
))
story.extend(clinical_box(
    "Hepatic Fibrosis and Cirrhosis",
    "In chronic liver injury (alcohol, viral hepatitis B/C, NAFLD/NASH), activated hepatic "
    "stellate cells transform from vitamin A-storing cells into myofibroblasts, depositing "
    "collagen (predominantly type I and III) in the Space of Disse. Progressive fibrosis "
    "distorts sinusoidal architecture ('capillarization' — loss of fenestrations), increases "
    "portal resistance, and forms regenerative nodules — the hallmarks of cirrhosis. "
    "NAFLD/NASH is now the most common chronic liver disease in industrialized nations, "
    "strongly associated with obesity and type 2 diabetes."
))

# ── Section 12: Biliary System ─────────────────────────────────────────────────
story.extend(section_header("12", "Biliary System"))
story.append(body(
    "Bile flows <b>opposite to blood flow</b> through the sinusoids:"
))
story.append(Paragraph(
    "<b>Hepatocyte bile canaliculi → Canals of Hering (bile ductules) → "
    "Interlobular bile ducts (in portal tracts) → Right &amp; Left hepatic ducts → "
    "Common hepatic duct + Cystic duct → Common bile duct (CBD) → "
    "Ampulla of Vater → Duodenum</b>",
    ParagraphStyle('pathway', fontName='Helvetica', fontSize=9.5, textColor=MED_BLUE,
                   alignment=TA_CENTER, spaceBefore=8, spaceAfter=8,
                   leading=16, borderPad=8,
                   backColor=LIGHT_BLUE, borderColor=MED_BLUE, borderWidth=1)
))
story.append(body(
    "The <b>bile canaliculi</b> are tiny channels (0.5–1.5 μm diameter) formed between adjacent "
    "hepatocytes by hemicanaliculi, sealed by tight junctions (zona occludens). They are entirely "
    "bounded by hepatocyte plasma membranes — not lined by ductal epithelium. At the interface "
    "with the portal tract, bile enters the <b>Canals of Hering</b> (mixed hepatocyte/cholangiocyte "
    "lining), then the interlobular bile ducts (pure cholangiocyte lining)."
))
story.extend(clinical_box(
    "Cholestasis",
    "When bile flow is obstructed (intrahepatic or extrahepatic), bile acids accumulate. "
    "Features: conjugated hyperbilirubinaemia (jaundice), pruritis (bile acid deposition in skin), "
    "pale stools, dark urine, fat-soluble vitamin deficiency (A, D, E, K). "
    "Causes: choledocholithiasis (gallstones in CBD), primary biliary cholangitis (PBC — "
    "autoimmune destruction of small bile ducts), primary sclerosing cholangitis (PSC — "
    "associated with IBD), pancreatic head carcinoma, drug-induced cholestasis."
))

# ── Section 13: Functions ─────────────────────────────────────────────────────
story.extend(section_header("13", "Key Functions of the Liver"))
story.extend(make_table(
    ["Category", "Functions"],
    [
        ["Metabolic", "Glucose homeostasis (glycolysis, gluconeogenesis, glycogenesis/glycogenolysis); lipid metabolism (cholesterol synthesis, lipoprotein assembly, beta-oxidation, ketogenesis); amino acid catabolism; urea cycle"],
        ["Synthetic", "Albumin; clotting factors I, II, V, VII, VIII, IX, X, XI, XIII; complement proteins; angiotensinogen; IGF-1; acute-phase reactants (CRP, fibrinogen, ferritin)"],
        ["Detoxification", "Drug metabolism via CYP450 system; alcohol metabolism (alcohol dehydrogenase, CYP2E1); bilirubin conjugation (glucuronidation); removal of gut endotoxins"],
        ["Storage", "Glycogen; vitamins A, D, E, K, B12; iron (ferritin/hemosiderin); copper"],
        ["Immunological", "Kupffer cells — phagocytose gut-derived bacteria and endotoxin; produces acute-phase proteins; tolerogenic immune responses to gut antigens"],
        ["Endocrine", "Produces IGF-1 (in response to GH), thrombopoietin, 25-hydroxylation of vitamin D"],
    ],
    col_widths=[4*cm, 12.5*cm]
))

# ── Section 14: Clinical Summary Table ────────────────────────────────────────
story.extend(section_header("14", "Clinical Correlates — Summary Table"))
story.extend(make_table(
    ["Anatomical Feature", "Clinical Significance"],
    [
        ["Dual blood supply (portal 80% / hepatic artery 20%)", "Liver relatively resistant to isolated arterial occlusion; portal venous thrombosis is far more dangerous"],
        ["Couinaud segmental anatomy", "Precise anatomical resection possible for primary and metastatic tumors; living-donor transplantation"],
        ["Zone 3 (centrilobular) hepatocytes", "Most vulnerable to ischemic necrosis and CYP450-mediated drug toxicity (paracetamol, alcohol)"],
        ["Falciform ligament / ligamentum teres", "Recanalization in portal hypertension → caput medusae visible on abdominal examination"],
        ["Caudate lobe (segment I) direct IVC drainage", "Spared in Budd-Chiari syndrome; compensatory hypertrophy is a diagnostic imaging feature"],
        ["Hepatocystic triangle (Calot's)", "Critical surgical anatomy during cholecystectomy; inadvertent CBD injury leading complication"],
        ["Hepatoduodenal ligament", "Basis of Pringle maneuver — manual compression controls total hepatic inflow hemorrhage"],
        ["Glisson's capsule", "Capsule distension → RUQ pain + right shoulder referred pain (phrenic nerve C3–C5)"],
        ["Space of Disse + hepatic stellate cells", "Stellate cell activation → collagen deposition → fibrosis → cirrhosis (NAFLD/NASH, alcohol, viral hepatitis)"],
        ["Sinusoidal endothelial fenestrations", "Loss of fenestrations (capillarization of sinusoids) in cirrhosis impairs hepatocyte–blood exchange, worsening liver dysfunction"],
        ["Bile canalicular tight junctions", "Disruption → intrahepatic cholestasis; seen in drug reactions, total parenteral nutrition, viral hepatitis"],
        ["Hepatic veins draining into IVC", "Hepatic venous pressure gradient (HVPG) >10 mmHg predicts risk of variceal bleeding in cirrhosis"],
    ],
    col_widths=[6*cm, 10.5*cm]
))

# ── Footer note ────────────────────────────────────────────────────────────────
story.append(spacer(0.5))
story.append(HRFlowable(width="100%", thickness=1, color=GREY_LINE))
story.append(spacer(0.2))
story.append(Paragraph(
    "Generated by Orris Medical Education AI | Sources: Bailey &amp; Love's Surgery 28th ed., "
    "Gray's Anatomy for Students, Guyton &amp; Hall Medical Physiology, "
    "Yamada's Gastroenterology 7th ed., Miller's Anesthesia 10th ed.",
    ParagraphStyle('footer', fontName='Helvetica', fontSize=8, textColor=colors.grey,
                   alignment=TA_CENTER, leading=11)
))

# ── Page number callback ───────────────────────────────────────────────────────
def add_page_number(canvas, doc):
    canvas.saveState()
    canvas.setFont("Helvetica", 8)
    canvas.setFillColor(colors.HexColor("#888888"))
    canvas.drawCentredString(A4[0]/2, 1.2*cm, f"Page {doc.page}")
    canvas.restoreState()

# ── Build PDF ─────────────────────────────────────────────────────────────────
doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
print(f"PDF generated: {OUTPUT}")
Running Command

cd /home/daytona/workspace/liver-anatomy-pdf && python3 generate_pdf.py 2>&1

Editing File

~/liver-anatomy-pdf/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/liver-anatomy-pdf/generate_pdf.py'
Running Command

cd /home/daytona/workspace/liver-anatomy-pdf && python3 generate_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/liver-anatomy-pdf/Liver_Anatomy_Complete.pdf

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

Liver Anatomy Complete

PDF Document · PDF

What's inside (9 MB, fully formatted A4 PDF):
  • 14 sections covering the complete liver anatomy — embryology, ligaments, gross anatomy, Couinaud segments, dual blood supply, porta hepatis, venous drainage, lymphatics/nerves, microanatomy (lobule + Rappaport acinus zones), cellular components (hepatocytes, Kupffer cells, stellate cells, Space of Disse), biliary system, and functions
  • 5 textbook images embedded at full quality: Couinaud segment diagrams (Bailey & Love + Gray's), portal vein branching (Yamada's), liver lobule structure (Guyton & Hall), and acinus zone/metabolic zonation diagram (Miller's Anesthesia)
  • 14 Clinical Correlate boxes (orange-bordered) covering portal hypertension, Budd-Chiari, Pringle maneuver, hepatic resection surgery, paracetamol toxicity, cirrhosis/NAFLD, cholestasis, biliary atresia, and more
  • Multiple styled tables - Couinaud segments, ligament functions, hepatic cell types, zone metabolism, and clinical summary
  • Page numbers, section dividers, and source attribution throughout
This is a shared conversation. Sign in to Orris to start your own chat.