Give a pdf on jaundice topic in pathology

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

mkdir -p /home/daytona/workspace/jaundice-pdf

Writing File

~/jaundice-pdf/generate_jaundice_pdf.py

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

OUTPUT = "/home/daytona/workspace/jaundice-pdf/Jaundice_Pathology.pdf"

doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    rightMargin=2*cm,
    leftMargin=2*cm,
    topMargin=2.5*cm,
    bottomMargin=2*cm,
    title="Jaundice – Pathology",
    author="Orris Medical Library",
)

# ── Color palette ────────────────────────────────────────────────────────────
DARK_BLUE   = colors.HexColor("#1A3C5E")
MED_BLUE    = colors.HexColor("#2B6CB0")
LIGHT_BLUE  = colors.HexColor("#EBF4FF")
ACCENT      = colors.HexColor("#C05621")
TABLE_HDR   = colors.HexColor("#2B6CB0")
TABLE_ALT   = colors.HexColor("#EBF8FF")
BORDER_GREY = colors.HexColor("#CBD5E0")
WHITE       = colors.white
TEXT_DARK   = colors.HexColor("#1A202C")

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

def style(name, parent="Normal", **kw):
    s = ParagraphStyle(name, parent=base[parent], **kw)
    return s

Title_S   = style("Title_S",   "Normal",    fontSize=28, textColor=WHITE,       alignment=TA_CENTER, fontName="Helvetica-Bold", leading=34)
Sub_S     = style("Sub_S",     "Normal",    fontSize=13, textColor=colors.HexColor("#BEE3F8"), alignment=TA_CENTER, fontName="Helvetica", leading=18)
H1        = style("H1",        "Normal",    fontSize=16, textColor=WHITE,        fontName="Helvetica-Bold", leading=20, spaceBefore=6)
H2        = style("H2",        "Normal",    fontSize=13, textColor=DARK_BLUE,    fontName="Helvetica-Bold", leading=17, spaceBefore=10, spaceAfter=4)
H3        = style("H3",        "Normal",    fontSize=11, textColor=MED_BLUE,     fontName="Helvetica-Bold", leading=15, spaceBefore=8, spaceAfter=3)
Body      = style("Body",      "Normal",    fontSize=10, textColor=TEXT_DARK,    fontName="Helvetica",      leading=15, spaceBefore=3, spaceAfter=3, alignment=TA_JUSTIFY)
Bullet    = style("Bullet",    "Normal",    fontSize=10, textColor=TEXT_DARK,    fontName="Helvetica",      leading=14, leftIndent=16, spaceBefore=2)
Caption   = style("Caption",   "Normal",    fontSize=8.5, textColor=colors.HexColor("#4A5568"), fontName="Helvetica-Oblique", alignment=TA_CENTER, leading=12)
KeyBox    = style("KeyBox",    "Normal",    fontSize=10, textColor=DARK_BLUE,    fontName="Helvetica",      leading=14, leftIndent=8, spaceBefore=2)
Ref       = style("Ref",       "Normal",    fontSize=8,  textColor=colors.HexColor("#718096"), fontName="Helvetica-Oblique", leading=11)

def bullet(txt, level=0):
    indent = 16 + level*14
    s = ParagraphStyle(f"bul_{level}", parent=base["Normal"],
                       fontSize=10, textColor=TEXT_DARK, fontName="Helvetica",
                       leading=14, leftIndent=indent, firstLineIndent=-10,
                       spaceBefore=2)
    return Paragraph(f"\u2022  {txt}", s)

def hr(color=BORDER_GREY, width=1):
    return HRFlowable(width="100%", thickness=width, color=color, spaceAfter=4, spaceBefore=4)

def section_header(title, color=MED_BLUE):
    data = [[Paragraph(title, H1)]]
    t = Table(data, colWidths=["100%"])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), color),
        ("TOPPADDING",    (0,0),(-1,-1), 7),
        ("BOTTOMPADDING", (0,0),(-1,-1), 7),
        ("LEFTPADDING",   (0,0),(-1,-1), 10),
        ("RIGHTPADDING",  (0,0),(-1,-1), 10),
        ("ROUNDEDCORNERS", [4]),
    ]))
    return t

def info_box(title, items, bg=LIGHT_BLUE, border=MED_BLUE):
    rows = [[Paragraph(f"<b>{title}</b>", H3)]]
    for item in items:
        rows.append([Paragraph(f"\u2022  {item}", KeyBox)])
    t = Table(rows, colWidths=["100%"])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), bg),
        ("BOX",        (0,0), (-1,-1), 1.2, border),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 10),
        ("RIGHTPADDING",  (0,0), (-1,-1), 10),
    ]))
    return t

def make_table(header, rows, col_widths=None):
    data = [[Paragraph(h, style("TH","Normal", fontSize=9.5, textColor=WHITE,
                                fontName="Helvetica-Bold", leading=13)) for h in header]]
    for i, row in enumerate(rows):
        bg = TABLE_ALT if i % 2 == 0 else WHITE
        data.append([Paragraph(str(c), style("TD","Normal", fontSize=9.5,
                               textColor=TEXT_DARK, fontName="Helvetica",
                               leading=13)) for c in row])
    t = Table(data, colWidths=col_widths, repeatRows=1)
    ts = TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), TABLE_HDR),
        ("GRID",          (0,0), (-1,-1), 0.5, BORDER_GREY),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [TABLE_ALT, WHITE]),
        ("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"),
    ])
    t.setStyle(ts)
    return t

# ─────────────────────────────────────────────────────────────────────────────
# BUILD STORY
# ─────────────────────────────────────────────────────────────────────────────
story = []

# ── COVER PAGE ───────────────────────────────────────────────────────────────
cover_data = [[Paragraph("JAUNDICE", Title_S)],
              [Paragraph("A Comprehensive Pathology Review", Sub_S)],
              [Spacer(1, 0.3*cm)],
              [Paragraph("Harrison's Principles of Internal Medicine (22e, 2025) &amp;<br/>Sleisenger &amp; Fordtran's Gastrointestinal and Liver Disease", Sub_S)],
              [Spacer(1, 0.3*cm)],
              [Paragraph("Orris Medical Library  |  June 2026", Sub_S)],
]
cover = Table(cover_data, colWidths=["100%"])
cover.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,-1), DARK_BLUE),
    ("TOPPADDING",    (0,0), (-1,-1), 14),
    ("BOTTOMPADDING", (0,0), (-1,-1), 14),
    ("LEFTPADDING",   (0,0), (-1,-1), 20),
    ("RIGHTPADDING",  (0,0), (-1,-1), 20),
]))
story.append(cover)
story.append(Spacer(1, 1.2*cm))

