~/pathology-reference/build_pdf.py
#!/usr/bin/env python3
"""
Comprehensive Pathology Reference PDF
Built with ReportLab Platypus
"""
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
HRFlowable, PageBreak, KeepTogether
)
from reportlab.platypus.tableofcontents import TableOfContents
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm, mm
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate
from reportlab.lib.colors import HexColor
import datetime
# ─── Colour palette ──────────────────────────────────────────────────────────
DARK_BLUE = HexColor('#1A3557')
MID_BLUE = HexColor('#2563A8')
ACCENT_RED = HexColor('#C0392B')
ACCENT_TEAL = HexColor('#16847A')
LIGHT_GRAY = HexColor('#F4F6F9')
MED_GRAY = HexColor('#8B9CB0')
TABLE_HEAD = HexColor('#1A3557')
TABLE_ALT = HexColor('#EEF2F8')
WHITE = colors.white
BLACK = colors.black
OUTPUT = "/tmp/workspace/pathology-reference/Pathology_Reference.pdf"
# ─── Document with header/footer ─────────────────────────────────────────────
class PathologyDoc(BaseDocTemplate):
def __init__(self, filename, **kwargs):
super().__init__(filename, **kwargs)
frame = Frame(
self.leftMargin, self.bottomMargin,
self.width, self.height,
id='normal'
)
template = PageTemplate(id='main', frames=frame,
onPage=self._header_footer)
self.addPageTemplates([template])
def _header_footer(self, canvas, doc):
canvas.saveState()
w, h = A4
# Header bar
canvas.setFillColor(DARK_BLUE)
canvas.rect(0, h - 1.1*cm, w, 1.1*cm, fill=1, stroke=0)
canvas.setFont('Helvetica-Bold', 9)
canvas.setFillColor(WHITE)
canvas.drawString(1.5*cm, h - 0.75*cm, "COMPREHENSIVE PATHOLOGY REFERENCE")
canvas.drawRightString(w - 1.5*cm, h - 0.75*cm,
f"Page {doc.page}")
# Footer
canvas.setFillColor(MED_GRAY)
canvas.setFont('Helvetica', 7.5)
canvas.drawString(1.5*cm, 0.7*cm,
"Based on Robbins & Kumar Basic Pathology | Robbins, Cotran & Kumar Pathologic Basis of Disease")
canvas.drawRightString(w - 1.5*cm, 0.7*cm,
f"© {datetime.date.today().year} | For Educational Use")
# Footer line
canvas.setStrokeColor(MED_GRAY)
canvas.setLineWidth(0.4)
canvas.line(1.5*cm, 1.1*cm, w - 1.5*cm, 1.1*cm)
canvas.restoreState()
# ─── Styles ───────────────────────────────────────────────────────────────────
def make_styles():
base = getSampleStyleSheet()
styles = {}
styles['cover_title'] = ParagraphStyle(
'cover_title',
fontName='Helvetica-Bold', fontSize=34,
textColor=WHITE, alignment=TA_CENTER, leading=42, spaceAfter=8
)
styles['cover_sub'] = ParagraphStyle(
'cover_sub',
fontName='Helvetica', fontSize=14,
textColor=HexColor('#BDD0E8'), alignment=TA_CENTER, leading=20
)
styles['cover_date'] = ParagraphStyle(
'cover_date',
fontName='Helvetica', fontSize=11,
textColor=HexColor('#7FA8CC'), alignment=TA_CENTER
)
styles['part_title'] = ParagraphStyle(
'part_title',
fontName='Helvetica-Bold', fontSize=22,
textColor=WHITE, alignment=TA_CENTER, leading=28
)
styles['h1'] = ParagraphStyle(
'h1',
fontName='Helvetica-Bold', fontSize=15,
textColor=WHITE, leading=20,
spaceBefore=14, spaceAfter=6,
backColor=DARK_BLUE,
leftIndent=-0.5*cm, rightIndent=-0.5*cm,
borderPad=(4, 8, 4, 8)
)
styles['h2'] = ParagraphStyle(
'h2',
fontName='Helvetica-Bold', fontSize=12,
textColor=DARK_BLUE, leading=16,
spaceBefore=12, spaceAfter=4,
borderPad=(0, 0, 2, 0),
borderColor=MID_BLUE, borderWidth=0
)
styles['h3'] = ParagraphStyle(
'h3',
fontName='Helvetica-Bold', fontSize=10.5,
textColor=ACCENT_TEAL, leading=14,
spaceBefore=8, spaceAfter=3
)
styles['body'] = ParagraphStyle(
'body',
fontName='Helvetica', fontSize=9.5,
textColor=HexColor('#2C2C2C'), leading=14,
spaceBefore=3, spaceAfter=3,
alignment=TA_JUSTIFY
)
styles['bullet'] = ParagraphStyle(
'bullet',
fontName='Helvetica', fontSize=9.5,
textColor=HexColor('#2C2C2C'), leading=13,
spaceBefore=2, spaceAfter=2,
leftIndent=14, bulletIndent=4
)
styles['sub_bullet'] = ParagraphStyle(
'sub_bullet',
fontName='Helvetica', fontSize=9,
textColor=HexColor('#3A3A3A'), leading=12,
spaceBefore=1, spaceAfter=1,
leftIndent=28, bulletIndent=18
)
styles['key_point'] = ParagraphStyle(
'key_point',
fontName='Helvetica-Bold', fontSize=9.5,
textColor=DARK_BLUE, leading=13,
spaceBefore=2, spaceAfter=2,
leftIndent=14, bulletIndent=4
)
styles['clinical_box'] = ParagraphStyle(
'clinical_box',
fontName='Helvetica-Oblique', fontSize=9,
textColor=HexColor('#1A5276'), leading=13,
spaceBefore=2, spaceAfter=2,
leftIndent=8, rightIndent=8
)
styles['table_head'] = ParagraphStyle(
'table_head',
fontName='Helvetica-Bold', fontSize=8.5,
textColor=WHITE, alignment=TA_CENTER, leading=11
)
styles['table_cell'] = ParagraphStyle(
'table_cell',
fontName='Helvetica', fontSize=8.5,
textColor=BLACK, alignment=TA_LEFT, leading=11
)
styles['table_cell_bold'] = ParagraphStyle(
'table_cell_bold',
fontName='Helvetica-Bold', fontSize=8.5,
textColor=DARK_BLUE, alignment=TA_LEFT, leading=11
)
styles['caption'] = ParagraphStyle(
'caption',
fontName='Helvetica-Oblique', fontSize=8,
textColor=MED_GRAY, alignment=TA_CENTER, leading=11,
spaceBefore=2, spaceAfter=6
)
return styles
# ─── Helpers ─────────────────────────────────────────────────────────────────
def H1(text, S): return Paragraph(f" {text}", S['h1'])
def H2(text, S): return Paragraph(text, S['h2'])
def H3(text, S): return Paragraph(text, S['h3'])
def P(text, S): return Paragraph(text, S['body'])
def B(text, S): return Paragraph(f"• {text}", S['bullet'])
def SB(text, S): return Paragraph(f"– {text}", S['sub_bullet'])
def KP(text, S): return Paragraph(f"▶ {text}", S['key_point'])
def SP(n=6): return Spacer(1, n)
def HR(): return HRFlowable(width="100%", thickness=0.5,
color=MED_GRAY, spaceAfter=6, spaceBefore=4)
def section_divider(S):
return [HR(), SP(2)]
def clinical_note(text, S):
data = [[Paragraph(f"<b>Clinical Pearl:</b> {text}", S['clinical_box'])]]
t = Table(data, colWidths=[16*cm])
t.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,-1), HexColor('#EBF5FB')),
('BOX', (0,0), (-1,-1), 1, MID_BLUE),
('LEFTPADDING', (0,0), (-1,-1), 8),
('RIGHTPADDING', (0,0), (-1,-1), 8),
('TOPPADDING', (0,0), (-1,-1), 6),
('BOTTOMPADDING', (0,0), (-1,-1), 6),
('ROUNDEDCORNERS', [4, 4, 4, 4]),
]))
return t
def warning_note(text, S):
data = [[Paragraph(f"<b>Key Concept:</b> {text}", S['clinical_box'])]]
t = Table(data, colWidths=[16*cm])
t.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,-1), HexColor('#FEF9E7')),
('BOX', (0,0), (-1,-1), 1, HexColor('#F39C12')),
('LEFTPADDING', (0,0), (-1,-1), 8),
('RIGHTPADDING', (0,0), (-1,-1), 8),
('TOPPADDING', (0,0), (-1,-1), 6),
('BOTTOMPADDING', (0,0), (-1,-1), 6),
]))
return t
def make_table(headers, rows, S, col_widths=None):
head_row = [Paragraph(h, S['table_head']) for h in headers]
data = [head_row]
for i, row in enumerate(rows):
cells = []
for j, cell in enumerate(row):
style = S['table_cell_bold'] if j == 0 else S['table_cell']
cells.append(Paragraph(str(cell), style))
data.append(cells)
if col_widths is None:
col_widths = [16*cm / len(headers)] * len(headers)
t = Table(data, colWidths=col_widths, repeatRows=1)
style_cmds = [
('BACKGROUND', (0,0), (-1,0), TABLE_HEAD),
('TEXTCOLOR', (0,0), (-1,0), WHITE),
('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
('FONTSIZE', (0,0), (-1,-1), 8.5),
('ROWBACKGROUNDS', (0,1), (-1,-1), [WHITE, TABLE_ALT]),
('GRID', (0,0), (-1,-1), 0.4, HexColor('#BFC9D4')),
('ALIGN', (0,0), (-1,-1), 'LEFT'),
('VALIGN', (0,0), (-1,-1), 'TOP'),
('LEFTPADDING', (0,0), (-1,-1), 5),
('RIGHTPADDING', (0,0), (-1,-1), 5),
('TOPPADDING', (0,0), (-1,-1), 4),
('BOTTOMPADDING', (0,0), (-1,-1), 4),
]
t.setStyle(TableStyle(style_cmds))
return t
# ─── Cover page ──────────────────────────────────────────────────────────────
def cover_page(S):
elements = []
w, h = A4
# Big colour block (simulated with a wide table)
cover_data = [['']]
cover_table = Table(cover_data, colWidths=[19*cm], rowHeights=[7*cm])
cover_table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,-1), DARK_BLUE),
]))
# Title block
title_data = [[
Paragraph("COMPREHENSIVE<br/>PATHOLOGY<br/>REFERENCE", S['cover_title'])
]]
title_table = Table(title_data, colWidths=[19*cm], rowHeights=[8*cm])
title_table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,-1), DARK_BLUE),
('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
('ALIGN', (0,0), (-1,-1), 'CENTER'),
]))
sub_data = [[
Paragraph(
"Cell Injury · Inflammation · Repair · Adaptations<br/>"
"Neoplasia · Hemodynamics · Immunopathology",
S['cover_sub']
)
]]
sub_table = Table(sub_data, colWidths=[19*cm], rowHeights=[3*cm])
sub_table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,-1), MID_BLUE),
('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
('ALIGN', (0,0), (-1,-1), 'CENTER'),
]))
date_data = [[
Paragraph(
f"Based on Robbins & Kumar Basic Pathology and Robbins, Cotran & Kumar<br/>"
f"Pathologic Basis of Disease · {datetime.date.today().strftime('%B %Y')}",
S['cover_date']
)
]]
date_table = Table(date_data, colWidths=[19*cm], rowHeights=[2.5*cm])
date_table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,-1), HexColor('#0F2437')),
('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
('ALIGN', (0,0), (-1,-1), 'CENTER'),
]))
elements += [cover_table, title_table, sub_table, date_table]
elements.append(PageBreak())
return elements
# ─── Section 1: Introduction ─────────────────────────────────────────────────
def section_intro(S):
el = []
el += [H1("PART I: FOUNDATIONS OF PATHOLOGY", S), SP(10)]
el += [H1("1. Introduction to Pathology", S), SP(6)]
el += [P(
"Pathology is the scientific study of the structural, biochemical, and functional changes "
"in cells, tissues, and organs that underlie disease. It forms the bridge between basic science "
"and clinical medicine. The pathologist identifies changes in the gross or microscopic appearance "
"of cells and tissues, as well as biochemical alterations in body fluids, to aid diagnosis, "
"predict outcomes, and guide therapy.", S
), SP(4)]
el += [H2("1.1 Core Concepts", S)]
rows = [
["Etiology", "The origin and cause of disease; includes genetic susceptibility and environmental triggers"],
["Pathogenesis", "The sequence of cellular/molecular events from the initial etiologic trigger to the final expression of disease"],
["Morphology", "Structural changes in cells and tissues — gross and microscopic"],
["Clinical Manifestation", "The signs and symptoms that result from structural and functional changes"],
["Precision Medicine", "Individualized therapy based on molecular characterization of each patient's disease"],
]
el += [make_table(["Concept", "Definition"], rows, S, [4*cm, 12*cm]), SP(6)]
el += [warning_note(
"Etiology answers WHY a disease arises. Pathogenesis describes HOW it develops. "
"Both are essential for rational treatment design.", S
), SP(8)]
el += [H2("1.2 Causes of Disease", S)]
causes = [
("Hypoxia & Ischemia", "Most common; oxygen and nutrient deprivation"),
("Toxins", "Chemical agents, drugs, environmental pollutants"),
("Infectious Agents", "Bacteria, viruses, fungi, parasites, prions"),
("Immunologic Reactions", "Autoimmunity, hypersensitivity, allograft rejection"),
("Genetic Abnormalities", "Mutations, chromosomal disorders, copy number variants"),
("Nutritional Imbalances", "Deficiencies (protein, vitamins) and excesses (obesity)"),
("Physical Agents", "Trauma, extreme temperature, radiation, electrical injury"),
("Aging", "Accumulated cellular damage, telomere shortening, epigenetic drift"),
]
for c, d in causes:
el += [B(f"<b>{c}</b> — {d}", S)]
el += [SP(4)]
return el
# ─── Section 2: Cell Injury & Death ──────────────────────────────────────────
def section_cell_injury(S):
el = []
el += [H1("2. Cell Injury, Adaptation & Death", S), SP(6)]
el += [P(
"Cells actively maintain homeostasis. When stress exceeds adaptive capacity, a spectrum "
"of responses occurs: <b>Adaptation → Reversible Injury → Irreversible Injury → Cell Death</b>. "
"The cellular response depends on the type, duration, and severity of the injury, "
"as well as the cell type, metabolic state, and genetic makeup.", S
), SP(6)]
# ── Adaptations ──
el += [H2("2.1 Cellular Adaptations to Stress", S)]
el += [H3("Hypertrophy", S)]
el += [P("Increase in cell <b>size</b>; no new cells. Occurs in cells with limited capacity to divide.", S)]
el += [B("<b>Physiologic:</b> Cardiac and skeletal muscle hypertrophy with exercise; uterus in pregnancy", S)]
el += [B("<b>Pathologic:</b> Left ventricular hypertrophy (LVH) in hypertension — α-myosin heavy chain "
"replaced by β form (slower, more energy-efficient contractions)", S)]
el += [clinical_note(
"Sustained hypertrophy can progress to ventricular dilation and heart failure when "
"blood supply, mitochondria, or biosynthetic machinery can no longer keep pace with "
"the enlarged fiber demands.", S
), SP(4)]
el += [H3("Hyperplasia", S)]
el += [P("Increase in cell <b>number</b> due to proliferation; driven by hormones or growth factors.", S)]
el += [B("<b>Physiologic:</b> Breast glandular tissue in puberty; compensatory liver hyperplasia", S)]
el += [B("<b>Pathologic:</b> Endometrial hyperplasia (estrogenic excess); benign prostatic hyperplasia (BPH)", S)]
el += [SP(4)]
el += [H3("Atrophy", S)]
el += [P("Reduction in cell <b>size and number</b>; an adaptive retreat to ensure survival.", S)]
el += [B("Causes: decreased workload, loss of innervation, reduced blood supply, inadequate nutrition, "
"loss of endocrine stimulation, aging (senile atrophy)", S)]
el += [B("Mechanism: ↓ protein synthesis + ↑ ubiquitin–proteasome degradation + increased autophagy", S)]
el += [B("Progression: severe atrophy → threshold → apoptosis", S)]
el += [SP(4)]
el += [H3("Metaplasia", S)]
el += [P("Replacement of one adult cell type by another better suited to withstand the adverse environment. "
"Arises from reprogramming of stem cells (not transdifferentiation of mature cells).", S)]
el += [B("<b>Respiratory metaplasia:</b> Ciliated columnar → stratified squamous in smokers. "
"Protective but sacrifices mucus/ciliary clearance.", S)]
el += [B("<b>Barrett's oesophagus:</b> Squamous → intestinal columnar epithelium (acid reflux). "
"Pre-malignant — risk of adenocarcinoma.", S)]
el += [SP(6)]
# ── Cell Death Comparison ──
el += [H2("2.2 Forms of Cell Death", S)]
rows = [
["Cell size", "Enlarged (swelling)", "Reduced (shrinkage)"],
["Nucleus", "Pyknosis → karyorrhexis → karyolysis", "Fragmented into nucleosome-sized fragments"],
["Plasma membrane", "Disrupted — contents leak", "Intact; altered lipid orientation"],
["Cellular contents", "Released into extracellular space", "Packaged into apoptotic bodies"],
["Tissue reaction", "Inflammatory — always", "No inflammation — anti-inflammatory"],
["ATP required", "No", "Yes"],
["Regulation", "Unregulated (accidental)", "Highly regulated (programmed)"],
["Caspase activation", "No", "Yes (central executioners)"],
]
el += [make_table(["Feature", "Necrosis", "Apoptosis"], rows, S, [4.5*cm, 5.75*cm, 5.75*cm]), SP(6)]
# ── Necrosis patterns ──
el += [H2("2.3 Morphologic Patterns of Necrosis", S)]
rows = [
["Coagulative", "Architecture preserved for days; firm, eosinophilic, anucleate cells",
"Infarcts in all solid organs (except brain)"],
["Liquefactive", "Complete digestion; viscous liquid. Yellow pus if bacterial.",
"Brain infarcts; bacterial abscesses"],
["Caseous", "Friable cheese-like yellow-white debris; amorphous granular pink on H&E; "
"architecture obliterated",
"Tuberculosis (pathognomonic)"],
["Fat", "Focal fat destruction; chalky-white calcium-fatty acid deposits; "
"saponification on gross exam",
"Acute pancreatitis; abdominal trauma"],
["Fibrinoid", "Bright pink amorphous deposits in vessel walls (microscopy only)",
"Immune vasculitis; malignant hypertension"],
["Gangrenous", "Coagulative + liquefactive necrosis (wet gangrene with superinfection)",
"Limb ischaemia"],
]
el += [make_table(["Type", "Characteristics", "Typical Setting"], rows, S,
[3.5*cm, 7.5*cm, 5*cm]), SP(6)]
# ── Mechanisms of Injury ──
el += [H2("2.4 Mechanisms of Cell Injury", S)]
el += [H3("1. Mitochondrial Dysfunction & ATP Depletion", S)]
el += [B("↓ ATP → failure of Na/K ATPase → Na and water influx → cell swelling", S)]
el += [B("Compensatory anaerobic glycolysis → ↑ lactic acid → ↓ pH → enzyme inhibition", S)]
el += [B("Ribosome detachment from RER → ↓ protein synthesis", S)]
el += [B("Release of cytochrome c → activates apoptotic caspase cascade", S)]
el += [warning_note(
"Skeletal muscle tolerates ischaemia for 2–3 hours; cardiac muscle dies after only "
"20–30 minutes — a direct reflection of their differing metabolic demands.", S
), SP(4)]
el += [H3("2. Oxidative Stress (Reactive Oxygen Species)", S)]
el += [B("Sources: mitochondrial leak, radiation, reperfusion injury, neutrophil oxidative burst", S)]
el += [B("Damage: lipid peroxidation of membranes; protein oxidation; DNA strand breaks", S)]
el += [B("Defence: SOD, catalase, glutathione peroxidase, vitamins C and E", S)]
el += [SP(3)]
el += [H3("3. Calcium Dysregulation", S)]
el += [P("Ischaemia and toxins increase intracellular Ca²⁺, activating:", S)]
rows = [
["Phospholipases", "Membrane damage"],
["Proteases", "Cytoskeletal destruction (spectrin, fodrin)"],
["Endonucleases", "DNA and chromatin damage"],
["ATPases", "Further ATP depletion"],
["Nitric oxide synthase", "↑ NO → reactive nitrogen species"],
]
el += [make_table(["Enzyme Activated", "Consequence"], rows, S, [6*cm, 10*cm]), SP(4)]
el += [H3("4. Membrane Damage", S)]
el += [B("Direct plasma membrane injury → loss of osmotic balance → cell lysis", S)]
el += [B("Lysosomal membrane rupture → release of digestive enzymes into cytoplasm (key amplifier)", S)]
el += [B("Mitochondrial permeability transition pore (mPTP) opening → catastrophic ATP loss", S)]
el += [SP(3)]
el += [H3("5. DNA Damage", S)]
el += [B("Mild DNA damage → p53 activation → cell cycle arrest → DNA repair", S)]
el += [B("Severe DNA damage → p53 induces pro-apoptotic BH3-only proteins → apoptosis", S)]
el += [SP(6)]
# ── Apoptosis mechanisms ──
el += [H2("2.5 Mechanisms of Apoptosis", S)]
rows = [
["Intrinsic (Mitochondrial)", "DNA damage, growth factor withdrawal, ER stress",
"Pro-apoptotic BCL-2 family (BAX, BAK) open mitochondrial membrane → cytochrome c release "
"→ apoptosome → caspase-9 → effector caspases (3, 6, 7)"],
["Extrinsic (Death Receptor)", "FasL–Fas (CD95) binding; TNF–TNFR1 binding",
"Death-inducing signalling complex (DISC) → caspase-8 activation → effector caspases"],
["Perforin/Granzyme", "Cytotoxic T lymphocyte (CTL) killing",
"Granzyme B enters target cell via perforin pores → directly activates caspases"],
]
el += [make_table(["Pathway", "Triggers", "Mechanism"], rows, S, [3.5*cm, 4.5*cm, 8*cm]), SP(4)]
el += [clinical_note(
"BCL-2 is the archetypal anti-apoptotic protein. Its overexpression (t(14;18) in follicular "
"lymphoma) blocks apoptosis, promoting tumour cell survival — a direct link between "
"apoptosis dysregulation and cancer.", S
), SP(6)]
# ── Autophagy ──
el += [H2("2.6 Autophagy", S)]
el += [P(
"A survival mechanism in which a nutrient-starved cell sequesters its own organelles in "
"double-membrane vesicles (autophagosomes) that fuse with lysosomes for digestion. "
"The degradation products are recycled for energy and biosynthesis. Excessive or "
"dysregulated autophagy can trigger apoptosis.", S
), SP(4)]
el += [H2("2.7 Ischaemia–Reperfusion Injury", S)]
el += [P(
"Paradoxically, restoration of blood flow after ischaemia can worsen cell injury. "
"Mechanisms include:", S
)]
el += [B("Burst of reactive oxygen species upon re-oxygenation", S)]
el += [B("Massive Ca²⁺ influx into cells that survived ischaemia", S)]
el += [B("Opening of mitochondrial permeability transition pore (mPTP)", S)]
el += [B("Neutrophil activation and inflammatory mediator release", S)]
el += [clinical_note(
"Ischaemia–reperfusion injury is clinically relevant in myocardial infarction after "
"thrombolysis/PCI, stroke, organ transplantation, and tourniquet release. "
"Cardioprotective strategies target mPTP opening and ROS generation.", S
), SP(8)]
return el
# ─── Section 3: Inflammation ─────────────────────────────────────────────────
def section_inflammation(S):
el = []
el += [H1("PART II: INFLAMMATION & REPAIR", S), SP(10)]
el += [H1("3. Inflammation", S), SP(6)]
el += [P(
"Inflammation is the body's protective response to infection and tissue damage, designed to "
"eliminate the injurious stimulus and initiate repair. It is a double-edged sword: while "
"essential for survival, it also mediates tissue injury in many common diseases "
"(atherosclerosis, rheumatoid arthritis, asthma, inflammatory bowel disease).", S
), SP(4)]
el += [H2("3.1 Cardinal Signs of Inflammation", S)]
rows = [
["Rubor (Redness)", "Vasodilation → increased blood flow"],
["Calor (Heat)", "Vasodilation + increased metabolic activity"],
["Tumor (Swelling)", "Increased vascular permeability → exudate in tissue"],
["Dolor (Pain)", "Prostaglandins + bradykinin sensitise nociceptors"],
["Functio Laesa (Loss of function)", "Combination of pain, swelling, and tissue damage"],
]
el += [make_table(["Cardinal Sign", "Mechanism"], rows, S, [5*cm, 11*cm]), SP(6)]
el += [H2("3.2 Causes of Inflammation", S)]
el += [B("<b>Infections:</b> bacteria, viruses, fungi, parasites", S)]
el += [B("<b>Tissue necrosis:</b> ischaemia, trauma, burns — DAMPs trigger 'sterile' inflammation", S)]
el += [B("<b>Foreign bodies:</b> sutures, implants, urate crystals (gout), cholesterol crystals", S)]
el += [B("<b>Immune reactions:</b> autoimmunity (Type II–IV hypersensitivity), allergy (Type I)", S)]
el += [SP(6)]
el += [H2("3.3 Recognition — Sentinel Cells & Pattern Recognition", S)]
el += [P(
"Tissue-resident macrophages and dendritic cells express pattern-recognition receptors (PRRs) "
"that detect conserved molecular patterns:", S
)]
rows = [
["PAMPs", "Pathogen-Associated Molecular Patterns", "Microbial products: LPS, flagellin, peptidoglycan, viral dsRNA"],
["DAMPs", "Damage-Associated Molecular Patterns", "Signals from injured cells: HMGB1, ATP, uric acid, heat shock proteins, leaked DNA"],
["TLRs", "Toll-like Receptors", "Surface and endosomal PRRs; activation → NF-κB → pro-inflammatory cytokines"],
["NLRs / Inflammasome", "NOD-like Receptors", "Cytosolic sensors; assembly of inflammasome complex → active IL-1β and IL-18"],
]
el += [make_table(["Acronym", "Name", "Function"], rows, S, [2.5*cm, 5*cm, 8.5*cm]), SP(6)]
el += [H2("3.4 Acute Inflammation", S)]
el += [P("Three cardinal vascular and cellular components:", S)]
el += [KP("1. Vasodilation — histamine, NO, prostaglandins → ↑ blood flow", S)]
el += [KP("2. Increased vascular permeability — plasma proteins leak into tissue → exudate", S)]
el += [KP("3. Leukocyte emigration — neutrophils exit vessels into tissue", S)]
el += [SP(6)]
el += [H3("Leukocyte Recruitment Sequence", S)]
rows = [
["1. Margination", "Leukocytes leave central axial flow toward vessel wall"],
["2. Rolling", "Selectins (E-selectin, P-selectin on endothelium; L-selectin on leukocytes) — loose adhesion"],
["3. Adhesion", "Integrins (LFA-1, Mac-1) bind ICAM-1 on endothelium; triggered by TNF and IL-1 — firm adhesion"],
["4. Transmigration (Diapedesis)", "Leukocytes squeeze through intercellular junctions; PECAM-1 (CD31) facilitates crossing"],
["5. Chemotaxis", "Migration toward chemical gradient: C5a, LTB4, bacterial products, IL-8 (CXCL8)"],
["6. Phagocytosis", "Engulfment of opsonised targets (IgG, C3b) + intracellular killing"],
]
el += [make_table(["Step", "Mechanism"], rows, S, [4*cm, 12*cm]), SP(6)]
el += [H2("3.5 Key Inflammatory Mediators", S)]
rows = [
["Histamine", "Mast cells, basophils, platelets", "Rapid vasodilation, ↑ permeability; first mediator released"],
["Serotonin (5-HT)", "Platelets", "Similar to histamine in vessels"],
["PGE2, PGI2", "Arachidonic acid (COX pathway)", "Vasodilation, fever, pain sensitisation"],
["LTB4", "Arachidonic acid (LOX pathway)", "Potent neutrophil chemotaxis"],
["LTC4, LTD4, LTE4", "LOX pathway; mast cells", "Bronchoconstriction, mucus secretion (asthma)"],
["PAF", "Leukocytes, endothelium, platelets", "Platelet aggregation, bronchoconstriction, ↑ permeability"],
["TNF-α, IL-1", "Macrophages, mast cells", "Fever, acute-phase response, endothelial activation, septic shock"],
["IL-6", "Macrophages, T cells", "Acute-phase protein synthesis, fever"],
["IL-8 (CXCL8)", "Macrophages, endothelium", "Potent neutrophil chemokine"],
["IL-17", "T lymphocytes (Th17)", "Neutrophil recruitment; drives chronic inflammatory diseases"],
["IL-12", "Macrophages, DCs", "Activates NK cells; promotes Th1 differentiation"],
["Complement C3a, C5a", "Complement cascade", "Mast cell degranulation, chemotaxis, opsonisation"],
["Nitric oxide (NO)", "Macrophages (iNOS)", "Vasodilation, microbicidal activity"],
["Reactive O₂ species", "Neutrophils (NADPH oxidase)", "Microbicidal; also causes bystander tissue damage"],
]
el += [make_table(
["Mediator", "Source", "Key Action"], rows, S,
[4*cm, 4.5*cm, 7.5*cm]
), SP(4)]
el += [clinical_note(
"NSAIDs inhibit COX enzymes, blocking prostaglandin synthesis. Corticosteroids "
"block phospholipase A2 (reducing arachidonic acid release) AND suppress cytokine "
"production — explaining their broader anti-inflammatory potency.", S
), SP(6)]
el += [H2("3.6 Morphologic Patterns of Acute Inflammation", S)]
rows = [
["Serous", "Watery, protein-poor transudate/exudate", "Skin blisters (burns, herpes); pleural effusion (early)"],
["Fibrinous", "Fibrin-rich exudate; major vascular leak", "Fibrinous pericarditis ('bread-and-butter' appearance); fibrinous pleuritis"],
["Purulent (Suppurative)", "Pus = neutrophils + necrotic debris + organisms", "Bacterial abscesses; acute appendicitis; empyema"],
["Ulcerative", "Epithelial erosion exposing deeper layers", "Peptic ulcer; aphthous ulcers; chronic venous ulcers"],
["Pseudomembranous", "Inflammatory debris on mucosal surface", "C. difficile colitis; diphtheria"],
["Haemorrhagic", "Severe vascular damage + RBC leak", "Anthrax, plague, haemorrhagic viral fevers"],
]
el += [make_table(["Pattern", "Description", "Examples"], rows, S, [3.5*cm, 5.5*cm, 7*cm]), SP(6)]
el += [H2("3.7 Outcomes of Acute Inflammation", S)]
el += [B("<b>Complete resolution</b> — if brief injury, minimal destruction; macrophages phagocytose debris", S)]
el += [B("<b>Abscess formation</b> — pyogenic infection isolated by fibrous wall", S)]
el += [B("<b>Progression to chronic inflammation</b> — if injurious agent persists", S)]
el += [B("<b>Repair by scarring</b> — if extensive tissue destruction; collagen replacement", S)]
el += [SP(6)]
el += [H2("3.8 Chronic Inflammation", S)]
el += [P(
"Chronic inflammation occurs when the injurious agent persists or there is an abnormal "
"immune response. Unlike acute inflammation (neutrophil-dominated), chronic inflammation "
"is characterised by a <b>mononuclear infiltrate</b>, ongoing tissue destruction, and "
"simultaneous repair attempts.", S
), SP(4)]
el += [H3("Key Cellular Players", S)]
rows = [
["Macrophages", "Dominant cell. Produce TNF, IL-1, IL-12, ROS, proteases, VEGF. "
"Drive both injury and repair (two phenotypes: M1 inflammatory vs M2 repair)"],
["T Lymphocytes (CD4+)", "Th1 cells activate macrophages via IFN-γ. "
"Th2 cells promote eosinophil activation and antibody responses. "
"Th17 cells recruit neutrophils via IL-17"],
["B Lymphocytes / Plasma Cells", "Produce antibodies; prominent in autoimmune diseases "
"and infections (e.g., H. pylori gastritis)"],
["Eosinophils", "Prominent in parasitic infections and IgE-mediated allergic reactions; "
"toxic granule contents (major basic protein, eosinophil cationic protein)"],
["Mast Cells", "Tissue-resident; degranulate in allergic reactions; regulate "
"vasodilation and vascular permeability"],
]
el += [make_table(["Cell", "Role"], rows, S, [4*cm, 12*cm]), SP(6)]
el += [H2("3.9 Granulomatous Inflammation", S)]
el += [P(
"A special pattern of chronic inflammation characterised by collections of activated "
"macrophages (epithelioid cells) often fused into multinucleated giant cells, surrounded "
"by a rim of lymphocytes. Represents an attempt to wall off indigestible material.", S
), SP(4)]
rows = [
["Tuberculosis", "Caseating (with central necrosis) — cheese-like friable yellow-white centre", "Mycobacterium tuberculosis"],
["Sarcoidosis", "Non-caseating; asteroid bodies in giant cells", "Unknown antigen; T-cell mediated"],
["Crohn's Disease", "Non-caseating; transmural", "Dysregulated immune response to gut flora"],
["Leprosy", "Lepromatous (many bacilli, no T-cell response) vs tuberculoid (few bacilli, granulomas)", "Mycobacterium leprae"],
["Fungal Infections", "Variable necrosis", "Histoplasma, Cryptococcus, Coccidioides"],
["Foreign Body", "Foreign body giant cells around material", "Sutures, silica, beryllium, urate crystals"],
["Cat-Scratch Disease", "Stellate necrosis in granuloma centre", "Bartonella henselae"],
]
el += [make_table(["Condition", "Features", "Cause/Agent"], rows, S, [3.5*cm, 7.5*cm, 5*cm]), SP(6)]
el += [H2("3.10 Systemic Effects of Inflammation — Acute Phase Response", S)]
el += [B("<b>Fever:</b> IL-1, TNF, IL-6 → hypothalamic COX-2 → ↑ PGE2 → reset thermostat", S)]
el += [B("<b>Acute-phase proteins:</b> CRP, SAA, fibrinogen, complement ↑; albumin ↓ (negative)", S)]
el += [B("<b>Leucocytosis:</b> IL-1, TNF → bone marrow release. Neutrophilia (bacteria), lymphocytosis (viruses), "
"eosinophilia (parasites/allergy)", S)]
el += [B("<b>Septic shock:</b> Massive TNF/IL-1 release → systemic vasodilation, DIC, multi-organ failure", S)]
el += [SP(8)]
return el
# ─── Section 4: Tissue Repair ─────────────────────────────────────────────────
def section_repair(S):
el = []
el += [H1("4. Tissue Repair, Regeneration & Fibrosis", S), SP(6)]
el += [P(
"After injury, tissues repair by two main processes: "
"<b>regeneration</b> (replacement with the same cell type) or "
"<b>scarring/fibrosis</b> (collagen deposition when regeneration is insufficient). "
"Most injuries involve both in varying proportions.", S
), SP(4)]
el += [H2("4.1 Proliferative Capacity of Cells", S)]
rows = [
["Labile (Continuously Dividing)", "Continuously replace dead cells; driven by stem cells",
"Haematopoietic cells, gut epithelium, skin, corneal epithelium",
"Excellent — regenerate fully"],
["Stable (Quiescent)", "Low normal replication; re-enter cycle when stimulated",
"Hepatocytes, renal tubular cells, smooth muscle, endothelium, fibroblasts",
"Good if scaffold intact"],
["Permanent (Non-Dividing)", "Terminally differentiated; cannot re-enter cell cycle",
"Neurons, cardiac myocytes, skeletal muscle cells",
"No regeneration — replaced by scar"],
]
el += [make_table(
["Category", "Definition", "Examples", "Repair Potential"],
rows, S, [3.5*cm, 4*cm, 5.5*cm, 3*cm]
), SP(6)]
el += [H2("4.2 Steps in Scar Formation", S)]
steps = [
("Angiogenesis", "VEGF (from macrophages and hypoxic cells) drives endothelial sprouting. "
"Forms granulation tissue — hallmark: pale pink, oedematous, with loops of new capillaries."),
("Fibroblast Migration & Activation", "PDGF (from platelets/macrophages) and TGF-β recruit and activate fibroblasts. "
"Myofibroblasts (α-SMA positive) contract the wound edges."),
("Collagen Synthesis", "TGF-β is the master driver of collagen synthesis. Type III collagen "
"(early) is replaced by type I collagen (mature scar). "
"Requires Vitamin C for hydroxylation of proline/lysine."),
("ECM Remodelling", "Matrix metalloproteinases (MMPs — collagenase, gelatinase) degrade provisional ECM. "
"TIMP (tissue inhibitors of metalloproteinases) balance MMP activity."),
("Wound Contraction", "Myofibroblasts draw wound edges together; can cause contractures in "
"large wounds (e.g., burn scarring)."),
]
for title, desc in steps:
el += [H3(f"Step: {title}", S), P(desc, S)]
el += [warning_note(
"Wound healing requires: adequate nutrition (esp. Vitamin C and zinc), "
"adequate blood supply, absence of infection, and absence of persistent mechanical stress. "
"Diabetes, corticosteroids, and malnutrition are key inhibitors.", S
), SP(6)]
el += [H2("4.3 Types of Wound Healing", S)]
rows = [
["Primary Intention", "Clean incised wound with apposed edges",
"Minimal granulation tissue; thin scar; e.g., surgical incision"],
["Secondary Intention", "Large wound with gaping edges; tissue loss",
"Extensive granulation tissue; wound contraction; larger scar; e.g., large ulcer"],
["Tertiary Intention", "Delayed primary closure; wound left open initially",
"Used in contaminated wounds; closed after infection cleared"],
]
el += [make_table(["Type", "Context", "Features"], rows, S, [4*cm, 5*cm, 7*cm]), SP(6)]
el += [H2("4.4 Pathologic Forms of Repair", S)]
el += [H3("Keloid", S)]
el += [B("Excessive collagen deposition extending beyond original wound borders", S)]
el += [B("More common in dark-skinned individuals; tendency to recur after excision", S)]
el += [H3("Hypertrophic Scar", S)]
el += [B("Excessive collagen within wound boundaries; may regress with time", S)]
el += [H3("Fibrosis / Cirrhosis", S)]
el += [B("Excessive scarring in parenchymal organs (liver, lung, kidney)", S)]
el += [B("Destroys organ architecture and function; driven by persistent inflammation and TGF-β", S)]
el += [B("Examples: hepatic cirrhosis (alcohol/NASH), pulmonary fibrosis, glomerulosclerosis", S)]
el += [SP(8)]
return el
# ─── Section 5: Neoplasia ─────────────────────────────────────────────────────
def section_neoplasia(S):
el = []
el += [H1("PART III: NEOPLASIA", S), SP(10)]
el += [H1("5. Neoplasia — Tumours & Cancer", S), SP(6)]
el += [P(
"A neoplasm (Greek: neos = new + plasma = growth) is an abnormal mass of tissue whose growth "
"is excessive and uncoordinated with normal tissue, persists even after the stimulus is removed. "
"Neoplasms may be benign or malignant.", S
), SP(4)]
el += [H2("5.1 Benign vs Malignant Tumours", S)]
rows = [
["Differentiation", "Well differentiated; resembles tissue of origin", "Variable; may be poorly or undifferentiated"],
["Rate of growth", "Slow; mitoses rare and normal", "Rapid; mitoses frequent, often abnormal"],
["Local invasion", "Non-invasive; expansile, encapsulated", "Invasive; infiltrates surrounding tissue"],
["Metastasis", "Absent — cardinal feature distinguishing benign", "Present — defines malignancy absolutely"],
["Effect on host", "Local pressure; rarely fatal", "Destruction, cachexia, paraneoplastic syndromes; often fatal"],
["Nomenclature (epithelial)", "Adenoma, papilloma, cystadenoma", "Carcinoma, adenocarcinoma"],
["Nomenclature (mesenchymal)", "Lipoma, fibroma, leiomyoma", "Liposarcoma, fibrosarcoma, leiomyosarcoma"],
]
el += [make_table(["Feature", "Benign", "Malignant"], rows, S, [4*cm, 6*cm, 6*cm]), SP(6)]
el += [H2("5.2 Tumour Nomenclature", S)]
rows = [
["Squamous epithelium", "Squamous cell papilloma", "Squamous cell carcinoma"],
["Glandular epithelium", "Adenoma", "Adenocarcinoma"],
["Transitional epithelium", "Transitional cell papilloma", "Transitional cell carcinoma (urothelial ca.)"],
["Hepatocytes", "Hepatocellular adenoma", "Hepatocellular carcinoma (hepatoma)"],
["Fat", "Lipoma", "Liposarcoma"],
["Cartilage", "Chondroma", "Chondrosarcoma"],
["Bone", "Osteoma", "Osteosarcoma"],
["Smooth muscle", "Leiomyoma", "Leiomyosarcoma"],
["Striated muscle", "Rhabdomyoma", "Rhabdomyosarcoma"],
["Blood vessels", "Haemangioma", "Angiosarcoma"],
["Nerve sheath", "Neurofibroma, schwannoma", "Malignant peripheral nerve sheath tumour"],
["Melanocytes", "Melanocytic naevus (mole)", "Melanoma"],
["Lymphocytes", "—", "Lymphoma, leukaemia"],
["Plasma cells", "—", "Multiple myeloma"],
["Mixed / Embryonal", "Mature teratoma", "Wilms' tumour, retinoblastoma"],
]
el += [make_table(["Cell/Tissue of Origin", "Benign", "Malignant"], rows, S, [4.5*cm, 5*cm, 6.5*cm]), SP(6)]
el += [H2("5.3 Hallmarks of Cancer", S)]
el += [P("Hanahan and Weinberg defined the following acquired capabilities of cancer cells:", S), SP(3)]
hallmarks = [
("Self-sufficiency in growth signals", "Oncogene activation; autocrine stimulation (e.g., RAS mutations)"),
("Insensitivity to anti-growth signals", "Loss of tumour suppressors (RB, p16, SMAD pathway)"),
("Evasion of apoptosis", "BCL-2 overexpression; loss of p53; upregulation of IAPs"),
("Limitless replicative potential (immortality)", "Telomerase re-activation; bypasses Hayflick limit"),
("Sustained angiogenesis", "VEGF overexpression; supply tumour with O₂ and nutrients"),
("Tissue invasion and metastasis", "Loss of E-cadherin; MMP upregulation; EMT"),
("Reprogramming of energy metabolism", "Warburg effect: aerobic glycolysis even in the presence of O₂"),
("Evading immune destruction", "PD-L1 expression; secretion of TGF-β; loss of MHC-I"),
("Tumour-promoting inflammation", "Chronic inflammation supplies growth factors and mutation-causing ROS"),
("Genome instability and mutation", "Defective DNA repair; microsatellite instability; chromosomal instability"),
]
rows = [[h, d] for h, d in hallmarks]
el += [make_table(["Hallmark", "Key Mechanism"], rows, S, [6*cm, 10*cm]), SP(6)]
el += [H2("5.4 Carcinogenesis — Molecular Basis", S)]
el += [H3("Oncogenes", S)]
el += [P(
"Oncogenes are derived from normal proto-oncogenes by gain-of-function mutations. "
"They encode proteins that drive proliferation.", S
)]
rows = [
["RAS (KRAS, NRAS)", "GTPase signal transduction", "KRAS: pancreatic (90%), colorectal (50%), lung"],
["MYC", "Transcription factor; drives proliferation", "Burkitt lymphoma (t(8;14)); many solid tumours"],
["ERBB2 (HER2)", "Receptor tyrosine kinase", "Breast, gastric (amplification; target of trastuzumab)"],
["BCL-2", "Anti-apoptotic", "Follicular lymphoma (t(14;18))"],
["EGFR", "Receptor tyrosine kinase", "Lung adenocarcinoma; glioblastoma"],
["BRAF (V600E)", "Serine/threonine kinase", "Melanoma (50%), papillary thyroid cancer, colorectal"],
]
el += [make_table(["Oncogene", "Function", "Key Cancers"], rows, S, [4*cm, 5*cm, 7*cm]), SP(4)]
el += [H3("Tumour Suppressor Genes", S)]
el += [P(
"Tumour suppressors restrain cell growth. Both alleles must be inactivated "
"(Knudson's 'two-hit hypothesis') — the first hit is inherited or somatic, "
"the second is somatic loss of heterozygosity (LOH).", S
)]
rows = [
["RB1 (Retinoblastoma)", "Cell cycle brake at G1/S checkpoint (pocket protein)", "Retinoblastoma; osteosarcoma; SCLC"],
["TP53 (p53)", "Guardian of the genome: DNA damage → apoptosis or cell cycle arrest",
"50% of all human cancers; Li-Fraumeni syndrome (germline)"],
["APC", "β-catenin degradation (Wnt pathway suppressor)", "Colorectal cancer; FAP"],
["BRCA1/2", "Homologous recombination DNA repair", "Breast (up to 80% lifetime risk), ovarian cancer"],
["CDKN2A (p16)", "Inhibits CDK4/6, maintaining RB in active (hypophosphorylated) form",
"Melanoma, pancreatic cancer, many others"],
["PTEN", "Phosphatase; opposes PI3K/AKT signalling", "Endometrial cancer; Cowden syndrome; glioblastoma"],
["VHL", "Targets HIF-1α for degradation", "Renal clear cell carcinoma"],
["SMAD4 / DPC4", "TGF-β signalling effector (anti-proliferative)", "Pancreatic cancer (55%), colorectal"],
]
el += [make_table(["Tumour Suppressor", "Function", "Key Cancers/Syndromes"], rows, S, [3.5*cm, 6.5*cm, 6*cm]), SP(4)]
el += [H2("5.5 Invasion and Metastasis", S)]
el += [P("Metastasis is the spread of tumour cells from the primary site to distant locations. "
"Only malignant tumours metastasise. Steps in the metastatic cascade:", S)]
steps_meta = [
"Detachment from primary tumour — loss of E-cadherin; epithelial-mesenchymal transition (EMT)",
"Invasion of ECM — MMPs degrade basement membrane and interstitial collagen",
"Intravasation — entry into lymphatics or blood vessels",
"Survival in circulation — evasion of immune destruction; tumour cell emboli",
"Extravasation — arrest at secondary site, adhesion to endothelium, exit from vessel",
"Formation of micrometastasis — colonisation of distant stroma; depends on 'seed and soil' compatibility",
"Macrometastasis — angiogenesis in secondary site; clinically detectable disease",
]
for i, step in enumerate(steps_meta, 1):
el += [B(f"<b>Step {i}:</b> {step}", S)]
el += [SP(4)]
el += [H3("Common Metastatic Patterns", S)]
rows = [
["Lung carcinoma", "Adrenal glands, liver, bone, brain"],
["Breast carcinoma", "Bone (osteolytic), lung, liver, brain; sentinel LN → axillary LN"],
["Prostate carcinoma", "Bone (osteoblastic — 'ivory vertebra')"],
["Colorectal carcinoma", "Liver (portal drainage); then lung"],
["Gastric carcinoma", "Peritoneum; Virchow's node (left supraclavicular); Krukenberg tumour (ovaries)"],
["Renal cell carcinoma", "'Clear cell' — metastasises late but to unusual sites (thyroid, skin)"],
["Melanoma", "Brain, liver, skin, bone; haematogenous spread early"],
]
el += [make_table(["Primary Tumour", "Typical Metastatic Sites"], rows, S, [5*cm, 11*cm]), SP(6)]
el += [H2("5.6 Carcinogenic Agents", S)]
rows = [
["Chemical", "Direct-acting alkylating agents (nitrogen mustard); indirect-acting polycyclic hydrocarbons "
"(benzo[a]pyrene in tobacco smoke — metabolised by CYP enzymes to reactive epoxides)",
"Lung, bladder, skin"],
["Radiation (UV)", "UV-B → pyrimidine dimers → C→T transversions in p53; failure of nucleotide excision repair",
"Skin (BCC, SCC, melanoma)"],
["Radiation (ionising)", "Double-strand DNA breaks; chromosomal rearrangements",
"Leukaemia, thyroid, breast"],
["Viral (DNA)", "HPV (E6 inactivates p53, E7 inactivates RB); HBV (HCC); EBV (BL, NPC, Hodgkin); "
"KSHV/HHV8 (Kaposi sarcoma)", "Cervical, HCC, lymphomas"],
["Viral (RNA — retroviruses)", "HTLV-1 → Tax protein activates NF-κB, cyclin D", "Adult T-cell leukaemia/lymphoma"],
["Helicobacter pylori", "Chronic gastritis → metaplasia → gastric adenocarcinoma; also MALT lymphoma", "Stomach"],
["Aflatoxin B1 (Aspergillus)", "Highly reactive epoxide → adducts with guanine in p53 codon 249",
"HCC (Africa, Asia)"],
]
el += [make_table(["Agent", "Mechanism", "Associated Cancer"], rows, S, [3*cm, 9*cm, 4*cm]), SP(8)]
return el
# ─── Section 6: Haemodynamics ─────────────────────────────────────────────────
def section_haemodynamics(S):
el = []
el += [H1("PART IV: HAEMODYNAMICS & THROMBOSIS", S), SP(10)]
el += [H1("6. Haemodynamic Disorders", S), SP(6)]
el += [H2("6.1 Oedema", S)]
el += [P("Accumulation of fluid in interstitial tissue spaces or body cavities. "
"Two types: <b>Exudate</b> (protein-rich, SG > 1.020, inflammatory) vs "
"<b>Transudate</b> (protein-poor, SG < 1.012, non-inflammatory).", S)]
rows = [
["↓ Plasma oncotic pressure", "Hypoalbuminaemia (nephrotic syndrome, cirrhosis, malnutrition)", "Transudate; generalised"],
["↑ Hydrostatic pressure", "Venous obstruction, cardiac failure, portal hypertension", "Transudate; local/dependent"],
["↑ Vascular permeability", "Inflammation, burns, allergic reaction", "Exudate; localised"],
["Lymphatic obstruction", "Filariasis, post-mastectomy, tumour infiltration", "Lymphoedema; pitting"],
["Sodium/water retention", "Renal failure, hyperaldosteronism", "Transudate; generalised"],
]
el += [make_table(["Mechanism", "Causes", "Features"], rows, S, [4.5*cm, 7*cm, 4.5*cm]), SP(6)]
el += [H2("6.2 Thrombosis — Virchow's Triad", S)]
rows = [
["Endothelial injury", "Atherosclerosis, hypertension, vasculitis, homocysteinaemia",
"Exposes subendothelial collagen and tissue factor → platelet adhesion + coagulation cascade"],
["Stasis / turbulent flow", "Atrial fibrillation, aneurysm, immobilisation, post-op",
"Reduces washout of activated clotting factors; hypoxia of endothelium"],
["Hypercoagulability", "Factor V Leiden, prothrombin gene mutation, antiphospholipid syndrome, "
"malignancy, OCP, antithrombin/protein C/S deficiency",
"Inherited or acquired thrombophilia"],
]
el += [make_table(["Component", "Causes", "Mechanism"], rows, S, [3.5*cm, 6.5*cm, 6*cm]), SP(4)]
el += [clinical_note(
"Factor V Leiden (R506Q mutation) is the most common inherited thrombophilia. "
"Mutant factor Va is resistant to inactivation by protein C — risk of DVT and PE.", S
), SP(6)]
el += [H2("6.3 Embolism", S)]
rows = [
["Pulmonary thromboembolism", "DVT from lower limb/pelvic veins", "Pleuritic chest pain, dyspnoea; massive PE → sudden death"],
["Systemic arterial embolism", "Left atrial thrombus (AF), LV thrombus (post-MI), endocarditis vegetations",
"Stroke, limb ischaemia, renal/mesenteric infarction"],
["Fat embolism", "Long bone fracture, liposuction, bone marrow transplant",
"Petechiae, altered consciousness, respiratory failure (72h post-trauma)"],
["Air embolism", "Iatrogenic (IV lines), decompression sickness",
"Gas lock in heart; bends in divers"],
["Amniotic fluid embolism", "Labour, rupture of foetal membranes",
"Sudden cardiovascular collapse + DIC; rare but highly lethal"],
["Septic embolism", "Infected heart valves, IV drug use",
"Metastatic abscesses"],
]
el += [make_table(["Type", "Source", "Consequences"], rows, S, [4*cm, 6*cm, 6*cm]), SP(6)]
el += [H2("6.4 Infarction", S)]
el += [P("Ischaemic necrosis due to obstruction of arterial supply (or, rarely, venous drainage).", S)]
rows = [
["Red (haemorrhagic) infarct", "Loose tissue (lung); dual blood supply (liver, small bowel); "
"reperfused infarct; venous occlusion",
"Wedge-shaped, haemorrhagic; lung, small intestine"],
["White (pale/anaemic) infarct", "Solid organs with end-arterial supply",
"Wedge-shaped, pale, coagulative necrosis; heart, kidney, spleen"],
]
el += [make_table(["Type", "Setting", "Examples"], rows, S, [3.5*cm, 7.5*cm, 5*cm]), SP(6)]
el += [H2("6.5 Disseminated Intravascular Coagulation (DIC)", S)]
el += [P(
"DIC is a pathologic activation of the coagulation cascade, consuming clotting factors "
"and platelets and activating fibrinolysis. Results in simultaneous thrombosis and bleeding.", S
)]
el += [B("<b>Causes:</b> Sepsis (most common), obstetric catastrophes (abruption, amniotic fluid embolism), "
"massive trauma, malignancy (especially APML), burns, incompatible blood transfusion", S)]
el += [B("<b>Lab findings:</b> ↑ PT, ↑ APTT, ↑ D-dimer, ↓ fibrinogen, ↓ platelets, "
"microangiopathic haemolytic anaemia (schistocytes)", S)]
el += [SP(8)]
return el
# ─── Section 7: Immunopathology ───────────────────────────────────────────────
def section_immunopath(S):
el = []
el += [H1("PART V: IMMUNOPATHOLOGY", S), SP(10)]
el += [H1("7. Hypersensitivity Reactions & Autoimmunity", S), SP(6)]
el += [H2("7.1 Gell and Coombs Classification", S)]
rows = [
["Type I — Immediate/Anaphylactic", "IgE cross-linking on mast cells/basophils → degranulation",
"Histamine, leukotrienes (LTC4, LTD4)", "Minutes",
"Anaphylaxis, atopic asthma, hay fever, urticaria"],
["Type II — Cytotoxic", "IgG/IgM bind cell-surface antigens → complement activation or ADCC",
"Complement, NK cells, macrophages", "Hours",
"Autoimmune haemolytic anaemia, Goodpasture, haemolytic disease of newborn"],
["Type III — Immune Complex", "Ag-Ab complexes deposit in vessels/tissues → complement + neutrophil activation",
"Complement, neutrophils, PMNs", "Hours–days",
"Serum sickness, SLE, post-streptococcal GN, Arthus reaction"],
["Type IV — Delayed (Cell-Mediated)", "CD4+ Th1 cells activate macrophages; CD8+ CTLs kill target cells",
"IFN-γ, TNF, perforin/granzymes", "24–72 hours",
"Contact dermatitis, TB (Mantoux test), graft rejection, Type 1 diabetes"],
]
el += [make_table(
["Type", "Mechanism", "Effectors", "Timing", "Examples"],
rows, S, [3.5*cm, 5.5*cm, 3*cm, 2*cm, 4*cm]
), SP(6)]
el += [H2("7.2 Key Autoimmune Diseases", S)]
rows = [
["Systemic Lupus Erythematosus (SLE)",
"Anti-dsDNA, anti-Sm (diagnostic); Type III hypersensitivity dominant. "
"Wire-loop glomerulonephritis; butterfly rash; Libman-Sacks endocarditis; cytopenias",
"Anti-dsDNA, ANA, anti-Sm, anti-Ro/La"],
["Rheumatoid Arthritis",
"Anti-CCP antibodies; RF. Pannus formation → erosion of articular cartilage. "
"Rheumatoid nodules; extra-articular vasculitis; Felty's syndrome",
"RF, anti-CCP"],
["Sjögren's Syndrome",
"Lymphocytic destruction of salivary and lacrimal glands → xerostomia, xerophthalmia. "
"Risk of NHL (MALT lymphoma)",
"Anti-Ro (SS-A), anti-La (SS-B)"],
["Goodpasture Syndrome",
"Anti-GBM antibodies (Type II); linear IgG deposition on GBM. "
"Pulmonary haemorrhage + rapidly progressive GN",
"Anti-GBM, p-ANCA (some)"],
["Myasthenia Gravis",
"Anti-AChR antibodies block neuromuscular transmission → fatigable weakness. "
"Thymoma in 15%. Anti-MuSK in seronegative cases",
"Anti-AChR"],
["Hashimoto's Thyroiditis",
"Lymphocytic thyroiditis; Hürthle cell change; germinal centres in thyroid. "
"Most common cause of hypothyroidism in iodine-replete regions",
"Anti-TPO, anti-thyroglobulin"],
["Type 1 Diabetes (T1DM)",
"CD8+ CTL destruction of β-islet cells; HLA-DR3/DR4 association. "
"Insulitis on histology",
"Anti-islet cell, anti-GAD, anti-insulin"],
]
el += [make_table(["Disease", "Pathology & Features", "Key Antibodies"], rows, S, [4*cm, 8*cm, 4*cm]), SP(6)]
el += [H2("7.3 Transplant Rejection", S)]
rows = [
["Hyperacute", "Minutes to hours", "Pre-formed donor-specific antibodies → complement activation",
"Immediate thrombosis; graft removed intraoperatively"],
["Acute (humoral)", "Days–weeks", "Donor-specific antibodies formed post-transplant",
"C4d deposition on biopsy; arteritis"],
["Acute (cellular)", "Days–weeks", "CD4+ and CD8+ T cells recognise alloantigen (direct/indirect)",
"Mononuclear interstitial infiltrate; tubulitis (kidney)"],
["Chronic", "Months–years", "Combined antibody and T-cell mediated; chronic ischaemia",
"Intimal fibrosis of vessels ('onion-skin'); interstitial fibrosis; organ dysfunction"],
]
el += [make_table(["Type", "Timing", "Mechanism", "Pathology"], rows, S, [3*cm, 3*cm, 5.5*cm, 4.5*cm]), SP(8)]
return el
# ─── Section 8: Pathologic Calcification & Ageing ────────────────────────────
def section_misc(S):
el = []
el += [H1("PART VI: DEPOSITIONS, AGEING & GENETICS", S), SP(10)]
el += [H1("8. Pathologic Depositions & Calcification", S), SP(6)]
el += [H2("8.1 Intracellular Accumulations", S)]
rows = [
["Lipids (Steatosis)", "Fatty liver (alcohol, obesity, DM, drugs); foam cells in atherosclerosis",
"Membrane whorls (myelin figures); lipid vacuoles on Oil Red O stain"],
["Proteins", "Russell bodies (immunoglobulin in plasma cells); Mallory-Denk bodies (keratin in alcoholic hepatitis); "
"α1-antitrypsin globules in liver",
"Pink hyaline inclusions on H&E"],
["Glycogen", "Glycogen storage diseases (Pompe, Gaucher, Niemann-Pick); diabetic hepatocytes",
"Clear vacuoles; PAS-positive"],
["Lipofuscin", "Wear-and-tear ageing pigment; not harmful; lysosomal residue",
"Perinuclear golden-brown granules; older patients"],
["Melanin", "Normal in melanocytes; excess in Addison's disease, melanoma",
"Brown-black pigment"],
["Haemosiderin", "Iron overload (haemochromatosis, repeated transfusions, local haemorrhage)",
"Golden-brown granules; Perls' Prussian Blue positive"],
["Bilirubin", "Cholestasis; jaundice",
"Yellow-green pigment in hepatocytes and bile canaliculi"],
["Carbon (Anthracosis)", "Coal dust inhalation; tattoo pigment",
"Black pigment in macrophages; benign; marks draining lymph nodes"],
]
el += [make_table(["Substance", "Context", "Histologic Features"], rows, S, [3*cm, 7.5*cm, 5.5*cm]), SP(4)]
el += [H2("8.2 Pathologic Calcification", S)]
rows = [
["Dystrophic", "Calcium deposits in dead or damaged tissue; serum calcium NORMAL",
"Atherosclerotic plaques, heart valves, tuberculous foci, fat necrosis, mature tumours"],
["Metastatic", "Calcium deposits in normal tissue; serum calcium ELEVATED (hypercalcaemia)",
"Kidneys (nephrocalcinosis), lungs, gastric mucosa, blood vessels, cornea"],
]
el += [make_table(["Type", "Mechanism/Context", "Sites"], rows, S, [3*cm, 7*cm, 6*cm]), SP(6)]
el += [H2("8.3 Cellular Ageing", S)]
el += [P("Ageing reflects accumulated cellular damage. Key mechanisms:", S)]
mechanisms = [
("Telomere Shortening", "Each cell division shortens telomeres (TTAGGG repeats). "
"When critically short, cells enter replicative senescence (p21-mediated) or apoptosis. "
"Cancer cells re-activate telomerase (hTERT) to achieve immortality."),
("Oxidative Damage Accumulation", "ROS from mitochondrial leak accumulate in DNA, lipids, and proteins "
"over decades. Mitochondrial DNA especially vulnerable (no histones, limited repair)."),
("Epigenetic Alterations", "Progressive loss of DNA methylation marks and histone acetylation "
"changes alter gene expression patterns, activating pro-ageing genes."),
("Decreased DNA Repair", "Fidelity of mismatch repair, nucleotide excision repair, and "
"NHEJ declines with age — increasing mutational burden."),
("Inflammaging", "Chronic low-grade sterile inflammation driven by senescent cells that "
"secrete a SASP (Senescence-Associated Secretory Phenotype): IL-6, IL-8, TNF, MMPs."),
("Protein Homeostasis (Proteostasis) Failure", "Reduced proteasome/autophagy efficiency → accumulation of "
"misfolded proteins → ER stress → apoptosis."),
]
for name, desc in mechanisms:
el += [H3(name, S), P(desc, S)]
el += [SP(8)]
return el
# ─── Section 9: Key Pathology Mnemonics & Quick Reference ────────────────────
def section_quick_ref(S):
el = []
el += [H1("PART VII: QUICK REFERENCE", S), SP(10)]
el += [H1("9. Mnemonics, Buzzwords & High-Yield Facts", S), SP(6)]
el += [H2("9.1 Pathology Buzzwords", S)]
rows = [
["Bread-and-butter pericardium", "Fibrinous pericarditis"],
["Cheese-like appearance", "Caseous necrosis (TB)"],
["Wire-loop glomeruli", "SLE nephritis (WHO Class III/IV)"],
["Signet ring cells", "Gastric adenocarcinoma (mucus pushes nucleus to periphery)"],
["Psammoma bodies", "Papillary thyroid carcinoma, serous ovarian carcinoma, meningioma, mesothelioma"],
["Aschoff bodies", "Rheumatic fever (macrophage nodules in myocardium)"],
["Reed-Sternberg cells (owl-eye)", "Hodgkin lymphoma (CD15+, CD30+)"],
["Lewy bodies", "Parkinson's disease (α-synuclein aggregates)"],
["Negri bodies", "Rabies (neuronal cytoplasmic inclusions)"],
["Mallory-Denk bodies", "Alcoholic hepatitis (keratin aggregates)"],
["Councilman bodies (acidophilic bodies)", "Viral hepatitis (apoptotic hepatocytes)"],
["Rokitansky-Aschoff sinuses", "Chronic cholecystitis"],
["Curschmann spirals + Charcot-Leyden crystals", "Bronchial asthma"],
["Ivory vertebra", "Osteoblastic metastasis (prostate cancer) or Paget's disease"],
["Call-Exner bodies", "Granulosa cell tumour (ovary)"],
["Schiller-Duval bodies", "Yolk sac tumour (AFP-secreting)"],
["Reinke crystals", "Leydig cell tumour (testis)"],
["Verocay bodies", "Schwannoma"],
]
el += [make_table(["Buzzword/Sign", "Diagnosis"], rows, S, [7*cm, 9*cm]), SP(6)]
el += [H2("9.2 Important Stains in Histopathology", S)]
rows = [
["H&E (Haematoxylin & Eosin)", "Routine stain. Nuclei: blue; cytoplasm, collagen: pink"],
["PAS (Periodic Acid-Schiff)", "Glycogen, glycoproteins, fungi (Candida, Histoplasma)"],
["Perls' Prussian Blue", "Haemosiderin/iron (sideroblastic anaemia, haemochromatosis)"],
["Congo Red", "Amyloid (apple-green birefringence under polarised light)"],
["Ziehl-Neelsen (ZN)", "Acid-fast bacilli (TB, leprosy, Nocardia)"],
["India Ink", "Cryptococcus neoformans (capsule)"],
["Silver stain (Gomori methenamine)", "Fungi, PCP (Pneumocystis), reticulin fibres"],
["Alcian Blue", "Acid mucopolysaccharides, mucus"],
["Masson's Trichrome", "Collagen (blue/green) vs muscle (red) — fibrosis"],
["Oil Red O", "Lipids/fat (frozen sections only — lipids dissolve in paraffin processing)"],
["Giemsa", "H. pylori, Leishmania, malaria, lymphoma cells"],
["Toluidine Blue", "Mast cell granules"],
["Luxol Fast Blue (LFB)", "Myelin (demyelination in MS)"],
["Fontana-Masson", "Melanin"],
]
el += [make_table(["Stain", "Use / What it Demonstrates"], rows, S, [5.5*cm, 10.5*cm]), SP(6)]
el += [H2("9.3 p53 — The Guardian of the Genome", S)]
el += [P("TP53 is mutated in ~50% of all human cancers — the most frequently mutated gene in human neoplasia.", S)]
el += [B("Normal function: senses DNA damage → activates p21 (CDK inhibitor) → G1 arrest → DNA repair. "
"If repair fails → BAX/PUMA upregulation → apoptosis", S)]
el += [B("Mutant p53 (gain-of-function): acts as oncogene; accumulates in nucleus (IHC positive)", S)]
el += [B("Germline mutation: Li-Fraumeni syndrome (LFS) — multiple primary malignancies from childhood", S)]
el += [B("HPV E6 protein binds wild-type p53 and targets it for ubiquitin-mediated degradation", S)]
el += [SP(4)]
el += [H2("9.4 High-Yield Associations", S)]
rows = [
["Asbestos exposure", "Mesothelioma (pleura), lung carcinoma, asbestosis (lower lobes)"],
["Vinyl chloride", "Hepatic angiosarcoma"],
["Aflatoxin B1", "Hepatocellular carcinoma (p53 codon 249 mutation)"],
["Benzene", "Aplastic anaemia, AML"],
["Cyclophosphamide", "Haemorrhagic cystitis, transitional cell carcinoma of bladder"],
["Diethylstilboestrol (DES)", "Clear cell adenocarcinoma of vagina in offspring"],
["Tobacco smoke", "Oral, laryngeal, lung, oesophageal, bladder, renal, pancreatic cancer"],
["Obesity/NASH", "Hepatocellular carcinoma (via NASH → cirrhosis)"],
["Ulcerative colitis", "Colorectal carcinoma (dysplasia-carcinoma sequence; after 10 years)"],
["Actinic (solar) keratosis", "Squamous cell carcinoma of skin"],
["Villous adenoma (colon)", "High malignant potential; associated with hypokalaemia"],
["Cirrhosis (any cause)", "Hepatocellular carcinoma"],
]
el += [make_table(["Risk Factor / Precursor", "Associated Malignancy"], rows, S, [6.5*cm, 9.5*cm]), SP(8)]
return el
# ─── Assemble document ───────────────────────────────────────────────────────
def build_pdf():
doc = PathologyDoc(
OUTPUT,
pagesize=A4,
leftMargin=1.5*cm, rightMargin=1.5*cm,
topMargin=1.8*cm, bottomMargin=1.8*cm,
title="Comprehensive Pathology Reference",
author="Orris Medical AI",
subject="Pathology"
)
S = make_styles()
elements = []
elements += cover_page(S)
elements += section_intro(S)
elements += [PageBreak()]
elements += section_cell_injury(S)
elements += [PageBreak()]
elements += section_inflammation(S)
elements += [PageBreak()]
elements += section_repair(S)
elements += [PageBreak()]
elements += section_neoplasia(S)
elements += [PageBreak()]
elements += section_haemodynamics(S)
elements += [PageBreak()]
elements += section_immunopath(S)
elements += [PageBreak()]
elements += section_misc(S)
elements += [PageBreak()]
elements += section_quick_ref(S)
doc.build(elements)
print(f"PDF created: {OUTPUT}")
if __name__ == "__main__":
build_pdf()