# short definition box
story.append(info_box(
    "Definition",
    [
        "Jaundice (icterus) is the yellowish discolouration of sclera, skin, and mucous membranes caused by deposition of bilirubin when serum bilirubin exceeds ~34 µmol/L (2 mg/dL).",
        "Clinically detectable jaundice typically appears when serum bilirubin > 2–3 mg/dL.",
        "Normal serum bilirubin: 3.4–15.4 µmol/L (0.2–0.9 mg/dL); 95% of healthy adults fall in this range.",
    ]
))
story.append(Spacer(1, 0.5*cm))
story.append(Paragraph("Source: Harrison's Principles of Internal Medicine, 22nd ed., Chapter 52", Ref))

story.append(PageBreak())

# ── SECTION 1: BILIRUBIN METABOLISM ─────────────────────────────────────────
story.append(section_header("1. Bilirubin Metabolism", DARK_BLUE))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("1.1  Formation of Bilirubin", H2))
story.append(Paragraph(
    "Bilirubin is the end-product of heme catabolism. Approximately <b>80–85%</b> derives from "
    "haemoglobin in senescent red blood cells; the remainder comes from myoglobin, cytochromes, "
    "and ineffective erythropoiesis.",
    Body))
story.append(Paragraph(
    "Two sequential enzymatic reactions occur in reticuloendothelial cells (spleen and liver):",
    Body))
story.append(bullet("<b>Step 1 – Heme oxygenase (microsomal):</b> Oxidatively cleaves the α-bridge of the porphyrin ring, opening the heme ring → produces biliverdin + CO + Fe²⁺."))
story.append(bullet("<b>Step 2 – Biliverdin reductase (cytosolic):</b> Reduces the central methylene bridge of biliverdin → unconjugated bilirubin (UCB)."))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("1.2  Transport to the Liver", H2))
story.append(Paragraph(
    "Unconjugated bilirubin (UCB) is <b>virtually water-insoluble</b> because of tight internal hydrogen "
    "bonding between propionic acid carboxyl groups and imino/lactam groups. "
    "It is transported in plasma bound non-covalently to <b>albumin</b> (UCB–albumin complex). "
    "Free UCB is lipid-soluble and can cross the blood–brain barrier (risk of kernicterus).",
    Body))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("1.3  Hepatic Uptake and Conjugation", H2))
story.append(Paragraph(
    "At the hepatocyte sinusoidal surface, UCB dissociates from albumin and enters hepatocytes via "
    "carrier-mediated transport. Inside, UCB binds to cytosolic proteins of the "
    "<b>glutathione-S-transferase superfamily</b>, preventing efflux back into blood.",
    Body))
story.append(Paragraph(
    "In the <b>smooth endoplasmic reticulum</b>, UCB is conjugated to glucuronic acid by "
    "<b>bilirubin UDP-glucuronosyl transferase (UDPGT)</b>:",
    Body))
story.append(bullet("UCB + UDP-glucuronic acid → bilirubin monoglucuronide → bilirubin diglucuronide (predominant conjugated form)."))
story.append(bullet("Conjugation disrupts internal H-bonds → water-soluble conjugated bilirubin (CB)."))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("1.4  Biliary Excretion", H2))
story.append(Paragraph(
    "Conjugated bilirubin diffuses from the ER to the canalicular membrane. "
    "It is actively transported into bile canaliculi by the ATP-dependent transporter "
    "<b>MRP2 (multidrug resistance-associated protein 2)</b>. "
    "A fraction is exported into sinusoidal blood by <b>MRP3</b> and may be recaptured by "
    "hepatocytes via <b>OATP1B1 / OATP1B3</b>.",
    Body))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("1.5  Intestinal Fate and Enterohepatic Circulation", H2))
story.append(Paragraph(
    "Conjugated bilirubin is not absorbed in the proximal small bowel (hydrophilic + large MW). "
    "In the <b>distal ileum and colon</b>, bacterial β-glucuronidases hydrolyse it to UCB, which is "
    "then reduced by gut bacteria to colourless <b>urobilinogens</b>.",
    Body))
story.append(bullet("80–90% of urobilinogens excreted in faeces (unchanged or oxidised to orange-brown urobilins → stool colour)."))
story.append(bullet("10–20% undergo enterohepatic circulation; a small fraction (<3 mg/dL) escapes hepatic re-uptake and is filtered at the glomerulus → excreted as urinary urobilinogen."))
story.append(Spacer(1, 0.3*cm))

# Metabolism summary table
story.append(Paragraph("Summary: Steps in Bilirubin Metabolism", H3))
met_rows = [
    ["Formation",    "Reticuloendothelial cells", "Heme oxygenase + biliverdin reductase", "Unconjugated bilirubin (UCB)"],
    ["Transport",    "Blood",                     "Bound to albumin (non-covalent)",        "UCB–albumin complex"],
    ["Hepatic uptake","Hepatocyte sinusoid",       "Carrier-mediated; GST binding in cytosol","UCB in hepatocyte"],
    ["Conjugation",  "Smooth ER",                 "UDPGT (UDP-glucuronosyl transferase)",   "Bilirubin mono/di-glucuronide (CB)"],
    ["Canalicular excretion","Bile canaliculus",  "MRP2 (ATP-dependent)",                  "CB in bile"],
    ["Intestinal processing","Distal ileum/colon","Bacterial β-glucuronidases + reduction", "Urobilinogens → urobilins / stercobilin"],
    ["Enterohepatic",  "Portal → liver",          "Hepatic re-uptake via OATP1B1/1B3",      "Re-excreted in bile"],
]
story.append(make_table(
    ["Step", "Location", "Enzyme / Mechanism", "Product"],
    met_rows,
    col_widths=[3.2*cm, 3.2*cm, 6.5*cm, 4.3*cm]
))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("Source: Harrison's Principles of Internal Medicine, 22nd ed., Chapter 52", Ref))

story.append(PageBreak())

# ── SECTION 2: MEASUREMENT OF BILIRUBIN ─────────────────────────────────────
story.append(section_header("2. Measurement of Serum Bilirubin", DARK_BLUE))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("2.1  Van den Bergh Reaction", H2))
story.append(Paragraph(
    "The traditional method (still used in most labs) exposes serum bilirubin to "
    "<b>diazotized sulfanilic acid</b>, which cleaves bilirubin into two dipyrrylmethene azopigments "
    "(max absorbance 540 nm). Two fractions are measured:",
    Body))
story.append(bullet("<b>Direct fraction (conjugated bilirubin):</b> reacts with diazo reagent without an accelerator."))
story.append(bullet("<b>Total bilirubin:</b> measured after addition of alcohol (accelerator) to release UCB from albumin."))
story.append(bullet("<b>Indirect fraction (unconjugated):</b> Total minus Direct."))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("2.2  Reference Values", H2))
ref_rows = [
    ["Total serum bilirubin",       "3.4–15.4 µmol/L", "0.2–0.9 mg/dL",  "95% of normal population"],
    ["Unconjugated (indirect)",     "Majority of total","≤ ~1.0 mg/dL",   "Near 100% in normal persons"],
    ["Conjugated (direct)",         "< 15% of total",   "< 0.3 mg/dL",    "Any rise = significant hepatobiliary pathology"],
    ["Overt clinical jaundice",     "> 34 µmol/L",      "> 2 mg/dL",      "Scleral icterus first sign"],
    ["Delta bilirubin (δ-bilirubin)","Covalently bound to albumin","Prolonged cholestasis","Half-life ≈ 18–20 days (albumin t½)"],
]
story.append(make_table(
    ["Parameter", "SI Units", "Conventional Units", "Clinical Note"],
    ref_rows,
    col_widths=[4.5*cm, 3.5*cm, 3.5*cm, 5.7*cm]
))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("2.3  Delta Bilirubin (Biliprotein)", H2))
story.append(Paragraph(
    "When hepatic excretion of bilirubin glucuronides is impaired, conjugated bilirubin accumulates "
    "in serum. A portion covalently links to albumin to form <b>delta (δ) bilirubin</b>. "
    "Because it is albumin-bound, it is NOT filtered at the renal glomerulus, explaining two "
    "clinical enigmas:",
    Body))
story.append(bullet("Absence of bilirubinuria in some patients with conjugated hyperbilirubinaemia (δ-bilirubin predominates)."))
story.append(bullet("Slow decline in serum bilirubin during recovery (mirrors albumin half-life of 18–20 days)."))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("Source: Harrison's Principles of Internal Medicine, 22nd ed.", Ref))

story.append(PageBreak())

# ── SECTION 3: CLASSIFICATION OF JAUNDICE ───────────────────────────────────
story.append(section_header("3. Classification of Jaundice", DARK_BLUE))
story.append(Spacer(1, 0.3*cm))
story.append(Paragraph(
    "Jaundice is classified by the type of bilirubin elevated and the site of pathology:",
    Body))
story.append(Spacer(1, 0.2*cm))

# Classification table
class_rows = [
    ["Prehepatic\n(Haemolytic)",
     "Unconjugated (indirect)",
     "Increased RBC destruction or ineffective erythropoiesis → ↑ bilirubin production exceeds hepatic conjugation capacity",
     "Haemolytic anaemias (hereditary spherocytosis, G6PD deficiency, sickle-cell, thalassaemia, autoimmune haemolysis), ineffective erythropoiesis, large haematoma resorption"],
    ["Hepatic\n(Hepatocellular)",
     "Mixed (conjugated + unconjugated)",
     "Damaged hepatocytes → impaired uptake, conjugation, and/or excretion of bilirubin",
     "Viral hepatitis (A,B,C,D,E), alcoholic hepatitis, drug-induced liver injury, cirrhosis, autoimmune hepatitis, ischaemic hepatitis, Wilson disease, Gilbert's syndrome, Crigler-Najjar I & II, Dubin-Johnson, Rotor syndrome"],
    ["Posthepatic\n(Obstructive / Cholestatic)",
     "Conjugated (direct)",
     "Obstruction of bile flow (intrahepatic or extrahepatic) → reflux of conjugated bilirubin into blood",
     "Choledocholithiasis, carcinoma head of pancreas, cholangiocarcinoma, PSC, PBC, strictures, cholestasis of pregnancy"],
]
story.append(make_table(
    ["Type", "Predominant Bilirubin", "Mechanism", "Key Causes"],
    class_rows,
    col_widths=[2.5*cm, 3.0*cm, 5.5*cm, 6.2*cm]
))
story.append(Spacer(1, 0.4*cm))

# ── 3.1 Unconjugated Hyperbilirubinaemia ─────────────────────────────────────
story.append(Paragraph("3.1  Isolated Unconjugated Hyperbilirubinaemia", H2))
story.append(Paragraph(
    "This pattern results from either <b>overproduction</b> (haemolysis / ineffective erythropoiesis) "
    "or <b>impaired hepatic uptake / conjugation</b>.",
    Body))

story.append(Paragraph("Haemolytic Disorders", H3))
haem_rows = [
    ["Hereditary spherocytosis",   "Spectrin/ankyrin defect", "AD", "Spherocytes, ↑ MCHC, splenomegaly"],
    ["G6PD deficiency",            "Heinz body haemolysis (oxidative)", "X-linked", "Bite cells, episodic haemolysis"],
    ["Sickle-cell anaemia",        "HbS polymerisation",      "AR", "Sickle cells, vaso-occlusive crises"],
    ["Thalassaemia",               "Ineffective erythropoiesis + haemolysis", "AR", "Hypochromic microcytic anaemia"],
    ["Autoimmune haemolytic anaemia","IgG/IgM anti-RBC antibodies","Acquired","+ Direct Coombs test"],
    ["Microangiopathic (TTP/HUS)", "Shear-stress haemolysis", "Acquired","Schistocytes, ↑LDH"],
]
story.append(make_table(
    ["Disorder", "Mechanism", "Inheritance", "Key Finding"],
    haem_rows,
    col_widths=[4.5*cm, 5.5*cm, 2.5*cm, 4.7*cm]
))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("Genetic Disorders of Bilirubin Conjugation", H3))
gen_rows = [
    ["Gilbert's syndrome",
     "UDPGT activity 10–35% of normal (UGT1A1 promoter TA repeat)",
     "Mild UCB < 6 mg/dL; fluctuates with fasting, stress, illness, alcohol",
     "Very common (3–7% population, M:F = 1.5–7:1); benign; may be hepatoprotective"],
    ["Crigler-Najjar Type I",
     "Complete absence of bilirubin UDPGT activity (UGT1A1 coding mutation)",
     "Severe UCB > 20 mg/dL (>342 µmol/L); kernicterus in neonates",
     "Rare; often fatal in infancy; liver transplant required"],
    ["Crigler-Najjar Type II",
     "UDPGT activity severely reduced (≤10% of normal); phenobarbital-inducible",
     "UCB 6–25 mg/dL (103–428 µmol/L)",
     "More common than type I; survive into adulthood; phenobarbital reduces bilirubin"],
    ["Dubin-Johnson syndrome",
     "Absent MRP2 (canalicular bilirubin transporter) — conjugated bilirubin reflux",
     "Conjugated hyperbilirubinaemia; black liver pigment on biopsy",
     "Benign; urinary coproporphyrin isomer I elevated"],
    ["Rotor syndrome",
     "Absent OATP1B1 + OATP1B3 (hepatic drug re-uptake transporters)",
     "Conjugated hyperbilirubinaemia",
     "Benign; no liver pigment; total urinary coproporphyrin elevated"],
]
story.append(make_table(
    ["Syndrome", "Defect", "Bilirubin Level", "Notes"],
    gen_rows,
    col_widths=[3.5*cm, 5.0*cm, 4.0*cm, 4.7*cm]
))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("Source: Harrison's Principles of Internal Medicine, 22nd ed., Chapter 52", Ref))

story.append(PageBreak())

# ── SECTION 4: HEPATOCELLULAR JAUNDICE ───────────────────────────────────────
story.append(section_header("4. Hepatocellular (Hepatic) Jaundice", DARK_BLUE))
story.append(Spacer(1, 0.3*cm))
story.append(Paragraph(
    "Liver-cell damage impairs all three steps—uptake, conjugation, and excretion—producing "
    "<b>mixed conjugated + unconjugated hyperbilirubinaemia</b>. "
    "Transaminases (ALT, AST) are markedly elevated (hepatocellular pattern).",
    Body))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("4.1  Major Causes", H2))
cause_rows = [
    ["Viral hepatitis A",      "Faeco-oral (HAV)",      "Acute, self-limiting; jaundice in ~70% of adults"],
    ["Viral hepatitis B",      "Parenteral/sexual/vertical","Acute + chronic; risk of cirrhosis/HCC"],
    ["Viral hepatitis C",      "Parenteral (blood)",    "Mostly anicteric acutely; 75–85% chronic"],
    ["Hepatitis E",            "Faeco-oral (HEV)",      "Dangerous in pregnancy (high mortality)"],
    ["Alcoholic hepatitis",    "Ethanol toxicity",      "AST:ALT > 2:1; neutrophilic infiltrate; Mallory bodies"],
    ["Drug-induced (DILI)",    "Hepatotoxic drugs/herbs","Paracetamol (dose-dependent); idiosyncratic agents"],
    ["Autoimmune hepatitis",   "Anti-liver autoantibodies","ANA, anti-SMA, anti-LKM1; steroid-responsive"],
    ["Ischaemic hepatitis",    "Hypoperfusion",         "Transaminases >1000 IU/L rapidly; 'shock liver'"],
    ["Wilson disease",         "Copper accumulation (ATP7B mutation)","Haemolysis + liver disease in young adults"],
    ["Cirrhosis",              "End-stage fibrosis (any cause)","Reduced synthetic function + portal hypertension"],
]
story.append(make_table(
    ["Cause", "Mechanism / Exposure", "Key Feature"],
    cause_rows,
    col_widths=[4.5*cm, 5.0*cm, 7.7*cm]
))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("4.2  Histological Features of Hepatocellular Damage", H2))
for txt in [
    "Hepatocyte necrosis and apoptosis (acidophilic bodies / Councilman bodies in viral hepatitis)",
    "Lobular disarray with inflammatory infiltrate (lymphocytes in viral; neutrophils in alcoholic)",
    "Mallory–Denk bodies (alcoholic hepatitis and NASH): intracytoplasmic eosinophilic inclusions of cytokeratin 8/18",
    "Ballooning degeneration of hepatocytes",
    "Zone 3 (centrilobular) necrosis in ischaemic hepatitis and paracetamol toxicity",
    "Ground-glass hepatocytes in chronic HBV (HBsAg accumulation)",
    "Bridging necrosis and fibrosis leading to cirrhosis in chronic disease",
]:
    story.append(bullet(txt))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("4.3  Liver Function Tests in Hepatocellular Disease", H2))
lft_rows = [
    ["ALT (SGPT)",         "↑↑↑ (often > 10× ULN)",     "Most specific marker of hepatocyte damage"],
    ["AST (SGOT)",         "↑↑↑",                        "Less specific (also in muscle, heart); AST:ALT > 2:1 in alcoholic hepatitis"],
    ["Bilirubin (total)",  "↑ (mixed pattern)",           "Both conjugated and unconjugated elevated"],
    ["Alkaline phosphatase","Normal or mildly ↑",         "Markedly elevated in cholestatic disease"],
    ["GGT",                "↑ in alcoholic / cholestatic","Useful for confirming hepatic source of ALP"],
    ["PT / INR",           "↑ in severe disease",         "Reflects synthetic function (factors I, II, V, VII, X)"],
    ["Albumin",            "↓ in chronic disease",        "Marker of chronic synthetic failure"],
    ["Urinary urobilinogen","↑↑",                         "More bilirubin reaches gut → more urobilinogen reabsorbed"],
    ["Urinary bilirubin",  "Present",                     "Conjugated bilirubin filtered by glomerulus"],
]
story.append(make_table(
    ["Test", "Result", "Comment"],
    lft_rows,
    col_widths=[4.0*cm, 4.5*cm, 8.7*cm]
))

story.append(PageBreak())

# ── SECTION 5: OBSTRUCTIVE JAUNDICE ─────────────────────────────────────────
story.append(section_header("5. Obstructive (Cholestatic / Posthepatic) Jaundice", DARK_BLUE))
story.append(Spacer(1, 0.3*cm))
story.append(Paragraph(
    "Obstruction of bile flow causes <b>conjugated bilirubin</b> to reflux from bile ducts into "
    "blood. Distinguishing intrahepatic from extrahepatic cholestasis is key to management.",
    Body))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("5.1  Causes", H2))
obs_rows = [
    ["Extrahepatic","Choledocholithiasis",           "Most common cause; gallstones in CBD; may be associated with cholangitis"],
    ["Extrahepatic","Pancreatic carcinoma (head)",   "Painless progressive jaundice; Courvoisier's sign (palpable non-tender GB)"],
    ["Extrahepatic","Cholangiocarcinoma",             "Klatskin tumour at biliary hilum; insidious onset; weight loss"],
    ["Extrahepatic","Periampullary carcinoma",        "Episodic jaundice (tumour necrosis)"],
    ["Extrahepatic","Stricture / trauma",             "Post-cholecystectomy bile duct injury"],
    ["Extrahepatic","Pancreatitis (chronic)",         "Compression of common bile duct"],
    ["Intrahepatic","Primary biliary cholangitis (PBC)","Autoimmune destruction of small bile ducts; AMA positive; middle-aged women"],
    ["Intrahepatic","Primary sclerosing cholangitis (PSC)","Fibro-inflammatory strictures; ERCP shows 'beaded' bile ducts; associated with UC"],
    ["Intrahepatic","Intrahepatic cholestasis of pregnancy","Late pregnancy; UDCA treatment"],
    ["Intrahepatic","Drug-induced cholestasis",       "Anabolic steroids, OCP, chlorpromazine, rifampicin"],
    ["Intrahepatic","Infiltrative diseases",          "Sarcoidosis, amyloidosis, lymphoma, metastases"],
]
story.append(make_table(
    ["Site", "Cause", "Notes"],
    obs_rows,
    col_widths=[2.8*cm, 5.0*cm, 9.4*cm]
))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("5.2  Pathophysiology of Obstructive Jaundice", H2))
for txt in [
    "Bile duct obstruction → backpressure → conjugated bilirubin regurgitates into sinusoidal blood",
    "Conjugated bilirubin appears in urine → dark 'tea/cola-coloured' urine (bilirubinuria)",
    "Absent bile in gut → acholic (pale clay-coloured) stools; reduced urobilinogen in urine",
    "Bile salt accumulation in skin → intense pruritus",
    "Fat malabsorption → steatorrhoea + deficiency of fat-soluble vitamins (A, D, E, K)",
    "Vitamin K deficiency → coagulopathy (prolonged PT); responds to parenteral vitamin K",
    "Secondary biliary cirrhosis in prolonged obstruction",
    "Ascending cholangitis risk (Charcot's triad: fever + RUQ pain + jaundice; Reynolds' pentad adds shock + altered consciousness)",
]:
    story.append(bullet(txt))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("5.3  LFTs in Obstructive Jaundice", H2))
obs_lft_rows = [
    ["Bilirubin",           "↑↑ (predominantly conjugated)","Bilirubinuria present"],
    ["ALP",                 "↑↑↑ (often > 3× ULN)",        "Most sensitive marker of cholestasis; from bile duct epithelium"],
    ["GGT",                 "↑↑",                           "Confirms hepatic source of ↑ALP"],
    ["ALT / AST",           "Normal or mildly ↑",           "Markedly elevated if secondary hepatocyte damage"],
    ["Prothrombin time",    "Prolonged (if chronic)",        "Due to vitamin K malabsorption; reverses with IV vitamin K"],
    ["Urinary urobilinogen","↓ or absent",                  "Bile not reaching gut → no urobilinogen formed"],
    ["Stool colour",        "Pale / acholic",                "Absence of stercobilin"],
]
story.append(make_table(
    ["Test", "Result", "Explanation"],
    obs_lft_rows,
    col_widths=[4.0*cm, 4.5*cm, 8.7*cm]
))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("Sources: Harrison's 22nd ed.; Sleisenger & Fordtran's GI and Liver Disease, Chapter 21", Ref))

story.append(PageBreak())

# ── SECTION 6: CLINICAL EVALUATION ──────────────────────────────────────────
story.append(section_header("6. Clinical Evaluation of Jaundice", DARK_BLUE))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("6.1  History", H2))
for txt in [
    "<b>Onset and duration:</b> acute vs. chronic; intermittent (choledocholithiasis) vs. progressive (malignancy)",
    "<b>Associated symptoms:</b> pruritus (cholestasis), RUQ pain (biliary colic, cholangitis), fever/rigors (cholangitis), weight loss (malignancy)",
    "<b>Urine/stool changes:</b> dark urine (bilirubinuria), pale stools (acholia) – point to obstructive cause",
    "<b>Drug/toxin history:</b> prescribed meds, OTC drugs, herbal supplements, alcohol, anabolic steroids",
    "<b>Viral hepatitis risk factors:</b> IV drug use, tattoos, sexual history, blood transfusions, travel",
    "<b>Family history:</b> Gilbert's, haemolytic anaemia, Wilson disease",
    "<b>Occupational/toxic exposure:</b> industrial solvents, heavy metals",
]:
    story.append(bullet(txt))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("6.2  Physical Examination", H2))
pe_rows = [
    ["Scleral icterus",            "First and most sensitive sign of jaundice (bilirubin > 2 mg/dL)"],
    ["Skin colour",                "Lemon-yellow (haemolytic); deep yellow-green (obstructive)"],
    ["Scratch marks",              "Pruritus from bile salt deposition (cholestasis)"],
    ["Hepatomegaly",               "Hepatitis, fatty liver, infiltrative disease, malignancy"],
    ["Splenomegaly",               "Haemolytic jaundice, portal hypertension, chronic liver disease"],
    ["Palpable gallbladder (Courvoisier)", "Obstruction by pancreatic/periampullary malignancy; GB not palpable in gallstone disease"],
    ["Signs of chronic liver disease","Spider naevi, palmar erythema, caput medusae, gynaecomastia, leuconychia, dupuytren, asterixis"],
    ["Ascites",                    "Portal hypertension / hypoalbuminaemia in cirrhosis or malignancy"],
    ["Kayser-Fleischer rings",     "Wilson disease (slit-lamp examination of cornea)"],
    ["Lymphadenopathy",            "Lymphoma, metastatic malignancy"],
    ["RUQ tenderness",             "Acute cholecystitis, hepatitis, biliary colic"],
    ["Murphy's sign",              "Acute cholecystitis (cessation of inspiration on RUQ palpation)"],
]
story.append(make_table(
    ["Finding", "Significance"],
    pe_rows,
    col_widths=[5.5*cm, 11.7*cm]
))

story.append(PageBreak())

story.append(Paragraph("6.3  Laboratory Investigation Algorithm", H2))
story.append(Paragraph(
    "Initial evaluation: determine whether hyperbilirubinaemia is <b>predominantly unconjugated or conjugated</b>. "
    "If conjugated, check whether other liver tests are abnormal.",
    Body))
story.append(Spacer(1, 0.2*cm))

algo_rows = [
    ["↑ Unconjugated bilirubin only\n(indirect fraction > 85% of total)",
     "No other LFT abnormalities",
     "Haemolysis (FBC, reticulocytes, Coombs test, LDH, haptoglobin)\nor Gilbert's / Crigler-Najjar"],
    ["↑ Conjugated bilirubin\n+↑ ALT/AST >> ALP",
     "Hepatocellular pattern",
     "Viral serology (HAV-IgM, HBsAg, anti-HCV), ANA, anti-SMA, ceruloplasmin, copper, alcohol history"],
    ["↑ Conjugated bilirubin\n+↑ ALP >> ALT/AST",
     "Cholestatic pattern",
     "Ultrasound abdomen (dilated ducts → extrahepatic; non-dilated → intrahepatic)\nMRCP, ERCP, liver biopsy, AMA, ANCA"],
]
story.append(make_table(
    ["Bilirubin Pattern", "LFT Pattern", "Next Investigations"],
    algo_rows,
    col_widths=[4.5*cm, 3.5*cm, 9.2*cm]
))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("6.4  Imaging and Invasive Investigations", H2))
img_rows = [
    ["Ultrasound abdomen",   "1st-line for jaundice","Dilated bile ducts → extrahepatic obstruction; gallstones, liver parenchyma"],
    ["MRCP",                 "Non-invasive biliary imaging","Detailed biliary anatomy; diagnosis of choledocholithiasis, PSC, strictures"],
    ["ERCP",                 "Diagnostic + therapeutic","Sphincterotomy, stone extraction, stent placement; risk of pancreatitis"],
    ["CECT abdomen",         "Pancreatic/hepatic pathology","Pancreatic carcinoma, metastases, hepatic masses"],
    ["PTC (Percutaneous transhepatic cholangiography)","When ERCP fails","Drainage of intrahepatic ducts; proximal biliary obstruction"],
    ["Liver biopsy",         "Parenchymal liver disease","Hepatitis grading/staging, PBC, autoimmune hepatitis, Wilson disease"],
    ["Endoscopic ultrasound (EUS)","Periampullary & pancreatic lesions","Staging, FNA of pancreatic masses"],
]
story.append(make_table(
    ["Investigation", "Indication", "Key Use"],
    img_rows,
    col_widths=[4.5*cm, 4.5*cm, 8.2*cm]
))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("Source: Sleisenger & Fordtran's GI and Liver Disease, Chapter 21; Harrison's 22nd ed., Chapter 52", Ref))

story.append(PageBreak())

# ── SECTION 7: NEONATAL JAUNDICE ─────────────────────────────────────────────
story.append(section_header("7. Neonatal Jaundice", DARK_BLUE))
story.append(Spacer(1, 0.3*cm))
story.append(Paragraph(
    "Jaundice in the newborn is extremely common and may be physiological or pathological. "
    "Unconjugated bilirubin is neurotoxic in neonates.",
    Body))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("7.1  Physiological Jaundice", H2))
for txt in [
    "Appears on <b>day 2–3</b> of life (never day 1)",
    "Peaks day 3–5; resolves by day 10–14 (may persist to 3 weeks in preterm)",
    "Mechanism: fetal Hb breakdown → ↑ bilirubin load; immature hepatic UDPGT activity; increased enterohepatic circulation",
    "Bilirubin < 12 mg/dL in term infant; < 15 mg/dL in preterm",
    "No treatment usually required",
]:
    story.append(bullet(txt))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("7.2  Pathological Jaundice – Red Flags", H2))
for txt in [
    "Jaundice appearing within <b>24 hours</b> of birth",
    "Bilirubin rising > 5 mg/dL/day",
    "Serum bilirubin > 15 mg/dL in term infant",
    "Jaundice persisting > 14 days (term) or > 21 days (preterm)",
    "Conjugated (direct) bilirubin > 2 mg/dL at any age",
    "Signs of haemolysis (pallor, hydrops fetalis, hepatosplenomegaly)",
]:
    story.append(bullet(txt))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("7.3  Causes of Neonatal Pathological Jaundice", H2))
neo_rows = [
    ["Haemolytic – immune", "Rh incompatibility (anti-D), ABO incompatibility, minor blood group antigens", "Coombs test positive", "Day 1"],
    ["Haemolytic – non-immune","G6PD deficiency, hereditary spherocytosis, alpha-thalassaemia","Peripheral blood smear","Variable"],
    ["Infection",           "Bacterial sepsis, congenital TORCH infections","CRP, blood cultures, TORCH screen","Any day"],
    ["Metabolic",           "Galactosaemia, hypothyroidism, tyrosinaemia","Metabolic screen","Variable"],
    ["Biliary atresia",     "Fibro-obliterative destruction of bile ducts","↑ Conjugated bilirubin, HIDA scan","Weeks 2–6"],
    ["Crigler-Najjar I",    "Absent UDPGT",    "Bilirubin > 20 mg/dL","Day 1–3"],
    ["Breast-milk jaundice","β-glucuronidase in breast milk → ↑ enterohepatic circulation","Clinical; temporary formula feeds","Week 2+"],
]
story.append(make_table(
    ["Cause", "Details", "Investigation", "Onset"],
    neo_rows,
    col_widths=[3.2*cm, 5.5*cm, 4.5*cm, 2.0*cm]
))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("7.4  Kernicterus (Bilirubin Encephalopathy)", H2))
story.append(Paragraph(
    "Unconjugated bilirubin at very high levels crosses the blood–brain barrier and deposits in "
    "the basal ganglia, hippocampus, and brainstem nuclei, causing irreversible neuronal necrosis. "
    "Characteristic yellow staining of the brain is called <b>kernicterus</b>.",
    Body))
for txt in [
    "<b>Acute phase:</b> hypotonia, poor feeding, high-pitched cry, seizures, opisthotonus",
    "<b>Chronic phase:</b> choreoathetosis, sensorineural deafness, upward gaze palsy, intellectual disability",
    "<b>Treatment:</b> phototherapy (converts bilirubin to water-soluble photoisomers via blue-green light 460–490 nm) and exchange transfusion for severe cases",
]:
    story.append(bullet(txt))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("Source: Rosen's Emergency Medicine; Harrison's 22nd ed.", Ref))

story.append(PageBreak())

# ── SECTION 8: DIFFERENTIAL DIAGNOSIS ────────────────────────────────────────
story.append(section_header("8. Differential Diagnosis at a Glance", DARK_BLUE))
story.append(Spacer(1, 0.3*cm))

dd_rows = [
    ["Feature",              "Haemolytic (Prehepatic)", "Hepatocellular (Hepatic)", "Obstructive (Posthepatic)"],
    ["Bilirubin type",       "Unconjugated ↑↑",         "Both ↑",                   "Conjugated ↑↑"],
    ["Urine bilirubin",      "Absent",                  "Present",                  "Present (dark)"],
    ["Urinary urobilinogen", "↑↑↑",                     "↑ (early) or ↓ (severe)",  "↓ or absent"],
    ["Stool colour",         "Normal / dark",           "Variable",                 "Pale / acholic"],
    ["ALT / AST",            "Normal",                  "↑↑↑",                      "Normal / mild ↑"],
    ["ALP",                  "Normal",                  "Normal / mild ↑",          "↑↑↑"],
    ["PT / INR",             "Normal",                  "↑ (if severe)",            "↑ (responds to vit. K)"],
    ["Haemoglobin",          "↓ (anaemia)",             "Usually normal",           "Normal"],
    ["Splenomegaly",         "Common",                  "Present (portal HT)",      "Absent (usually)"],
    ["Gallbladder",          "Not enlarged",            "Not enlarged",             "Enlarged if below cystic duct (Courvoisier)"],
    ["Key investigation",    "CBC, reticulocytes, Coombs","Viral serology, LFTs, biopsy","USS, MRCP, ERCP"],
]
# Header row separate
header = dd_rows[0]
data_r = dd_rows[1:]
story.append(make_table(header, data_r, col_widths=[4.3*cm, 4.0*cm, 4.0*cm, 4.9*cm]))
story.append(Spacer(1, 0.4*cm))

# ── SECTION 9: MANAGEMENT ────────────────────────────────────────────────────
story.append(section_header("9. Management Principles", DARK_BLUE))
story.append(Spacer(1, 0.3*cm))

story.append(Paragraph("9.1  Obstructive Jaundice", H2))
for txt in [
    "Therapy directed at <b>relieving obstruction</b>",
    "<b>ERCP</b>: sphincterotomy, balloon dilation of strictures, stent placement (for distal lesions, choledocholithiasis)",
    "<b>Interventional radiology (PTC)</b>: biliary drain for proximal obstruction (Klatskin tumour)",
    "<b>Surgery</b>: for resectable malignancies; biliary bypass for palliation",
    "Correct coagulopathy with parenteral <b>vitamin K</b> before any procedure",
    "<b>Broad-spectrum antibiotics</b> for ascending cholangitis (e.g., piperacillin-tazobactam)",
    "<b>UDCA (ursodeoxycholic acid)</b>: for PBC and cholestasis of pregnancy – stimulates bile flow, improves biochemistry",
]:
    story.append(bullet(txt))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("9.2  Hepatocellular Jaundice", H2))
for txt in [
    "Treat underlying cause: antiviral therapy (DAAs for HCV; tenofovir/entecavir for HBV); cessation of offending drug/alcohol",
    "Immunosuppressants (prednisolone ± azathioprine) for autoimmune hepatitis",
    "N-acetylcysteine (NAC) for paracetamol-induced acute liver failure",
    "Liver transplantation for fulminant hepatic failure or end-stage chronic liver disease",
    "Supportive care: nutrition, coagulopathy management, infection prevention",
]:
    story.append(bullet(txt))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("9.3  Haemolytic Jaundice", H2))
for txt in [
    "Treat underlying haemolytic condition (steroids for AIHA, transfusions, splenectomy in hereditary spherocytosis)",
    "Folate supplementation (↑ demand from erythroid hyperplasia)",
    "Avoid triggers for G6PD deficiency (oxidant drugs, fava beans)",
    "Phototherapy or exchange transfusion for neonatal jaundice with kernicterus risk",
]:
    story.append(bullet(txt))
story.append(Spacer(1, 0.2*cm))

story.append(Paragraph("9.4  Pruritus in Cholestasis", H2))
for txt in [
    "Cholestyramine (bile acid resin) – first-line",
    "Rifampicin – second-line (monitor hepatotoxicity)",
    "Naltrexone (opioid antagonist) – third-line; reverses opioid analgesia",
    "Sertraline (SSRI)",
    "UVB phototherapy",
    "Cool temperatures, emollients, topical steroids for symptomatic relief",
]:
    story.append(bullet(txt))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("Sources: Sleisenger & Fordtran's GI and Liver Disease, Chapter 21; Harrison's 22nd ed., Chapter 52", Ref))

story.append(PageBreak())

# ── SECTION 10: HIGH-YIELD SUMMARY BOX ───────────────────────────────────────
story.append(section_header("10. High-Yield Summary for Examinations", DARK_BLUE))
story.append(Spacer(1, 0.3*cm))

hy_data = [
    ["Topic", "Key Point"],
    ["Bilirubin normal range",   "0.2–0.9 mg/dL total; clinical jaundice > 2 mg/dL"],
    ["First step in evaluation", "Is bilirubin predominantly conjugated or unconjugated?"],
    ["UCB only, isolated",       "Haemolysis OR Gilbert's / Crigler-Najjar (check CBC, retics, Coombs)"],
    ["CB + ↑ALP >> ALT",         "Cholestatic pattern → USS abdomen (dilated ducts?)"],
    ["CB + ↑ALT >> ALP",         "Hepatocellular pattern → viral serology, autoimmune workup"],
    ["Courvoisier's law",        "Painless jaundice + non-tender palpable GB → malignant obstruction (not stones)"],
    ["Charcot's triad",          "Fever + RUQ pain + jaundice → acute cholangitis"],
    ["Reynolds' pentad",         "Charcot's triad + shock + altered consciousness → suppurative cholangitis"],
    ["Gilbert's syndrome",       "Most common hereditary cause of UCB; benign; 3–7% population; ↑ with fasting"],
    ["Crigler-Najjar I",         "No UDPGT; kernicterus; fatal without liver transplant"],
    ["Dubin-Johnson",            "MRP2 defect; conjugated CB; black liver pigment; benign"],
    ["Rotor syndrome",           "OATP1B1/1B3 defect; conjugated CB; no liver pigment; benign"],
    ["Delta bilirubin",          "Covalently albumin-bound CB; t½ = 18–20 days; explains persistent jaundice during recovery"],
    ["Kernicterus bilirubin",    "UCB > 20 mg/dL in neonate; phototherapy (460–490 nm) is primary treatment"],
    ["PBC marker",               "Anti-mitochondrial antibody (AMA); small bile duct destruction; UDCA treatment"],
    ["PSC association",          "Ulcerative colitis; 'beaded' bile ducts on ERCP/MRCP; risk of cholangiocarcinoma"],
    ["AST:ALT > 2:1",            "Alcoholic hepatitis (also: Wilson disease can show this pattern)"],
    ["Vitamin K response",       "Obstructive jaundice → PT corrects with IV vitamin K (fat malabsorption); hepatocellular → PT does NOT correct"],
]
story.append(make_table(
    hy_data[0],
    hy_data[1:],
    col_widths=[5.5*cm, 11.7*cm]
))
story.append(Spacer(1, 0.3*cm))

# ── REFERENCES ───────────────────────────────────────────────────────────────
story.append(hr(DARK_BLUE, 1.5))
story.append(Spacer(1, 0.2*cm))
story.append(Paragraph("<b>References</b>", H2))
refs = [
    "Longo DL, et al. <i>Harrison's Principles of Internal Medicine</i>, 22nd Edition. McGraw-Hill, 2025. Chapter 52: Jaundice.",
    "Feldman M, Friedman LS, Brandt LJ. <i>Sleisenger and Fordtran's Gastrointestinal and Liver Disease</i>, 11th Edition. Elsevier, 2021. Chapter 21: Jaundice.",
    "Marx J, et al. <i>Rosen's Emergency Medicine</i>, 10th Edition. Elsevier. Chapter 24 & 166: Jaundice (Adult & Neonatal).",
    "Kumar V, Abbas AK, Aster JC. <i>Robbins & Cotran Pathologic Basis of Disease</i>. Elsevier. Chapter 18: Liver and Biliary Tract.",
    "Pye's Surgical Handicraft, 22nd Edition. Chapter: Jaundice.",
]
for r in refs:
    story.append(Paragraph(f"\u2022  {r}", Ref))

story.append(Spacer(1, 0.5*cm))
story.append(hr(BORDER_GREY))
story.append(Paragraph(
    "This document was compiled from authoritative medical textbooks via the Orris Medical Library. "
    "It is intended for educational purposes only.",
    Caption))

# ── BUILD ─────────────────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    # header bar
    canvas.setFillColor(DARK_BLUE)
    canvas.rect(2*cm, A4[1]-1.5*cm, A4[0]-4*cm, 0.6*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica-Bold", 8)
    canvas.drawString(2.2*cm, A4[1]-1.2*cm, "JAUNDICE – PATHOLOGY REVIEW")
    canvas.setFont("Helvetica", 8)
    canvas.drawRightString(A4[0]-2.2*cm, A4[1]-1.2*cm, "Orris Medical Library | June 2026")
    # footer
    canvas.setFillColor(DARK_BLUE)
    canvas.rect(2*cm, 1.2*cm, A4[0]-4*cm, 0.4*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica", 7.5)
    canvas.drawCentredString(A4[0]/2, 1.35*cm, f"Page {doc.page}")
    canvas.restoreState()

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

cd /home/daytona/workspace/jaundice-pdf && python generate_jaundice_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/jaundice-pdf/Jaundice_Pathology.pdf

Your PDF is ready for download:

Jaundice Pathology

PDF Document · PDF


Here is what the PDF covers across 10 sections (~45 KB, A4, fully formatted with colored tables and section headers):
SectionContent
1. Bilirubin MetabolismFormation (heme oxygenase → biliverdin reductase), albumin transport, hepatic uptake, UDPGT conjugation, MRP2 excretion, enterohepatic circulation
2. Measurement of BilirubinVan den Bergh reaction, direct/indirect fractions, reference values, delta bilirubin (biliprotein)
3. Classification of JaundicePrehepatic / Hepatic / Posthepatic with mechanisms and causes table; genetic conjugation disorders (Gilbert's, Crigler-Najjar I & II, Dubin-Johnson, Rotor)
4. Hepatocellular JaundiceViral hepatitis, alcoholic hepatitis, DILI, autoimmune hepatitis, Wilson disease; histological features; LFT pattern
5. Obstructive JaundiceExtrahepatic vs intrahepatic causes; pathophysiology (acholic stools, pruritus, vitamin K deficiency, cholangitis); LFT pattern
6. Clinical EvaluationHistory, physical exam findings (Courvoisier's sign, Charcot's triad), lab algorithm, imaging (USS, MRCP, ERCP, liver biopsy)
7. Neonatal JaundicePhysiological vs pathological; biliary atresia; kernicterus; phototherapy
8. Differential DiagnosisSide-by-side comparison table for all 3 types
9. ManagementObstructive (ERCP, PTC, UDCA), hepatocellular (antivirals, NAC, transplant), haemolytic, pruritus treatment
10. High-Yield Summary18 key examination points including Courvoisier's law, Reynolds' pentad, delta bilirubin, vitamin K response test
Sources: Harrison's Principles of Internal Medicine (22nd ed., 2025) and Sleisenger & Fordtran's GI and Liver Disease.
This is a shared conversation. Sign in to Orris to start your own chat.