Make a exam oriented perfect and good notes on the given topics from the given source

Asking for Preferences
Asking for Preferences
Reading File
Running Command

python3 -c " import pdfplumber pdf_path = '/home/daytona/workspace/attachments/79f94596-41c5-44ca-8233-85c0c0d7541a/Tara Shanbhag Pharmacology pdf Medicalstudyzone.com (1)_11zon_11zon (1)(pdfgear.com).pdf' with pdfplumber.open(pdf_path) as pdf: print(f'Total pages: {len(pdf.pages)}') # Print first 5 pages to understand structure for i in range(min(5, len(pdf.pages))): text = pdf.pages[i].extract_text() print(f'--- PAGE {i+1} ---') print(text[:2000] if text else '[No text]') print() "

Running Command

python3 -c " from pypdf import PdfReader pdf_path = '/home/daytona/workspace/attachments/79f94596-41c5-44ca-8233-85c0c0d7541a/Tara Shanbhag Pharmacology pdf Medicalstudyzone.com (1)_11zon_11zon (1)(pdfgear.com).pdf' reader = PdfReader(pdf_path) print('Total pages:', len(reader.pages)) # Read first 3 pages for i in range(3): text = reader.pages[i].extract_text() print(f'--- PAGE {i+1} ---') print(text[:1500] if text else '[empty]') " 2>&1 | head -100

Running Command

python3 -c " from pypdf import PdfReader pdf_path = '/home/daytona/workspace/attachments/79f94596-41c5-44ca-8233-85c0c0d7541a/Tara Shanbhag Pharmacology pdf Medicalstudyzone.com (1)_11zon_11zon (1)(pdfgear.com).pdf' reader = PdfReader(pdf_path) # Try pages 5-20 to find where text starts for i in range(4, 25): text = reader.pages[i].extract_text() if text and len(text.strip()) > 50: print(f'--- PAGE {i+1} has text ---') print(text[:800]) print() break else: print(f'Page {i+1}: empty or sparse') " 2>&1

Running Command

python3 -c " from pypdf import PdfReader pdf_path = '/home/daytona/workspace/attachments/79f94596-41c5-44ca-8233-85c0c0d7541a/Tara Shanbhag Pharmacology pdf Medicalstudyzone.com (1)_11zon_11zon (1)(pdfgear.com).pdf' reader = PdfReader(pdf_path) # Check if pages have images page = reader.pages[5] print('Images:', len(page.images) if hasattr(page, 'images') else 'N/A') print('Resources:', list(page.get('/Resources', {}).keys()) if page.get('/Resources') else 'none') # Also check raw text raw = page.extract_text(extraction_mode='raw') print('Raw text len:', len(raw) if raw else 0) print('Raw sample:', raw[:200] if raw else 'empty') " 2>&1

Running Command

python3 -c " import subprocess # Check available OCR tools result = subprocess.run(['which', 'tesseract'], capture_output=True, text=True) print('tesseract:', result.stdout.strip()) result2 = subprocess.run(['which', 'pdftotext'], capture_output=True, text=True) print('pdftotext:', result2.stdout.strip()) result3 = subprocess.run(['pdftotext', '--version'], capture_output=True, text=True) print('pdftotext version:', result3.stderr.strip()) " 2>&1

Running Command

PDF_PATH='/home/daytona/workspace/attachments/79f94596-41c5-44ca-8233-85c0c0d7541a/Tara Shanbhag Pharmacology pdf Medicalstudyzone.com (1)_11zon_11zon (1)(pdfgear.com).pdf' # Try pdftotext first (handles some image PDFs with embedded text layers) pdftotext "$PDF_PATH" /tmp/tara_text.txt 2>&1 echo "Exit: $?" wc -c /tmp/tara_text.txt head -100 /tmp/tara_text.txt

Running Command

python3 -c " # Check if pdf2image is available import importlib for pkg in ['pdf2image', 'pytesseract', 'PIL']: try: m = importlib.import_module(pkg) print(f'{pkg}: OK') except ImportError as e: print(f'{pkg}: MISSING - {e}') " 2>&1

Running Command

python3 << 'EOF' import pdf2image import pytesseract pdf_path = '/home/daytona/workspace/attachments/79f94596-41c5-44ca-8233-85c0c0d7541a/Tara Shanbhag Pharmacology pdf Medicalstudyzone.com (1)_11zon_11zon (1)(pdfgear.com).pdf' # Convert pages 1-5 at low DPI to find Table of Contents / General Pharmacology section print("Converting pages 1-5...") images = pdf2image.convert_from_path(pdf_path, dpi=100, first_page=1, last_page=5) print(f"Got {len(images)} images") for i, img in enumerate(images): text = pytesseract.image_to_string(img) print(f"\n=== PAGE {i+1} ===") print(text[:1000]) EOF

Running Command

python3 << 'EOF' import pdf2image import pytesseract pdf_path = '/home/daytona/workspace/attachments/79f94596-41c5-44ca-8233-85c0c0d7541a/Tara Shanbhag Pharmacology pdf Medicalstudyzone.com (1)_11zon_11zon (1)(pdfgear.com).pdf' # Get TOC - typically pages 6-15 print("Converting pages 6-15 for TOC...") images = pdf2image.convert_from_path(pdf_path, dpi=120, first_page=6, last_page=15) for i, img in enumerate(images): text = pytesseract.image_to_string(img) print(f"\n=== PAGE {i+6} ===") print(text[:1500]) EOF

Running Command

python3 << 'EOF' import pdf2image import pytesseract import os pdf_path = '/home/daytona/workspace/attachments/79f94596-41c5-44ca-8233-85c0c0d7541a/Tara Shanbhag Pharmacology pdf Medicalstudyzone.com (1)_11zon_11zon (1)(pdfgear.com).pdf' os.makedirs('/tmp/gp_ocr', exist_ok=True) # General Pharmacology is Chapter 1, roughly pages 14-80 based on TOC # Let's extract pages 14-50 first print("Converting pages 14-40...") images = pdf2image.convert_from_path(pdf_path, dpi=150, first_page=14, last_page=40) print(f"Got {len(images)} images") all_text = {} for i, img in enumerate(images): page_num = i + 14 text = pytesseract.image_to_string(img, config='--oem 3 --psm 6') all_text[page_num] = text print(f"Page {page_num}: {len(text)} chars") # Save import json with open('/tmp/gp_ocr/pages_14_40.json', 'w') as f: json.dump(all_text, f) print("Saved to /tmp/gp_ocr/pages_14_40.json") EOF

Running Command

python3 << 'EOF' import pdf2image import pytesseract import json pdf_path = '/home/daytona/workspace/attachments/79f94596-41c5-44ca-8233-85c0c0d7541a/Tara Shanbhag Pharmacology pdf Medicalstudyzone.com (1)_11zon_11zon (1)(pdfgear.com).pdf' # Continue pages 41-80 (rest of Chapter 1 and beginning of Chapter 2 - we stop when we hit Chapter 2) print("Converting pages 41-80...") images = pdf2image.convert_from_path(pdf_path, dpi=150, first_page=41, last_page=80) print(f"Got {len(images)} images") all_text = {} for i, img in enumerate(images): page_num = i + 41 text = pytesseract.image_to_string(img, config='--oem 3 --psm 6') all_text[page_num] = text # Check if we've hit Chapter 2 if 'Autonomic' in text and 'Chapter' in text and page_num > 60: print(f" ** Possible Chapter 2 start at page {page_num}") with open('/tmp/gp_ocr/pages_41_80.json', 'w') as f: json.dump(all_text, f) print("Done. Saved.") EOF

Running Command

python3 << 'EOF' import json # Load both files and print key sections to understand content scope with open('/tmp/gp_ocr/pages_14_40.json') as f: d1 = json.load(f) with open('/tmp/gp_ocr/pages_41_80.json') as f: d2 = json.load(f) all_pages = {**d1, **d2} # Find where Chapter 2 starts (Autonomic Nervous System) for pg in range(30, 81): t = all_pages.get(str(pg), all_pages.get(pg, '')) if 'Autonomic' in t or 'AUTONOMIC' in t: print(f"Page {pg} mentions Autonomic:") print(t[:300]) print("---") EOF

Running Command

python3 << 'EOF' import json with open('/tmp/gp_ocr/pages_14_40.json') as f: d1 = json.load(f) with open('/tmp/gp_ocr/pages_41_80.json') as f: d2 = json.load(f) all_pages = {**d1, **d2} # Compile General Pharmacology: pages 14-64 full_text = [] for pg in range(14, 65): t = all_pages.get(str(pg), all_pages.get(pg, '')) full_text.append(f"\n\n=== PAGE {pg} ===\n{t}") combined = '\n'.join(full_text) with open('/tmp/gp_ocr/general_pharma_full.txt', 'w') as f: f.write(combined) print(f"Total chars: {len(combined)}") print("First 3000 chars:") print(combined[:3000]) EOF

Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Running Command

mkdir -p /home/daytona/workspace/general-pharmacology-notes && ls /home/daytona/workspace/general-pharmacology-notes/

Make a notes

Writing File

~/general-pharmacology-notes/gen_pharma_notes.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_LEFT, TA_CENTER, TA_JUSTIFY
from reportlab.platypus import ListFlowable, ListItem

OUTPUT = "/home/daytona/workspace/general-pharmacology-notes/General_Pharmacology_Notes.pdf"

# ── Colour palette ──────────────────────────────────────────────────
C_DARK   = colors.HexColor("#1a237e")   # deep navy – chapter / section
C_MED    = colors.HexColor("#283593")   # mid-blue  – sub-heading
C_LIGHT  = colors.HexColor("#e8eaf6")   # very light lavender – box bg
C_BOX    = colors.HexColor("#c5cae9")   # box border
C_ACCENT = colors.HexColor("#e53935")   # red – mnemonics / key points
C_GOLD   = colors.HexColor("#f57f17")   # amber – exam tips
C_GREEN  = colors.HexColor("#1b5e20")   # green – examples
C_GREY   = colors.HexColor("#424242")   # body text
C_TABLE1 = colors.HexColor("#e3f2fd")   # table row 1
C_TABLE2 = colors.HexColor("#ffffff")   # table row 2
C_THEAD  = colors.HexColor("#1565c0")   # table header

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

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

TITLE = S("TITLE",
    fontName="Helvetica-Bold", fontSize=28, textColor=colors.white,
    alignment=TA_CENTER, spaceAfter=6)

SUBTITLE = S("SUBTITLE",
    fontName="Helvetica", fontSize=13, textColor=colors.HexColor("#bbdefb"),
    alignment=TA_CENTER, spaceAfter=4)

CH_HEAD = S("CH_HEAD",
    fontName="Helvetica-Bold", fontSize=16, textColor=colors.white,
    alignment=TA_LEFT, spaceBefore=10, spaceAfter=6,
    leftIndent=4)

SEC = S("SEC",
    fontName="Helvetica-Bold", fontSize=12, textColor=C_DARK,
    spaceBefore=10, spaceAfter=4, borderPad=2)

SUBSEC = S("SUBSEC",
    fontName="Helvetica-Bold", fontSize=10.5, textColor=C_MED,
    spaceBefore=7, spaceAfter=3)

BODY = S("BODY",
    fontName="Helvetica", fontSize=9.5, textColor=C_GREY,
    leading=14, spaceAfter=3, alignment=TA_JUSTIFY)

BULLET = S("BULLET",
    fontName="Helvetica", fontSize=9.5, textColor=C_GREY,
    leading=13, leftIndent=14, spaceAfter=2)

BULLET2 = S("BULLET2",
    fontName="Helvetica", fontSize=9, textColor=C_GREY,
    leading=12, leftIndent=26, spaceAfter=1)

KEY = S("KEY",
    fontName="Helvetica-Bold", fontSize=9.5, textColor=C_ACCENT,
    leading=13, spaceAfter=2)

EX = S("EX",
    fontName="Helvetica-Oblique", fontSize=9, textColor=C_GREEN,
    leading=12, leftIndent=14, spaceAfter=2)

TIP = S("TIP",
    fontName="Helvetica-Bold", fontSize=9.5, textColor=C_GOLD,
    leading=13, spaceAfter=2)

MNEM = S("MNEM",
    fontName="Helvetica-Bold", fontSize=10, textColor=C_ACCENT,
    alignment=TA_CENTER, spaceAfter=4)

TH = S("TH",
    fontName="Helvetica-Bold", fontSize=9, textColor=colors.white,
    alignment=TA_CENTER, leading=11)

TC = S("TC",
    fontName="Helvetica", fontSize=8.5, textColor=C_GREY,
    alignment=TA_LEFT, leading=11)

TCB = S("TCB",
    fontName="Helvetica-Bold", fontSize=8.5, textColor=C_DARK,
    alignment=TA_LEFT, leading=11)

# ── Helpers ──────────────────────────────────────────────────────────

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

def sp(h=4):
    return Spacer(1, h)

def p(text, style=BODY):
    return Paragraph(text, style)

def b(text, style=BULLET):
    return Paragraph(f"• {text}", style)

def b2(text, style=BULLET2):
    return Paragraph(f"– {text}", style)

def sec(text):
    return p(text, SEC)

def subsec(text):
    return p(text, SUBSEC)

def key(text):
    return p(f"★ {text}", KEY)

def tip(text):
    return p(f"🎯 EXAM TIP: {text}", TIP)

def ex(text):
    return p(f"e.g. {text}", EX)

def mnem(text):
    return p(text, MNEM)

def section_header(title):
    """Blue bar section header."""
    data = [[Paragraph(title, CH_HEAD)]]
    t = Table(data, colWidths=[17*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), C_DARK),
        ('ROUNDEDCORNERS', [4, 4, 4, 4]),
        ('TOPPADDING',  (0,0), (-1,-1), 7),
        ('BOTTOMPADDING', (0,0), (-1,-1), 7),
        ('LEFTPADDING', (0,0), (-1,-1), 10),
    ]))
    return t

def info_box(items, title=None, bg=C_LIGHT, border=C_BOX):
    """Coloured information box."""
    content = []
    if title:
        content.append(Paragraph(f"<b>{title}</b>", S("bx_title",
            fontName="Helvetica-Bold", fontSize=9.5, textColor=C_DARK, leading=13)))
    for item in items:
        content.append(Paragraph(f"• {item}", S("bx_body",
            fontName="Helvetica", fontSize=9, textColor=C_GREY, leading=13, leftIndent=6)))
    data = [[content]]
    t = Table(data, colWidths=[17*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), bg),
        ('BOX', (0,0), (-1,-1), 1, border),
        ('TOPPADDING',  (0,0), (-1,-1), 8),
        ('BOTTOMPADDING', (0,0), (-1,-1), 8),
        ('LEFTPADDING', (0,0), (-1,-1), 10),
        ('RIGHTPADDING', (0,0), (-1,-1), 10),
    ]))
    return t

def make_table(headers, rows, col_widths=None):
    if col_widths is None:
        col_widths = [17*cm / len(headers)] * len(headers)
    header_row = [Paragraph(h, TH) for h in headers]
    data = [header_row]
    for i, row in enumerate(rows):
        style = TC if i % 2 == 1 else TC
        data.append([Paragraph(str(cell), TC) for cell in row])
    t = Table(data, colWidths=col_widths)
    style = [
        ('BACKGROUND', (0,0), (-1,0), C_THEAD),
        ('TEXTCOLOR', (0,0), (-1,0), colors.white),
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor("#90a4ae")),
        ('TOPPADDING', (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
        ('ALIGN', (0,0), (-1,-1), 'LEFT'),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
    ]
    for i in range(1, len(rows)+1):
        bg = C_TABLE1 if i % 2 == 1 else C_TABLE2
        style.append(('BACKGROUND', (0,i), (-1,i), bg))
    t.setStyle(TableStyle(style))
    return t

# ════════════════════════════════════════════════════════════════════
#  BUILD DOCUMENT
# ════════════════════════════════════════════════════════════════════
doc = SimpleDocTemplate(OUTPUT, pagesize=A4,
    leftMargin=2*cm, rightMargin=2*cm,
    topMargin=2.2*cm, bottomMargin=2.2*cm,
    title="General Pharmacology – Exam Notes",
    author="Tara Shanbhag Pharmacology")

story = []

# ─── COVER PAGE ────────────────────────────────────────────────────
cover_bg = Table([[""]], colWidths=[17*cm], rowHeights=[4*cm])
cover_bg.setStyle(TableStyle([('BACKGROUND', (0,0), (-1,-1), C_DARK)]))
story.append(cover_bg)
story.append(sp(-112))   # overlap

story.append(sp(14))
story.append(p("GENERAL PHARMACOLOGY", S("cvt",
    fontName="Helvetica-Bold", fontSize=30, textColor=colors.white,
    alignment=TA_CENTER)))
story.append(p("Exam-Oriented Notes", S("cvs",
    fontName="Helvetica", fontSize=14, textColor=colors.HexColor("#bbdefb"),
    alignment=TA_CENTER, spaceAfter=10)))
story.append(sp(50))

story.append(p("Source: Tara V. Shanbhag & Smita Shenoy – Pharmacology for Medical Graduates, 3rd Edition",
    S("src", fontName="Helvetica-Oblique", fontSize=9, textColor=C_GREY,
      alignment=TA_CENTER)))
story.append(hr(C_DARK, 2))
story.append(sp(8))

# ─── CHAPTER OUTLINE ───────────────────────────────────────────────
toc_items = [
    "1. Definitions & Drug Nomenclature",
    "2. Sources of Drug Information",
    "3. Routes of Drug Administration",
    "4. Pharmacokinetics: ADME",
    "5. Pharmacodynamics",
    "6. Factors Modifying Drug Action",
    "7. Drug Interactions",
    "8. Rational Use of Medicines & ADRs",
    "9. Treatment of Poisoning",
    "10. New Drug Development & Clinical Trials",
]
story.append(sec("CHAPTER CONTENTS"))
for item in toc_items:
    story.append(b(item))
story.append(sp(6))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 1 – DEFINITIONS
# ════════════════════════════════════════════════════════════════════
story.append(section_header("1. DEFINITIONS & DRUG NOMENCLATURE"))
story.append(sp(6))

defs = [
    ("<b>Pharmacology</b>", "Science that deals with the effects of drugs on living organisms."),
    ("<b>Drug (WHO)</b>", "Any substance or product used or intended to modify/explore physiological systems or pathological states for the benefit of the recipient."),
    ("<b>Pharmacokinetics</b>", "What the BODY does to the DRUG – Absorption, Distribution, Metabolism, Excretion (ADME)."),
    ("<b>Pharmacodynamics</b>", "What the DRUG does to the BODY – mechanism of action, pharmacological effects, adverse effects."),
    ("<b>Pharmacy</b>", "Branch dealing with preparation, preservation, compounding and utilisation of drugs."),
    ("<b>Chemotherapy</b>", "Treatment of infectious diseases/cancer with chemicals that cause selective damage to the infecting organism/cancer cell."),
    ("<b>Toxicology</b>", "Study of poisons: their detection, prevention and treatment of poisoning."),
    ("<b>Clinical Pharmacology</b>", "Systematic study of drugs in humans (healthy volunteers + patients); includes PK, PD, safety, efficacy by comparative clinical trials."),
    ("<b>Essential Medicines (WHO)</b>", "Medicines that satisfy the healthcare needs of the majority of the population; assured quality, available at all times, in adequate quantities and appropriate dosage forms. e.g., Iron + folic acid (pregnancy), anti-TB drugs (INH, rifampicin, pyrazinamide, ethambutol)."),
    ("<b>Orphan Drugs</b>", "Drugs for rare diseases whose development cost cannot be recovered by the company. e.g., Digoxin-specific antibody (digoxin toxicity), fomepizole (methanol poisoning)."),
    ("<b>OTC Drugs</b>", "Over-the-counter drugs sold without a doctor's prescription. e.g., Paracetamol, antacids."),
    ("<b>Prescription Drugs</b>", "Require a doctor's prescription. e.g., Antibiotics."),
]

for term, definition in defs:
    story.append(KeepTogether([
        p(term, SUBSEC),
        p(definition, BODY),
    ]))

story.append(sp(6))
story.append(subsec("Drug Nomenclature – 3 Types of Names"))
story.append(make_table(
    ["Type", "Description", "Example (Aspirin)"],
    [
        ["Chemical Name", "Denotes the chemical structure", "Acetylsalicylic acid"],
        ["Non-proprietary (Generic) Name", "Assigned by an official body (INN)", "Aspirin"],
        ["Proprietary (Brand) Name", "Name given by pharmaceutical company", "Ecosprin, Disprin"],
    ],
    [4.5*cm, 7*cm, 5.5*cm]
))

story.append(sp(8))
story.append(tip("Pharmacokinetics = ADME = Body acts on Drug; Pharmacodynamics = Drug acts on Body. This distinction is frequently asked in MCQs."))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 2 – SOURCES OF DRUG INFORMATION
# ════════════════════════════════════════════════════════════════════
story.append(section_header("2. SOURCES OF DRUG INFORMATION"))
story.append(sp(6))

story.append(p("A <b>Pharmacopoeia</b> is a book containing a list of officially approved drugs with description of their physicochemical characteristics, purity standards, identification tests and methods of storage.", BODY))
story.append(sp(4))
story.append(make_table(
    ["Pharmacopoeia", "Abbreviation"],
    [
        ["Indian Pharmacopoeia", "IP"],
        ["British Pharmacopoeia", "BP"],
        ["European Pharmacopoeia", "EP"],
        ["United States Pharmacopoeia", "USP"],
    ],
    [10*cm, 7*cm]
))
story.append(sp(6))
story.append(subsec("Other Sources"))
for s in [
    "National Formulary (NF)",
    "Martindale – The Extra Pharmacopoeia",
    "Physician's Desk Reference (PDR)",
    "AMA Drug Evaluations",
    "Textbooks and journals of pharmacology",
    "Internet databases (e.g., Medline, Cochrane, PubMed)",
    "Pharmaceutical companies via medical representatives",
]:
    story.append(b(s))

story.append(sp(6))
story.append(p("<b>Formulary:</b> Provides information about available drugs – their uses, dosage, adverse effects, contraindications, precautions, warnings and guidance on drug selection.", BODY))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 3 – ROUTES OF ADMINISTRATION
# ════════════════════════════════════════════════════════════════════
story.append(section_header("3. ROUTES OF DRUG ADMINISTRATION"))
story.append(sp(6))

story.append(subsec("A. Enteral Routes (via GI Tract)"))
story.append(sp(3))

story.append(make_table(
    ["Route", "Advantages", "Disadvantages", "Examples"],
    [
        ["Oral (p.o.)", "Safe, convenient, economical, self-administered, no sterility needed",
         "Slow onset; 1st pass metabolism; not suitable for unconscious patients, vomiting, diarrhoea; acid/enzyme degradation",
         "Tablets, capsules, syrups"],
        ["Sublingual (s.l.)", "Rapid absorption; bypasses 1st pass; useful in emergency",
         "Not suitable for large doses; bitter taste",
         "GTN (angina), Buprenorphine"],
        ["Rectal", "Useful when oral route not possible; avoids 1st pass partially",
         "Erratic absorption; local irritation",
         "Indomethacin suppository; Diazepam enema (status epilepticus in children)"],
    ],
    [2.5*cm, 4.5*cm, 5*cm, 5*cm]
))
story.append(sp(6))

story.append(subsec("B. Parenteral Routes (non-GI)"))
story.append(sp(3))
story.append(info_box([
    "Faster onset – suitable for emergencies",
    "Useful in unconscious, uncooperative, or unreliable patients",
    "Suitable for drugs with high 1st-pass metabolism, drugs destroyed by digestive juices, or drugs not absorbed orally",
], title="Advantages of Parenteral Routes", bg=colors.HexColor("#e8f5e9"), border=colors.HexColor("#a5d6a7")))
story.append(sp(4))
story.append(info_box([
    "Requires aseptic conditions and sterile preparation (expensive)",
    "Requires invasive technique – painful",
    "Cannot usually be self-administered",
    "Can cause local tissue injury to nerves and vessels",
], title="Disadvantages of Parenteral Routes", bg=colors.HexColor("#fce4ec"), border=colors.HexColor("#f48fb1")))
story.append(sp(6))

story.append(make_table(
    ["Route", "Site", "Key Points", "Examples"],
    [
        ["Intradermal (i.d.)", "Layers of skin", "Painful; small volumes only", "BCG vaccine, drug sensitivity tests"],
        ["Subcutaneous (s.c.)", "Subcutaneous tissue (thigh, abdomen, arm)", "Slow absorption; not for irritant drugs; depot preparations possible", "Insulin, adrenaline"],
        ["Intramuscular (i.m.)", "Large muscles (deltoid, gluteus, vastus lateralis)", "Faster than s.c.; depot preparations possible (oily/aqueous)", "Antibiotics, vaccines, depot antipsychotics"],
        ["Intravenous (i.v.)", "Vein", "Fastest onset; 100% bioavailability; no 1st pass; suitable for large volumes & irritant drugs; cannot be recalled once given", "Emergency drugs, IV fluids"],
        ["Intra-arterial", "Artery", "Reserved for specialist use (e.g., angiography)", "Contrast agents"],
        ["Intrathecal", "Subarachnoid space", "Bypasses BBB", "Spinal anaesthesia, intrathecal MTX"],
    ],
    [2.8*cm, 3.2*cm, 5.5*cm, 5.5*cm]
))
story.append(sp(6))

story.append(subsec("C. Inhalation"))
story.append(b("Volatile liquids and gases given for systemic effects (general anaesthesia)."))
story.append(b("Aerosols/MDI given for local respiratory effects."))
story.append(b("<b>Advantages:</b> Quick onset; low dose needed; amount regulated."))
story.append(b("<b>Disadvantage:</b> Local irritation, increased secretions, bronchospasm."))
story.append(sp(4))

story.append(subsec("D. Topical / Local Routes"))
story.append(b("Skin: Ointments, creams, patches (transdermal – bypasses 1st pass). e.g., GTN patch, fentanyl patch."))
story.append(b("Eye, Ear, Nose drops – local effect."))
story.append(b("Vaginal: Pessaries."))
story.append(sp(4))
story.append(tip("Sublingual GTN and IV route have the fastest onset. The oral route has the slowest onset. 1st-pass metabolism is avoided by all parenteral, sublingual, rectal (partially), inhalation and transdermal routes."))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 4 – PHARMACOKINETICS
# ════════════════════════════════════════════════════════════════════
story.append(section_header("4. PHARMACOKINETICS (ADME)"))
story.append(sp(6))

story.append(p("Pharmacokinetics = what the body does to the drug. Derived from Greek: <i>pharmakon</i> (drug) + <i>kinetikos</i> (movement). Includes: <b>A</b>bsorption, <b>D</b>istribution, <b>M</b>etabolism, <b>E</b>xcretion.", BODY))
story.append(sp(4))

story.append(subsec("Drug Transport Across Membranes"))
story.append(p("All biological membranes are made up of a <b>lipid bilayer</b>. Drugs cross membranes by:", BODY))
story.append(sp(3))
story.append(make_table(
    ["Mechanism", "Energy Required?", "Carrier?", "Direction", "Examples"],
    [
        ["Passive Diffusion", "No", "No", "High → Low conc.", "Most lipid-soluble drugs"],
        ["Filtration", "No", "No", "Depends on pore size & mol. weight", "Small water-soluble molecules"],
        ["Active Transport", "Yes (ATP)", "Yes", "Low → High (against gradient)", "Levodopa (intestine), catecholamines into neurons"],
        ["Facilitated Diffusion", "No", "Yes", "High → Low", "Glucose into muscle cells"],
    ],
    [3.5*cm, 2.8*cm, 2*cm, 3.5*cm, 5.2*cm]
))
story.append(sp(6))

story.append(sec("4.1 ABSORPTION"))
story.append(p("<b>Absorption</b> = movement of a drug from the site of administration into the bloodstream.", BODY))
story.append(sp(3))
story.append(subsec("Factors Influencing Drug Absorption"))
story.append(b("<b>1. Physicochemical properties of the drug:</b>"))
story.append(b2("Physical state: Liquid > solid form for absorption."))
story.append(b2("Lipid solubility: Lipid-soluble, un-ionised form is better absorbed."))
story.append(b2("Particle size: Smaller particles are absorbed better (e.g., micronised griseofulvin). Large-particle anthelmintics act locally in the gut."))
story.append(b2("Disintegration time: Time for tablet/capsule to break into small particles."))
story.append(b2("Dissolution time: Time for particles to go into solution. Shorter = better absorption."))
story.append(sp(3))
story.append(b("<b>2. pH and Ionisation (Henderson-Hasselbalch equation):</b>"))
story.append(b2("Weak acids: better absorbed from stomach (acidic pH) – e.g., aspirin, barbiturates."))
story.append(b2("Weak bases: better absorbed from intestine (alkaline pH) – e.g., morphine, atropine."))
story.append(b2("Un-ionised form is lipid soluble and better absorbed; ionised form is water-soluble and poorly absorbed."))
story.append(sp(3))
story.append(b("<b>3. Blood flow to the site of absorption:</b> Increased blood flow → increased absorption."))
story.append(b("<b>4. Surface area:</b> Intestinal villi and microvilli provide large surface area, hence maximum absorption occurs in small intestine."))
story.append(b("<b>5. GI motility:</b> Increased peristalsis may reduce absorption time. Decreased motility increases contact time."))
story.append(sp(4))

story.append(subsec("Bioavailability (F)"))
story.append(p("Fraction of the administered dose that reaches systemic circulation in an <b>unchanged/active form</b>. Oral bioavailability is reduced by first-pass metabolism.", BODY))
story.append(info_box([
    "IV bioavailability = 100% (by definition)",
    "Oral bioavailability < 100% due to incomplete absorption + 1st-pass metabolism",
    "1st-pass (presystemic) metabolism: drug metabolised in gut wall / liver before reaching systemic circulation. e.g., GTN, propranolol, lidocaine, morphine have high 1st-pass metabolism.",
    "Bioavailability (F) = AUC (oral) / AUC (IV) × 100",
], title="Bioavailability Key Points"))
story.append(sp(6))

story.append(sec("4.2 DISTRIBUTION"))
story.append(p("Distribution = process by which a drug leaves the bloodstream and enters the interstitium and/or cells.", BODY))
story.append(sp(3))
story.append(subsec("Volume of Distribution (Vd)"))
story.append(p("Vd = Apparent volume in which the drug is distributed. Vd = Amount of drug in body / Plasma concentration.", BODY))
story.append(make_table(
    ["Vd", "Distribution", "Example"],
    [
        ["~4–5 L", "Confined to plasma (large molecules)", "Heparin, warfarin"],
        ["~12 L", "Plasma + extracellular fluid", "Aminoglycosides"],
        ["~40 L", "Total body water", "Ethanol"],
        [">100 L", "Extensive tissue binding", "Chloroquine, amiodarone, digoxin"],
    ],
    [2.5*cm, 7*cm, 7.5*cm]
))
story.append(sp(4))

story.append(subsec("Plasma Protein Binding"))
story.append(b("Most drugs bind reversibly to plasma proteins (mainly albumin for acidic drugs, α1-acid glycoprotein for basic drugs)."))
story.append(b("Only the FREE (unbound) drug is pharmacologically active."))
story.append(b("Drug interactions due to protein-binding displacement: e.g., warfarin displaced by aspirin → increased anticoagulant effect."))
story.append(sp(4))

story.append(subsec("Blood-Brain Barrier (BBB)"))
story.append(b("Only lipid-soluble, un-ionised drugs cross the BBB easily."))
story.append(b("Dopamine does NOT cross BBB → given as levodopa (prodrug) which crosses and converts to dopamine."))
story.append(b("In meningitis, BBB permeability increases → penicillin can now cross."))
story.append(sp(4))

story.append(subsec("Placental Transfer"))
story.append(b("Most drugs cross placenta by passive diffusion (lipid-soluble drugs)."))
story.append(b("Highly protein-bound drugs or large molecular drugs cross less."))
story.append(b("Teratogenic drugs: thalidomide, warfarin, ACE inhibitors, methotrexate, phenytoin."))
story.append(sp(6))

story.append(sec("4.3 METABOLISM (Biotransformation)"))
story.append(p("Metabolism = process by which drugs are converted to more water-soluble, polar compounds for excretion. Mainly in the <b>liver</b>. Also in lungs, kidney, gut wall, plasma.", BODY))
story.append(sp(4))

story.append(subsec("Prodrug"))
story.append(p("An inactive drug that is converted to its active form inside the body. Metabolism converts the prodrug → active metabolite.", BODY))
story.append(make_table(
    ["Prodrug", "Active Metabolite"],
    [
        ["Levodopa", "Dopamine (crosses BBB)"],
        ["Enalapril", "Enalaprilat"],
        ["Prednisone", "Prednisolone"],
        ["Codeine", "Morphine"],
        ["Cyclophosphamide", "Phosphoramide mustard (anticancer)"],
    ],
    [8.5*cm, 8.5*cm]
))
story.append(sp(4))
story.append(subsec("Uses/Advantages of Prodrugs"))
story.append(b("Improve bioavailability (e.g., levodopa for Parkinsonism)"))
story.append(b("Prolong duration of action (e.g., fluphenazine decanoate – depot antipsychotic)"))
story.append(b("Improve patient compliance and palatability"))
story.append(b("Site-specific drug delivery (e.g., methenamine → formaldehyde in acidic urine – urinary antiseptic)"))
story.append(sp(4))

story.append(subsec("Phases of Drug Metabolism"))
story.append(make_table(
    ["Phase", "Type", "Reactions", "Examples"],
    [
        ["Phase I\n(Non-synthetic)", "Catabolic", "Oxidation (most common), Reduction, Hydrolysis, Cyclization, Decyclization", "CYP450 enzymes (CYP3A4 most important; metabolises >50% drugs)"],
        ["Phase II\n(Synthetic)", "Anabolic", "Conjugation: Glucuronidation (most common), Sulfation, Acetylation, Methylation, Glycine conjugation", "Glucuronyltransferase; N-acetyltransferase"],
    ],
    [2.5*cm, 2.5*cm, 6*cm, 6*cm]
))
story.append(sp(4))

story.append(subsec("Cytochrome P450 (CYP450) System"))
story.append(b("A superfamily of microsomal enzymes mainly in hepatocytes."))
story.append(b("Named sequentially (CYP1, CYP2, CYP3…); each has subtypes e.g. CYP3A4."))
story.append(b("<b>CYP3A4</b> metabolises >50% of drugs."))
story.append(b("<b>Enzyme Inducers</b> (increase CYP activity → decrease drug levels):"))
story.append(b2("Rifampicin, Phenytoin, Phenobarbitone, Carbamazepine, Chronic alcohol, Cigarette smoke"))
story.append(b2("Mnemonic: <b>R</b>ita <b>P</b>ut <b>P</b>heny <b>C</b>arb <b>A</b>way <b>C</b>igs → RPPAC-C"))
story.append(b("<b>Enzyme Inhibitors</b> (decrease CYP activity → increase drug levels → toxicity):"))
story.append(b2("Ketoconazole, Erythromycin, Ciprofloxacin, Cimetidine, Grapefruit juice, Isoniazid, Acute alcohol"))
story.append(b2("Mnemonic: <b>KECK-GIA</b>"))
story.append(sp(4))

story.append(subsec("First-Pass (Presystemic) Metabolism"))
story.append(b("Drugs absorbed from the GI tract pass through the portal circulation to the liver before reaching systemic circulation."))
story.append(b("Drugs with HIGH first-pass metabolism: GTN, propranolol, lidocaine, morphine, aspirin."))
story.append(b("These drugs have LOW oral bioavailability."))
story.append(sp(6))

story.append(sec("4.4 EXCRETION"))
story.append(p("<b>Renal excretion</b> is the most important route.", BODY))
story.append(make_table(
    ["Route", "Mechanism", "Examples"],
    [
        ["Renal (urine)", "Glomerular filtration, Active tubular secretion, Passive tubular reabsorption",
         "Most drugs; acidic drugs excreted faster in alkaline urine (e.g., aspirin poisoning → alkalinise urine); basic drugs in acidic urine"],
        ["Biliary (bile → faeces)", "Active transport; enterohepatic recirculation prolongs drug action",
         "Rifampicin, oral contraceptives (caution with antibiotics), digoxin"],
        ["Lungs", "Exhalation of volatile substances", "General anaesthetics, ethanol (breathalyser)"],
        ["Saliva, Sweat, Tears", "Minor routes", "Rifampicin colours urine/sweat/tears orange"],
        ["Breast milk", "Passive diffusion; lipid-soluble drugs", "Caution in nursing mothers: metronidazole, lithium, chloramphenicol"],
    ],
    [2.5*cm, 6.5*cm, 8*cm]
))
story.append(sp(4))

story.append(subsec("Urinary pH Manipulation (Ion Trapping)"))
story.append(info_box([
    "Weak ACID (e.g., aspirin, phenobarbitone) poisoning → Alkalinise urine (sodium bicarbonate) → ionises drug → trapped in urine → faster excretion.",
    "Weak BASE (e.g., amphetamine, morphine) poisoning → Acidify urine (ammonium chloride) → ionises drug → trapped → faster excretion.",
], title="Ion Trapping – Exam Favourite!",
bg=colors.HexColor("#fff3e0"), border=colors.HexColor("#ffb74d")))
story.append(sp(6))

story.append(sec("4.5 KEY PHARMACOKINETIC PARAMETERS"))
story.append(make_table(
    ["Parameter", "Definition", "Formula / Notes"],
    [
        ["Half-life (t½)", "Time for plasma drug concentration to fall by 50%", "t½ = 0.693 × Vd / Cl;\nSteady state reached after 4–5 half-lives"],
        ["Clearance (Cl)", "Volume of plasma cleared of drug per unit time", "Cl = Dose / AUC;\nTotal Cl = Renal Cl + Hepatic Cl + others"],
        ["Bioavailability (F)", "Fraction of dose reaching systemic circulation", "F = AUC(oral)/AUC(IV) × 100"],
        ["Volume of Distribution (Vd)", "Apparent volume drug distributes into", "Vd = Amount of drug / Plasma conc."],
        ["Steady State (Css)", "Plasma conc. when rate in = rate out", "Reached after 4–5 half-lives of regular dosing"],
        ["Loading Dose", "Initial large dose to rapidly achieve target plasma concentration", "LD = Target Css × Vd / F;\nUsed when t½ is long (e.g., digoxin, amiodarone)"],
        ["Maintenance Dose", "Dose to maintain steady state", "MD = Target Css × Cl / F"],
    ],
    [3.5*cm, 5.5*cm, 8*cm]
))
story.append(sp(4))

story.append(subsec("Orders of Kinetics"))
story.append(make_table(
    ["Type", "Characteristics", "Clinical Example"],
    [
        ["First-Order Kinetics", "Constant FRACTION of drug eliminated per unit time; t½ is constant; most drugs follow this", "Most drugs at therapeutic doses"],
        ["Zero-Order Kinetics", "Constant AMOUNT eliminated per unit time; t½ is NOT constant; elimination enzymes are saturated", "Ethanol, phenytoin (at high doses), aspirin (at toxic doses)"],
    ],
    [3.5*cm, 7*cm, 6.5*cm]
))
story.append(sp(4))
story.append(tip("Phenytoin shows MIXED (Michaelis-Menten) kinetics – first-order at low doses, zero-order at high doses. Once plasma concentration >10 mg/L, small dose increments cause disproportionate rise in levels → Therapeutic Drug Monitoring (TDM) is essential for phenytoin."))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 5 – PHARMACODYNAMICS
# ════════════════════════════════════════════════════════════════════
story.append(section_header("5. PHARMACODYNAMICS"))
story.append(sp(6))

story.append(p("Pharmacodynamics = what the drug does to the body. Includes mechanisms of action, dose-response relationships, receptor pharmacology.", BODY))
story.append(sp(4))

story.append(sec("5.1 MECHANISMS OF DRUG ACTION"))
story.append(make_table(
    ["Mechanism", "Description", "Examples"],
    [
        ["Receptor Interaction", "Most common; drug binds receptor → response", "Adrenaline (β-receptor), Morphine (opioid receptor)"],
        ["Enzyme Inhibition", "Drug inhibits enzyme activity", "Aspirin (COX), ACE inhibitors, Neostigmine (AChE)"],
        ["Ion Channel Blockade", "Drug blocks ion channels", "Local anaesthetics (Na⁺ channel), Ca²⁺ channel blockers"],
        ["Physicochemical Action", "Drug acts by physical/chemical properties", "Antacids (neutralise HCl), Osmotic diuretics"],
        ["False substrate", "Structurally similar to natural substrate", "Methyldopa (false adrenergic transmitter)"],
        ["Gene regulation", "Drug activates nuclear receptors → gene transcription", "Corticosteroids, thyroid hormones, sex steroids"],
    ],
    [3.5*cm, 5.5*cm, 8*cm]
))
story.append(sp(6))

story.append(sec("5.2 RECEPTOR PHARMACOLOGY"))
story.append(p("Receptor: A macromolecule (usually protein) that recognises and binds a specific drug/ligand and initiates a pharmacological response.", BODY))
story.append(sp(3))
story.append(p("<b>Drug + Receptor → Drug-Receptor Complex → Response</b>", S("form",
    fontName="Helvetica-Bold", fontSize=10, textColor=C_DARK, alignment=TA_CENTER, spaceAfter=4)))
story.append(sp(3))

story.append(make_table(
    ["Term", "Definition", "Example"],
    [
        ["Affinity", "Ability of drug to bind to the receptor", "—"],
        ["Intrinsic Activity (Efficacy)", "Ability of drug to produce a response after binding", "—"],
        ["Agonist", "High affinity + HIGH intrinsic activity → full response", "Morphine (opioid), Adrenaline (adrenergic)"],
        ["Antagonist", "High affinity + ZERO intrinsic activity → blocks receptor, no response by itself", "Naloxone (opioid), Atropine (muscarinic)"],
        ["Partial Agonist", "Affinity + LOW intrinsic activity → submaximal response even at full receptor occupancy", "Pindolol (β-blocker), Buprenorphine (opioid)"],
        ["Inverse Agonist", "Affinity + intrinsic activity between 0 and −1 → effect OPPOSITE to agonist", "β-Carbolines at BZD receptors → anxiety + convulsions"],
    ],
    [3*cm, 6*cm, 8*cm]
))
story.append(sp(4))

story.append(subsec("Types of Receptor Antagonism"))
story.append(make_table(
    ["Type", "Mechanism", "Overcome by?", "Example"],
    [
        ["Competitive (Reversible)", "Binds same site as agonist; reversible; dose-response shifts RIGHT parallel", "Increasing agonist conc.", "Atropine, Naloxone, Propranolol"],
        ["Non-competitive (Irreversible)", "Binds same site as agonist; irreversible (covalent bonds); max. response reduced", "Cannot be overcome", "Phenoxybenzamine (α-receptor)"],
        ["Non-competitive (Allosteric)", "Binds DIFFERENT site; prevents agonist effect; max. response reduced", "Cannot be overcome", "Magnesium (NMDA receptor)"],
    ],
    [3*cm, 4.5*cm, 3*cm, 6.5*cm]
))
story.append(sp(4))

story.append(subsec("Receptor Families (Table)"))
story.append(make_table(
    ["Family", "Location", "Effector", "Coupling", "Examples"],
    [
        ["1. Ligand-gated ion channels\n(Ionotropic)", "Membrane", "Ion channel", "Direct", "Nicotinic ACh-R, GABA-A, Glutamate (NMDA)"],
        ["2. G protein-coupled receptors\n(Metabotropic)", "Membrane", "Enzyme or channel", "G proteins\n(Gs, Gi, Gq)", "Muscarinic, β-adrenergic, Opioid, Dopamine"],
        ["3. Kinase-linked (Enzymatic)\nreceptors", "Membrane", "Tyrosine kinase", "Direct (intrinsic enzyme)", "Insulin, EGF, Cytokine receptors"],
        ["4. Nuclear receptors\n(Intracellular)", "Intracellular", "Gene transcription (via DNA)", "Via DNA / RNA", "Steroid hormones, Thyroid hormone, Vit D"],
    ],
    [3.5*cm, 2.5*cm, 3*cm, 3.5*cm, 4.5*cm]
))
story.append(sp(4))
story.append(tip("Know all 4 receptor families with examples. G protein-coupled receptors use 2nd messengers: Gs→↑cAMP; Gi→↓cAMP; Gq→↑IP3+DAG. These are high-yield for exams."))
story.append(sp(4))

story.append(subsec("Dose-Response Relationship"))
story.append(b("<b>ED50 (Effective Dose 50):</b> Dose that produces effect in 50% of subjects."))
story.append(b("<b>LD50 (Lethal Dose 50):</b> Dose that causes death in 50% of animals."))
story.append(b("<b>Therapeutic Index (TI) = LD50 / ED50.</b> A HIGH TI = safer drug. e.g., Penicillin (very high TI) vs Digoxin, Phenytoin (low TI – narrow therapeutic window)."))
story.append(b("<b>Potency:</b> Amount of drug needed to produce a given effect. Lower ED50 = more potent."))
story.append(b("<b>Efficacy (Emax):</b> Maximum effect a drug can produce regardless of dose."))
story.append(sp(4))
story.append(info_box([
    "Potency relates to DOSE (shift left on graph = more potent).",
    "Efficacy relates to MAXIMUM EFFECT (height of the curve).",
    "A partial agonist can be MORE potent than a full agonist but has lower efficacy.",
], title="Potency vs Efficacy – Common MCQ Trap!",
bg=colors.HexColor("#fff3e0"), border=colors.HexColor("#ffb74d")))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 6 – FACTORS MODIFYING DRUG ACTION
# ════════════════════════════════════════════════════════════════════
story.append(section_header("6. FACTORS MODIFYING DRUG ACTION"))
story.append(sp(6))

story.append(p("Individuals often show <b>quantitative</b> variations in drug response (rarely qualitative). Key factors:", BODY))
story.append(sp(4))

story.append(subsec("A. Drug Factors"))
story.append(make_table(
    ["Factor", "Details"],
    [
        ["Route of administration", "Different routes give quantitative (and sometimes qualitative) variation. e.g., Morphine: oral dose 30–60 mg vs IV 5–10 mg for same analgesic effect."],
        ["Dose", "Oral morphine 30–60 mg; IV 5–10 mg. Qualitative: e.g., morphine depresses CNS systemically but stimulates on local application to cortex."],
        ["Presence of other drugs", "Synergism, potentiation, antagonism – see Drug Interactions."],
        ["Cumulation", "If elimination is slow, repeated doses lead to accumulation and toxicity. e.g., Lipid-soluble drugs: digoxin, chloroquine."],
    ],
    [3.5*cm, 13.5*cm]
))
story.append(sp(6))

story.append(subsec("B. Patient Factors"))
story.append(make_table(
    ["Factor", "Details & Examples"],
    [
        ["Age", "Neonates: Immature liver enzymes + renal function. Chloramphenicol → Grey baby syndrome (immature glucuronosyltransferase). Penicillin: 6-hourly in adults, 12-hourly in infants (renal immaturity). Elderly: Reduced renal + hepatic function → reduce dose of aminoglycosides."],
        ["Body weight", "Standard dose = mg/kg. For obese/oedematous patients, BSA-based dosing is more accurate. BSA used for anticancer drugs."],
        ["Sex", "β-blockers, diuretics, clonidine can cause decreased libido/impotence. Women are more sensitive to some drugs due to body composition differences."],
        ["Genetic factors", "Acetylation polymorphism (slow vs fast acetylators): e.g., INH – slow acetylators get toxicity; G6PD deficiency: primaquine/dapsone → haemolysis; Succinylcholine sensitivity (pseudocholinesterase deficiency)."],
        ["Disease states", "Liver disease → impaired drug metabolism; Renal disease → impaired excretion. Dose adjustment needed."],
        ["Psychological factors", "Placebo effect: Inactive substance produces a response due to the patient's belief."],
        ["Tolerance", "Decreased response to a drug after repeated administration. e.g., Morphine (analgesic tolerance), Alcohol (behavioural tolerance)."],
        ["Tachyphylaxis", "Rapidly developing tolerance after a few doses. e.g., Ephedrine, LSD, Nitrates."],
        ["Diet/Environment", "Fatty food ↑ griseofulvin absorption. Milk ↓ tetracycline absorption. Cigarette smoking induces CYP enzymes → ↑ theophylline metabolism."],
    ],
    [3*cm, 14*cm]
))
story.append(sp(4))

story.append(subsec("Dose Calculation in Children"))
story.append(make_table(
    ["Formula", "Equation"],
    [
        ["Young's formula (by age)", "Child dose = Age / (Age + 12) × Adult dose"],
        ["Dilling's formula (by age)", "Child dose = Age / 20 × Adult dose"],
        ["Clark's formula (by weight)", "Child dose = Body weight (kg) / 70 × Adult dose"],
    ],
    [5*cm, 12*cm]
))
story.append(sp(4))
story.append(tip("Grey baby syndrome (chloramphenicol in neonates) and G6PD deficiency (primaquine haemolysis) are classic exam questions under genetic factors."))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 7 – DRUG INTERACTIONS
# ════════════════════════════════════════════════════════════════════
story.append(section_header("7. DRUG INTERACTIONS"))
story.append(sp(6))

story.append(p("Drug interaction: Modification of the effect of one drug by another drug (or food) when given simultaneously or sequentially.", BODY))
story.append(sp(4))

story.append(subsec("Types of Drug Interactions"))
story.append(make_table(
    ["Type", "Definition", "Example"],
    [
        ["Pharmaceutical (In vitro)", "Physical/chemical incompatibility in the same syringe or container before administration", "Mixing thiopentone + suxamethonium (precipitate forms)"],
        ["Pharmacokinetic", "One drug alters absorption, distribution, metabolism or excretion of another", "Rifampicin induces CYP3A4 → ↓ OCP levels → contraceptive failure"],
        ["Pharmacodynamic", "One drug alters the pharmacological effect of another at the receptor/tissue level", "Synergism (trimethoprim + sulfamethoxazole); Antagonism (propranolol + salbutamol)"],
    ],
    [3.5*cm, 6.5*cm, 7*cm]
))
story.append(sp(4))

story.append(subsec("Pharmacodynamic Interactions"))
story.append(make_table(
    ["Type", "Definition", "Example"],
    [
        ["Synergism", "Two drugs with SAME action given together → effect greater than additive", "Cotrimoxazole (TMP + SMZ – sequential blockade of folate synthesis)"],
        ["Additive Effect", "Effect of two drugs together = sum of individual effects (1+1=2)", "Two antihypertensives"],
        ["Potentiation", "Drug A has no effect alone but enhances effect of drug B", "Probenecid + ampicillin (probenecid blocks renal tubular secretion of ampicillin → higher ampicillin levels)"],
        ["Antagonism", "One drug reduces/nullifies the effect of another", "Propranolol (β-blocker) antagonises salbutamol; Naloxone reverses morphine"],
    ],
    [3*cm, 5.5*cm, 8.5*cm]
))
story.append(sp(4))

story.append(subsec("Important Clinical Drug Interactions"))
story.append(make_table(
    ["Drug A", "Drug B", "Interaction & Outcome"],
    [
        ["Warfarin", "Aspirin", "Displacement from protein binding + anti-platelet → major bleeding risk"],
        ["Warfarin", "Rifampicin", "Enzyme induction → ↓ warfarin levels → clotting"],
        ["Warfarin", "Metronidazole/Fluconazole", "Enzyme inhibition → ↑ warfarin → bleeding"],
        ["MAO inhibitors", "Tyramine-rich food (cheese, wine)", "Hypertensive crisis (cheese reaction)"],
        ["MAO inhibitors", "Pethidine/SSRIs", "Serotonin syndrome: agitation, hyperpyrexia, rigidity, death"],
        ["OCP", "Rifampicin, Phenytoin, Carbamazepine", "Enzyme induction → ↓ OCP → contraceptive failure"],
        ["Digoxin", "Amiodarone/Verapamil", "↑ Digoxin levels → toxicity (bradycardia, arrhythmias)"],
        ["Tetracycline/Quinolones", "Antacids, Milk, Iron", "Chelation → ↓ absorption"],
        ["Methotrexate", "NSAIDs/Sulfonamides", "↑ Methotrexate toxicity (displacement + ↓ renal excretion)"],
        ["ACE inhibitors", "K⁺-sparing diuretics", "Hyperkalaemia"],
    ],
    [3.5*cm, 4.5*cm, 9*cm]
))
story.append(sp(4))
story.append(tip("Know enzyme inducers (rifampicin, phenytoin, carbamazepine, phenobarbitone) vs inhibitors (ketoconazole, erythromycin, cimetidine, grapefruit juice). Rifampicin is the strongest inducer – reduces OCP, warfarin, immunosuppressants."))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 8 – ADRs & RATIONAL PRESCRIBING
# ════════════════════════════════════════════════════════════════════
story.append(section_header("8. ADVERSE DRUG REACTIONS (ADRs) & RATIONAL USE OF MEDICINES"))
story.append(sp(6))

story.append(subsec("WHO Definition of ADR"))
story.append(p("Any response to a drug which is <b>noxious, unintended</b> and which occurs at doses normally used in man for prophylaxis, diagnosis, or therapy of disease, or for modification of physiological function.", BODY))
story.append(sp(4))

story.append(subsec("Classification of ADRs (Type A & B)"))
story.append(make_table(
    ["Feature", "Type A (Augmented)", "Type B (Bizarre)"],
    [
        ["Nature", "Predictable, dose-related, related to pharmacological action", "Unpredictable, NOT dose-related, NOT related to pharmacological action"],
        ["Incidence", "Common (~80% of ADRs)", "Rare"],
        ["Mortality", "Low", "High"],
        ["Examples", "Side effects, Secondary effects, Toxic effects", "Allergic reactions, Idiosyncratic reactions"],
        ["Management", "Dose reduction or drug withdrawal", "Drug withdrawal; usually cannot be prevented by dose reduction"],
    ],
    [3.5*cm, 6.75*cm, 6.75*cm]
))
story.append(sp(4))

story.append(subsec("Types of Adverse Drug Effects"))
story.append(make_table(
    ["Type", "Definition", "Example"],
    [
        ["Side effect", "Unwanted pharmacological effect at therapeutic doses", "Atropine: dry mouth, blurred vision, urinary retention (while treating bradycardia)"],
        ["Secondary effect", "Indirect consequence of primary drug action", "Broad-spectrum antibiotics → superinfection with Candida"],
        ["Toxic effect", "Result of excessive drug dose or accumulation", "Gentamicin → nephrotoxicity + ototoxicity at high doses"],
        ["Allergic reaction (Hypersensitivity)", "Immune-mediated reaction; not dose-related; requires prior sensitization", "Penicillin → anaphylaxis (Type I), serum sickness (Type III)"],
        ["Idiosyncratic reaction", "Genetically determined abnormal reaction; unusual qualitative response", "G6PD deficiency → primaquine → haemolytic anaemia; succinylcholine apnoea"],
        ["Drug dependence", "Physical or psychological need to continue the drug", "Opioids (physical), Benzodiazepines"],
        ["Drug tolerance", "Decreased response after repeated use; higher dose needed", "Opioids, alcohol, nitrates"],
        ["Tachyphylaxis", "Rapidly developing tolerance after a few doses", "Ephedrine, GTN, LSD"],
        ["Teratogenicity", "Drug causes foetal malformation in 1st trimester", "Thalidomide (phocomelia), Warfarin, ACE inhibitors, Methotrexate"],
        ["Carcinogenicity", "Drug causes cancer after long-term use", "Cyclophosphamide → bladder carcinoma; Hormone therapy → breast cancer risk"],
        ["Mutagenicity", "Drug causes DNA mutations (may or may not be carcinogenic)", "Nitrogen mustards, alkylating agents"],
        ["Superinfection", "Secondary infection due to disruption of normal flora", "Broad-spectrum antibiotics → Candidiasis, CDAD"],
    ],
    [3.5*cm, 5.5*cm, 8*cm]
))
story.append(sp(4))

story.append(subsec("Rational Use of Medicines"))
story.append(p("Rational prescribing involves administering the <b>right drug</b> in the <b>right dose</b> via the <b>right route</b> for the <b>right duration</b> at the <b>right cost</b> to the <b>right patient</b>.", BODY))
story.append(sp(3))
story.append(subsec("Irrationalities in Prescribing"))
for item in [
    "Unnecessary use of drugs (e.g., antibiotics for viral infections)",
    "Drug not prescribed as per standard treatment guidelines",
    "Incorrect use of a drug (wrong route, dose, or indication)",
    "Use of drugs of doubtful efficacy (e.g., appetite stimulants)",
    "Use of irrational combinations (e.g., ampicillin + cloxacillin for staphylococcal infections instead of cloxacillin alone)",
    "Prescribing expensive drugs when cheaper, equally effective drugs are available",
    "Polypharmacy",
]:
    story.append(b(item))
story.append(sp(3))
story.append(subsec("Hazards of Irrational Drug Use"))
story.append(b("Therapeutic failure"))
story.append(b("Increased incidence of ADRs"))
story.append(b("Emergence of drug-resistant microorganisms"))
story.append(b("Increased cost of treatment and financial burden on society"))
story.append(b("Loss of patient's faith in the doctor"))
story.append(sp(4))
story.append(subsec("Steps in Rational Prescribing"))
for step in [
    "Define the therapeutic problem",
    "Make a diagnosis",
    "Define therapeutic goals (e.g., relief of symptoms, cure)",
    "Select the appropriate drug considering efficacy, safety, cost, convenience",
    "Prescribe in proper dose and dosage form",
    "Monitor therapy and reassess",
]:
    story.append(b(step))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 9 – TREATMENT OF POISONING
# ════════════════════════════════════════════════════════════════════
story.append(section_header("9. TREATMENT OF POISONING"))
story.append(sp(6))

story.append(subsec("General Principles"))
story.append(make_table(
    ["Step", "Actions"],
    [
        ["1. Remove the poison", "Skin/eye: copious water washing. Ingested: Gastric lavage (within 1–2 hrs), Activated charcoal (universal antidote – adsorbs most poisons), Emesis (ipecac – rarely used now)"],
        ["2. Prevent absorption", "Activated charcoal 1 g/kg orally. Multiple doses for carbamazepine, phenobarbitone, quinine, theophylline."],
        ["3. Supportive measures", "Maintain airway, breathing, circulation (ABC). IV fluids, vasopressors if needed. Treat seizures, arrhythmias."],
        ["4. Enhance elimination", "Forced diuresis, urine alkalinisation (for acidic drugs), urine acidification (for basic drugs), haemodialysis (for salicylates, lithium, methanol, ethylene glycol), haemoperfusion."],
        ["5. Specific antidotes", "See table below"],
    ],
    [3.5*cm, 13.5*cm]
))
story.append(sp(4))

story.append(subsec("Specific Antidotes (High-Yield Table)"))
story.append(make_table(
    ["Poison", "Antidote"],
    [
        ["Organophosphate (OP) compounds", "Atropine (muscarinic effects) + Pralidoxime/2-PAM (reactivates AChE if given early)"],
        ["Opioids (morphine, heroin)", "Naloxone (IV/IM/SC) – competitive opioid antagonist"],
        ["Benzodiazepines", "Flumazenil (competitive BZD antagonist)"],
        ["Paracetamol (acetaminophen)", "N-acetylcysteine (NAC) – replenishes glutathione; most effective within 8–10 hrs"],
        ["Aspirin / Salicylates", "Sodium bicarbonate (alkalinise urine) + haemodialysis if severe"],
        ["Iron poisoning", "Deferoxamine (desferrioxamine)"],
        ["Warfarin overdose", "Vitamin K (phytomenadione); Fresh frozen plasma (FFP) for immediate reversal"],
        ["Heparin overdose", "Protamine sulfate (1 mg per 100 units heparin)"],
        ["Digoxin toxicity", "Digoxin-specific antibody fragments (Digibind)"],
        ["Cyanide poisoning", "Hydroxocobalamin (Cyanide antidote kit); Sodium thiosulfate + Sodium nitrite"],
        ["Methanol / Ethylene glycol poisoning", "Fomepizole (4-MP; inhibits alcohol dehydrogenase) or Ethanol; + Haemodialysis"],
        ["Carbon monoxide (CO) poisoning", "100% oxygen; Hyperbaric oxygen in severe cases"],
        ["Atropine / Anticholinergics", "Physostigmine (crosses BBB, reverses CNS effects)"],
        ["Heavy metals (Pb, As, Hg)", "Chelating agents: Dimercaprol (BAL); EDTA (lead); DMSA (oral) for lead/arsenic"],
        ["Tricyclic antidepressants (TCA)", "Sodium bicarbonate (for arrhythmias); supportive care"],
        ["Methotrexate", "Folinic acid (leucovorin) – rescue therapy"],
        ["Beta-blockers", "Glucagon (increases cAMP in myocardium)"],
    ],
    [5.5*cm, 11.5*cm]
))
story.append(sp(4))
story.append(tip("OP poisoning: Atropine for muscarinic symptoms (SLUDGE: Salivation, Lacrimation, Urination, Defaecation, GI cramps, Emesis) + Pralidoxime within 24 hrs (before ageing). Nicotinic symptoms (muscle weakness, paralysis) NOT relieved by atropine."))
story.append(sp(4))
story.append(tip("Paracetamol overdose: Hepatotoxicity (zone 3 necrosis) due to NAPQI accumulation. NAC most effective if given within 8–10 hrs. Late presenters (>15 hrs): liver transplant may be needed."))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 10 – NEW DRUG DEVELOPMENT
# ════════════════════════════════════════════════════════════════════
story.append(section_header("10. NEW DRUG DEVELOPMENT & CLINICAL TRIALS"))
story.append(sp(6))

story.append(p("A new drug is rigorously and ethically evaluated for safety and efficacy before it can be used therapeutically. This is called <b>Clinical Development</b>.", BODY))
story.append(sp(4))

story.append(subsec("Preclinical (Animal) Studies"))
story.append(make_table(
    ["Study Type", "Details"],
    [
        ["Acute Toxicity", "Two animal species, two routes; determines LD50; done in 24 hrs"],
        ["Subacute Toxicity", "Two species; determines maximum tolerated dose and target organ toxicity; drug given daily for a period proportional to human treatment duration"],
        ["Chronic Toxicity", "Two species (rodent + non-rodent); 6–12 months; monitoring as in subacute"],
        ["Special Toxicity Studies", "Carcinogenicity, Mutagenicity (Ames test), Teratogenicity; also includes effects on reproduction"],
    ],
    [4*cm, 13*cm]
))
story.append(sp(4))

story.append(subsec("Clinical Trials (4 Phases)"))
story.append(make_table(
    ["Phase", "Subjects", "Purpose", "Size"],
    [
        ["Phase I", "Healthy volunteers (20–80)", "First-in-human; pharmacokinetics, safety, maximum tolerated dose (MTD)", "Small (20–80)"],
        ["Phase II", "Patients with target disease", "Therapeutic efficacy, dose-ranging, short-term safety", "100–300"],
        ["Phase III", "Patients (multicentre, RCT)", "Confirmation of efficacy and safety vs standard therapy or placebo; get regulatory approval", "1,000–5,000"],
        ["Phase IV", "General population (post-marketing)", "Post-marketing surveillance; detect rare ADRs (pharmacovigilance); new indications, long-term safety", "Large (thousands)"],
    ],
    [1.5*cm, 4*cm, 7*cm, 2.5*cm, 2*cm]
))
story.append(sp(4))
story.append(info_box([
    "Phase I: Pharmacokinetics in humans, first-in-human safety.",
    "Phase II: Proof of concept – DOES it work in patients?",
    "Phase III: Definitive RCT – Compared with standard therapy. Basis for regulatory approval (DCGI in India, FDA in USA).",
    "Phase IV (Post-Marketing Surveillance): Detects rare ADRs (e.g., 1 in 10,000 patients). e.g., Thalidomide teratogenicity detected in post-marketing phase.",
], title="Mnemonic for Phase Purposes: Safety → Efficacy → Confirmation → Surveillance",
bg=colors.HexColor("#e8f5e9"), border=colors.HexColor("#a5d6a7")))
story.append(sp(4))

story.append(subsec("IND, NDA, and Drug Approval"))
story.append(b("<b>IND (Investigational New Drug):</b> Application filed before Phase I trials begin. Contains preclinical data."))
story.append(b("<b>NDA (New Drug Application):</b> Filed after Phase III; contains all clinical data. Reviewed by FDA/DCGI."))
story.append(b("<b>DCGI:</b> Drug Controller General of India – approves drugs for Indian market."))
story.append(sp(4))

story.append(subsec("Pharmacoeconomics"))
story.append(p("Scientific discipline evaluating the cost and consequences of drug therapy in the healthcare system. Methods used:", BODY))
story.append(b("Cost-minimisation analysis: Compares costs when outcomes are equivalent."))
story.append(b("Cost-effectiveness analysis: Outcome measured in natural units (e.g., life-years gained)."))
story.append(b("Cost-benefit analysis: Outcome measured in monetary terms."))
story.append(b("Cost-utility analysis: Outcome measured in QALYs (quality-adjusted life-years)."))
story.append(sp(6))

# ─── QUICK REVISION BOX ─────────────────────────────────────────────
story.append(section_header("QUICK REVISION – HIGH YIELD MNEMONICS & FACTS"))
story.append(sp(6))

story.append(make_table(
    ["Topic", "Mnemonic / Key Fact"],
    [
        ["ADME", "A = Absorption, D = Distribution, M = Metabolism, E = Excretion"],
        ["Enzyme Inducers", "RIPPAC: Rifampicin, Isoniazid (weak), Phenytoin, Phenobarbitone, Alcohol (chronic), Carbamazepine"],
        ["Enzyme Inhibitors", "KECK-GIA: Ketoconazole, Erythromycin, Cimetidine, Ketoconazole again, Grapefruit juice, Isoniazid (acute), Alcohol (acute)"],
        ["1st-pass metabolism drugs", "GPMLA: GTN, Propranolol, Morphine, Lidocaine, Aspirin"],
        ["Drugs crossing BBB (lipid-soluble)", "Thiopentone, Diazepam, Chloramphenicol, Levodopa (prodrug)"],
        ["Competitive antagonism", "Parallel rightward shift of DRC with same Emax"],
        ["Non-competitive antagonism", "Reduced Emax; shift not reversible with higher agonist dose"],
        ["Therapeutic Index", "TI = LD50/ED50; HIGH TI = safer (penicillin). LOW TI = narrow therapeutic window (digoxin, phenytoin, lithium, aminoglycosides)"],
        ["Ion trapping for acids (poisoning)", "Alkalinise urine with NaHCO3 for aspirin/phenobarb overdose"],
        ["Ion trapping for bases (poisoning)", "Acidify urine with NH4Cl for amphetamine/morphine overdose"],
        ["Grey baby syndrome", "Chloramphenicol in neonates – immature glucuronosyltransferase"],
        ["G6PD deficiency drugs", "Primaquine, Dapsone, Nitrofurantoin → haemolytic anaemia"],
        ["Prodrugs", "Levodopa, Enalapril, Prednisone, Codeine, Cyclophosphamide"],
        ["Teratogenic drugs", "WARCAT: Warfarin, ACE-i, Retinoids (Vit A), Carbamazepine, Anti-thyroid (PTU), Thalidomide"],
        ["Drugs in breast milk (avoid)", "Metronidazole, Lithium, Chloramphenicol, Amiodarone"],
        ["Clinical trial phases", "I=Healthy volunteers (PK/Safety); II=Patients (Efficacy); III=RCT (Confirmation); IV=Post-marketing (Surveillance)"],
        ["OP poisoning antidote", "Atropine (SLUDGE) + Pralidoxime (within 24 hrs – before ageing)"],
        ["Paracetamol OD antidote", "N-acetylcysteine (NAC) – within 8–10 hrs"],
        ["Opioid OD antidote", "Naloxone"],
        ["BZD OD antidote", "Flumazenil"],
    ],
    [5*cm, 12*cm]
))

story.append(sp(8))
story.append(hr(C_DARK, 2))
story.append(p("End of General Pharmacology Notes | Source: Tara V. Shanbhag & Smita Shenoy, Pharmacology for Medical Graduates, 3rd Edition",
    S("foot", fontName="Helvetica-Oblique", fontSize=8, textColor=C_GREY, alignment=TA_CENTER)))

# ─── Build ──────────────────────────────────────────────────────────
doc.build(story)
print(f"PDF saved: {OUTPUT}")
Running Command

cd /home/daytona/workspace/general-pharmacology-notes && python3 gen_pharma_notes.py 2>&1

Running Command

ls -lh /home/daytona/workspace/general-pharmacology-notes/General_Pharmacology_Notes.pdf

Your PDF notes are ready! Download here:

General Pharmacology Notes

PDF Document · PDF


Here is everything that is covered inside the notes:

What's Included (10 Sections)

#SectionKey Content
1Definitions & Drug NomenclaturePharmacology, Pharmacokinetics, Pharmacodynamics, Essential medicines, Orphan drugs, OTC vs Prescription, Chemical/Generic/Brand names
2Sources of Drug InformationIP, BP, EP, USP, PDR, Formulary
3Routes of AdministrationEnteral (oral, sublingual, rectal), Parenteral (ID, SC, IM, IV, intrathecal), Inhalation, Topical - with Adv/Disadv tables
4Pharmacokinetics (ADME)Membrane transport, Absorption factors, Bioavailability, Vd, Protein binding, BBB, Phase I/II metabolism, CYP450 (inducers + inhibitors), Excretion + ion trapping, t½, Loading/Maintenance dose, Zero vs First-order kinetics
5PharmacodynamicsMechanisms of action, Receptor families (4 types), Agonist/Antagonist/Partial agonist/Inverse agonist, Competitive vs Non-competitive antagonism, ED50/LD50/TI, Potency vs Efficacy
6Factors Modifying Drug ActionDrug factors, Age (Grey baby, elderly), Sex, Genetics (G6PD, slow acetylators), Tolerance, Tachyphylaxis, Placebo, Paediatric dose formulae
7Drug InteractionsPharmaceutical, Pharmacokinetic, Pharmacodynamic; Synergism, Potentiation, Antagonism; 10 clinical interaction pairs
8ADRs & Rational PrescribingType A vs B ADRs; Side/secondary/toxic/allergic/idiosyncratic effects; Teratogenicity; Irrational prescribing hazards
9Treatment of PoisoningGeneral principles (ABC, activated charcoal, ion trapping); Specific antidotes table (17 poisons)
10New Drug DevelopmentPreclinical toxicity studies; Clinical Trials Phases I–IV; IND/NDA/DCGI; Pharmacoeconomics
  • Exam tips (highlighted in amber) appear throughout
  • Mnemonics for enzyme inducers/inhibitors, 1st-pass drugs, teratogens
  • Quick Revision table at the end with 20 high-yield facts

Make a notes on pharmacodynamics based on the following pointers in exam oriented and easy notes form the given source. Pharmacokinetics. Absorption, Distribution, Metabolism, and Excretion of Drugs (ADME): Physicochemical Properties of the Drug Route of Administration Gastrointestinal Factors: Drug Formulation Blood Flow to Tissue Plasma Protein Binding Tissue Binding Special Barriers Site of Metabolism: Phase I Reactions: Phase II Reactions First-Pass Metabolism Enzyme Induction/Inhibition: Genetic Polymorphisms: Hepatic (bile): Factors Affecting Absorption: Drug-Related Factors Solubility:  Ionization:  Molecular Size:  Formulation:  Chemical Stability: Route of Administration Gastrointestinal (GI) Factors  pH:  Gastric Emptying:  Presence of Food: Drug Transport Mechanisms: Physicochemical Properties: Blood Flow to Tissues: Plasma Protein Binding: Tissue Binding: Special Barriers:  Blood-Brain Barrier (BBB):  Placental Barrier: Site of Metabolism:  Phase I (Functionalization Reactions):  Phase II (Conjugation Reactions): Factors Affecting Metabolism Enzyme Activity:  Induction:  Inhibition: Genetic Variability: First-Pass Metabolism: Age: Factors Affecting Excretion Route of Excretion: Renal Excretion (Primary):  Glomerular Filtration:  Tubular Secretion:  Tubular Reabsorption: Biliary Excretion: Other Routes: Drug Properties: Renal Function: Hepatic Function: Age: Gender: Genetic Variations: Disease States: Lifestyle Factors: Patient-Related Factors Drug-Drug Interactions:

Writing File

~/general-pharmacology-notes/pharmacokinetics_notes.py


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

OUTPUT = "/home/daytona/workspace/general-pharmacology-notes/Pharmacokinetics_ADME_Notes.pdf"

# ── Colour Palette ──────────────────────────────────────────────────
NAVY    = colors.HexColor("#0d1b4b")
BLUE    = colors.HexColor("#1565c0")
LBLUE   = colors.HexColor("#e3f2fd")
MBLUE   = colors.HexColor("#bbdefb")
TEAL    = colors.HexColor("#00695c")
LTEAL   = colors.HexColor("#e0f2f1")
RED     = colors.HexColor("#b71c1c")
LRED    = colors.HexColor("#ffebee")
AMBER   = colors.HexColor("#e65100")
LAMBER  = colors.HexColor("#fff3e0")
GREEN   = colors.HexColor("#1b5e20")
LGREEN  = colors.HexColor("#e8f5e9")
PURPLE  = colors.HexColor("#4a148c")
LPURPLE = colors.HexColor("#f3e5f5")
GREY    = colors.HexColor("#212121")
LGREY   = colors.HexColor("#f5f5f5")
WHITE   = colors.white
ROWALT1 = colors.HexColor("#e8eaf6")
ROWALT2 = colors.HexColor("#ffffff")

# ── Style Factory ───────────────────────────────────────────────────
def S(name, **kw):
    return ParagraphStyle(name, **kw)

COVER_MAIN = S("CM", fontName="Helvetica-Bold", fontSize=32,
               textColor=WHITE, alignment=TA_CENTER, leading=38)
COVER_SUB  = S("CS", fontName="Helvetica", fontSize=14,
               textColor=colors.HexColor("#bbdefb"), alignment=TA_CENTER, spaceAfter=6)
COVER_INFO = S("CI", fontName="Helvetica-Oblique", fontSize=9,
               textColor=colors.HexColor("#90a4ae"), alignment=TA_CENTER)

CH = S("CH", fontName="Helvetica-Bold", fontSize=13,
       textColor=WHITE, alignment=TA_LEFT, leading=16)

SEC = S("SEC", fontName="Helvetica-Bold", fontSize=11.5,
        textColor=NAVY, spaceBefore=10, spaceAfter=4)

SUBSEC = S("SUBSEC", fontName="Helvetica-Bold", fontSize=10,
           textColor=BLUE, spaceBefore=6, spaceAfter=3)

BODY = S("BODY", fontName="Helvetica", fontSize=9.5,
         textColor=GREY, leading=14, spaceAfter=3, alignment=TA_JUSTIFY)

BUL = S("BUL", fontName="Helvetica", fontSize=9.5,
        textColor=GREY, leading=13, leftIndent=14, spaceAfter=2)

BUL2 = S("BUL2", fontName="Helvetica", fontSize=9,
         textColor=GREY, leading=12, leftIndent=28, spaceAfter=2)

KEY = S("KEY", fontName="Helvetica-Bold", fontSize=9.5,
        textColor=RED, leading=13, spaceAfter=2)

TIP = S("TIP", fontName="Helvetica-Bold", fontSize=9.5,
        textColor=AMBER, leading=13, spaceAfter=2)

EX = S("EX", fontName="Helvetica-Oblique", fontSize=9,
       textColor=TEAL, leading=12, leftIndent=14, spaceAfter=2)

TH = S("TH", fontName="Helvetica-Bold", fontSize=8.5,
       textColor=WHITE, alignment=TA_CENTER, leading=11)

TC = S("TC", fontName="Helvetica", fontSize=8.5,
       textColor=GREY, alignment=TA_LEFT, leading=11)

TCB = S("TCB", fontName="Helvetica-Bold", fontSize=8.5,
        textColor=NAVY, alignment=TA_LEFT, leading=11)

# ── Helpers ──────────────────────────────────────────────────────────
def hr(col=colors.HexColor("#90a4ae"), t=0.7):
    return HRFlowable(width="100%", thickness=t, color=col, spaceAfter=4, spaceBefore=4)

def sp(h=5):  return Spacer(1, h)
def p(txt, sty=BODY):   return Paragraph(txt, sty)
def b(txt):             return Paragraph(f"&#x2022; {txt}", BUL)
def b2(txt):            return Paragraph(f"&#x2013; {txt}", BUL2)
def sec(txt):           return p(txt, SEC)
def sub(txt):           return p(txt, SUBSEC)
def key(txt):           return p(f"&#x2605; {txt}", KEY)
def tip(txt):           return p(f"&#x1F3AF; EXAM TIP: {txt}", TIP)
def ex(txt):            return p(f"e.g. {txt}", EX)

def chapter_bar(title):
    data = [[Paragraph(title, CH)]]
    t = Table(data, colWidths=[17*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND',    (0,0),(-1,-1), NAVY),
        ('TOPPADDING',    (0,0),(-1,-1), 8),
        ('BOTTOMPADDING', (0,0),(-1,-1), 8),
        ('LEFTPADDING',   (0,0),(-1,-1), 12),
        ('RIGHTPADDING',  (0,0),(-1,-1), 8),
    ]))
    return t

def colbox(items, title=None, bg=LBLUE, border=MBLUE):
    inner = []
    if title:
        inner.append(p(f"<b>{title}</b>",
            S("bt", fontName="Helvetica-Bold", fontSize=9.5,
              textColor=NAVY, leading=13, spaceAfter=3)))
    for it in items:
        inner.append(p(f"&#x2022; {it}",
            S("bi", fontName="Helvetica", fontSize=9,
              textColor=GREY, leading=13, leftIndent=6)))
    t = Table([[inner]], colWidths=[17*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND',    (0,0),(-1,-1), bg),
        ('BOX',           (0,0),(-1,-1), 1,  border),
        ('TOPPADDING',    (0,0),(-1,-1), 8),
        ('BOTTOMPADDING', (0,0),(-1,-1), 8),
        ('LEFTPADDING',   (0,0),(-1,-1), 10),
        ('RIGHTPADDING',  (0,0),(-1,-1), 10),
    ]))
    return t

def tbl(headers, rows, widths=None):
    if widths is None:
        widths = [17*cm / len(headers)] * len(headers)
    data = [[Paragraph(h, TH) for h in headers]]
    for i, row in enumerate(rows):
        data.append([Paragraph(str(c), TC) for c in row])
    t = Table(data, colWidths=widths)
    ts = [
        ('BACKGROUND', (0,0),(-1,0), BLUE),
        ('GRID',       (0,0),(-1,-1), 0.4, colors.HexColor("#90a4ae")),
        ('TOPPADDING', (0,0),(-1,-1), 5),
        ('BOTTOMPADDING',(0,0),(-1,-1), 5),
        ('LEFTPADDING',(0,0),(-1,-1), 6),
        ('VALIGN',     (0,0),(-1,-1), 'TOP'),
    ]
    for i in range(1, len(rows)+1):
        ts.append(('BACKGROUND',(0,i),(-1,i), ROWALT1 if i%2 else ROWALT2))
    t.setStyle(TableStyle(ts))
    return t

def two_col(left_items, right_items, left_title, right_title,
            lbg=LBLUE, rbg=LGREEN, lb=MBLUE, rb=colors.HexColor("#a5d6a7")):
    def make_cell(title, items, bg, bdr):
        inner = [p(f"<b>{title}</b>",
            S("hd2", fontName="Helvetica-Bold", fontSize=9.5,
              textColor=NAVY, leading=13, spaceAfter=3))]
        for it in items:
            inner.append(p(f"&#x2022; {it}",
                S("bi2", fontName="Helvetica", fontSize=9,
                  textColor=GREY, leading=13, leftIndent=6)))
        cell = Table([[inner]], colWidths=[8*cm])
        cell.setStyle(TableStyle([
            ('BACKGROUND', (0,0),(-1,-1), bg),
            ('BOX',        (0,0),(-1,-1), 1, bdr),
            ('TOPPADDING', (0,0),(-1,-1), 7),
            ('BOTTOMPADDING',(0,0),(-1,-1), 7),
            ('LEFTPADDING',(0,0),(-1,-1), 8),
            ('RIGHTPADDING',(0,0),(-1,-1), 8),
        ]))
        return cell
    row = [[make_cell(left_title, left_items, lbg, lb),
            make_cell(right_title, right_items, rbg, rb)]]
    outer = Table(row, colWidths=[8.4*cm, 8.6*cm], hAlign='LEFT')
    outer.setStyle(TableStyle([
        ('VALIGN',     (0,0),(-1,-1), 'TOP'),
        ('LEFTPADDING',(0,0),(-1,-1), 0),
        ('RIGHTPADDING',(0,0),(-1,-1), 0),
    ]))
    return outer

# ════════════════════════════════════════════════════════════════════
#  DOCUMENT
# ════════════════════════════════════════════════════════════════════
doc = SimpleDocTemplate(OUTPUT, pagesize=A4,
    leftMargin=2*cm, rightMargin=2*cm,
    topMargin=2.2*cm, bottomMargin=2.2*cm,
    title="Pharmacokinetics (ADME) – Exam Notes",
    author="Tara Shanbhag Pharmacology")

story = []

# ════════════════ COVER PAGE ════════════════════════════════════════
cover = Table([[""]], colWidths=[17*cm], rowHeights=[5*cm])
cover.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,-1), NAVY)]))
story.append(cover)
story.append(sp(-130))
story.append(sp(18))
story.append(p("PHARMACOKINETICS", S("cvT", fontName="Helvetica-Bold",
    fontSize=34, textColor=WHITE, alignment=TA_CENTER, leading=40)))
story.append(p("Absorption · Distribution · Metabolism · Excretion",
    S("cvS", fontName="Helvetica", fontSize=13,
      textColor=colors.HexColor("#bbdefb"), alignment=TA_CENTER, spaceAfter=6)))
story.append(sp(55))
story.append(p("Comprehensive Exam-Oriented Notes",
    S("cvI", fontName="Helvetica-Bold", fontSize=10,
      textColor=colors.HexColor("#e3f2fd"), alignment=TA_CENTER)))
story.append(p("Source: Tara V. Shanbhag & Smita Shenoy — Pharmacology for Medical Graduates, 3rd Ed.",
    S("cvII", fontName="Helvetica-Oblique", fontSize=8.5,
      textColor=colors.HexColor("#90a4ae"), alignment=TA_CENTER)))
story.append(hr(NAVY, 2))
story.append(sp(8))

# ── TOC ─────────────────────────────────────────────────────────────
story.append(sec("CHAPTER OUTLINE"))
toc = [
    "1.  Overview of Pharmacokinetics (ADME)",
    "2.  Drug Transport Across Membranes",
    "3.  ABSORPTION — Factors Affecting Absorption",
    "       3a. Drug-Related Factors",
    "       3b. Route of Administration",
    "       3c. Gastrointestinal (GI) Factors",
    "       3d. Drug Formulation",
    "       3e. Blood Flow to Tissue",
    "4.  DISTRIBUTION — Factors Affecting Distribution",
    "       4a. Physicochemical Properties",
    "       4b. Plasma Protein Binding",
    "       4c. Tissue Binding",
    "       4d. Special Barriers (BBB & Placenta)",
    "5.  METABOLISM (Biotransformation)",
    "       5a. Phase I Reactions",
    "       5b. Phase II Reactions",
    "       5c. First-Pass Metabolism",
    "       5d. Factors Affecting Metabolism",
    "6.  EXCRETION — Factors Affecting Excretion",
    "       6a. Renal Excretion (Primary)",
    "       6b. Biliary / Hepatic Excretion",
    "       6c. Other Routes",
    "       6d. Patient & Drug-Related Factors",
    "7.  Key Pharmacokinetic Parameters",
    "8.  Drug–Drug Interactions (Pharmacokinetic Basis)",
    "9.  Quick Revision Table — High-Yield Facts",
]
for item in toc:
    story.append(b(item))
story.append(sp(6))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 1 – OVERVIEW
# ════════════════════════════════════════════════════════════════════
story.append(chapter_bar("1. OVERVIEW OF PHARMACOKINETICS (ADME)"))
story.append(sp(6))
story.append(p(
    "<b>Pharmacokinetics</b> = what the <b>body</b> does to the <b>drug</b>. "
    "Derived from Greek: <i>pharmakon</i> (drug) + <i>kinetikos</i> (motion). "
    "It describes the time-course of drug concentration in the body through four processes:", BODY))
story.append(sp(4))

story.append(tbl(
    ["Process", "Full Name", "Simple Definition", "Key Organ(s)"],
    [
        ["<b>A</b>bsorption",   "Drug uptake from site of administration",
         "Entry of drug into the bloodstream", "GI tract, Skin, Lungs"],
        ["<b>D</b>istribution", "Drug spread from blood to tissues",
         "Drug reaches its target tissues", "Liver, Kidney, Brain, Fat"],
        ["<b>M</b>etabolism",   "Biotransformation of drug",
         "Chemical alteration → usually inactive/polar metabolites", "Liver (primary), Gut wall, Lungs"],
        ["<b>E</b>xcretion",    "Removal of drug from body",
         "Elimination of drug and metabolites", "Kidney (primary), Bile, Lungs"],
    ],
    [2*cm, 4*cm, 5.5*cm, 5.5*cm]
))
story.append(sp(4))
story.append(colbox([
    "Pharmacokinetics = ADME = Body acts on Drug.",
    "Pharmacodynamics = Drug acts on Body (mechanisms of action, receptor binding).",
    "Together, PK + PD determine the dose-response relationship.",
], title="PK vs PD — Distinguish Always!", bg=LAMBER, border=colors.HexColor("#ffb74d")))
story.append(sp(6))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 2 – DRUG TRANSPORT
# ════════════════════════════════════════════════════════════════════
story.append(chapter_bar("2. DRUG TRANSPORT ACROSS BIOLOGICAL MEMBRANES"))
story.append(sp(6))
story.append(p(
    "All biological membranes consist of a <b>phospholipid bilayer</b>. "
    "The mechanism by which a drug crosses a membrane determines its absorption and distribution.", BODY))
story.append(sp(4))

story.append(tbl(
    ["Mechanism", "Energy?", "Carrier?", "Direction", "Saturable?", "Examples"],
    [
        ["Passive Diffusion",       "No (ATP)", "No",  "High → Low conc.",         "No",  "Most lipid-soluble drugs; weak acids/bases in un-ionised form"],
        ["Filtration",              "No",        "No",  "Depends on pore size",     "No",  "Small water-soluble molecules through capillary pores"],
        ["Active Transport",        "Yes (ATP)", "Yes", "Low → High (vs gradient)", "Yes", "Levodopa (intestine), choline into cholinergic neurones, catecholamines into sympathetic neurones"],
        ["Facilitated Diffusion",   "No",        "Yes", "High → Low",               "Yes", "Glucose uptake into muscle cells"],
        ["Pinocytosis/Endocytosis", "Yes",        "No",  "Engulfment of particles",  "No",  "Large proteins, some vaccines"],
    ],
    [3.2*cm, 1.5*cm, 1.5*cm, 3.2*cm, 1.8*cm, 5.8*cm]
))
story.append(sp(4))
story.append(colbox([
    "For passive diffusion: lipid solubility, degree of ionisation (pKa), and concentration gradient are the key determinants.",
    "Henderson-Hasselbalch equation governs ionisation: weak acids are un-ionised in acidic pH (stomach) → better absorbed; weak bases un-ionised in alkaline pH (intestine) → better absorbed.",
    "Only the UN-IONISED form crosses membranes; only the FREE (unbound) form is pharmacologically active.",
], title="Golden Rules of Drug Transport", bg=LGREEN, border=colors.HexColor("#a5d6a7")))
story.append(sp(6))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 3 – ABSORPTION
# ════════════════════════════════════════════════════════════════════
story.append(chapter_bar("3. ABSORPTION — FACTORS AFFECTING ABSORPTION"))
story.append(sp(6))
story.append(p(
    "<b>Absorption</b> = movement of a drug from its site of administration into the systemic circulation. "
    "Determines the <b>onset</b>, <b>intensity</b>, and <b>duration</b> of drug action after extra-vascular administration.", BODY))
story.append(sp(4))

# 3a – Drug Related Factors
story.append(sec("3a. Drug-Related Factors"))
story.append(sp(3))
story.append(tbl(
    ["Factor", "Principle", "Clinical Relevance / Examples"],
    [
        ["<b>Solubility</b>",
         "Drug must dissolve in GI fluid before absorption. Aqueous solubility is essential for dissolution.",
         "Griseofulvin: poorly water-soluble; absorption ↑ with fatty food (↑ bile salts). Micronised forms have ↑ surface area → ↑ dissolution → ↑ absorption."],
        ["<b>Ionisation (pKa)</b>",
         "Un-ionised lipid-soluble form is absorbed. Henderson-Hasselbalch determines fraction un-ionised at a given pH.",
         "Aspirin (weak acid, pKa 3.5): un-ionised in stomach → absorbed in stomach. Morphine (weak base): un-ionised in intestine → absorbed mainly in small intestine."],
        ["<b>Molecular Size</b>",
         "Small molecules cross membranes easily. Large molecules (>500 Da) are poorly absorbed orally.",
         "Heparin (large MW) → not absorbed orally → must be given parenterally. Insulin → not absorbed orally → SC/IV."],
        ["<b>Formulation</b>",
         "The dosage form determines rate and extent of drug release. Disintegration → Dissolution → Absorption.",
         "Enteric-coated tablets: resist stomach acid, dissolve in intestine (e.g., enteric-coated aspirin, omeprazole). SR/ER tablets: slow release → sustained plasma levels. Liquid formulations absorbed faster than solids."],
        ["<b>Chemical Stability</b>",
         "Drug must be stable to acid and enzymes in the GI tract.",
         "Penicillin G: destroyed by gastric acid → must give parenterally OR use acid-stable Penicillin V. Insulin: destroyed by proteolytic enzymes → cannot be given orally."],
        ["<b>Particle Size</b>",
         "Smaller particle size → larger surface area → faster dissolution → better absorption.",
         "Micronised griseofulvin has 4× better absorption than regular form. Anthelmintics (large particle size) poorly absorbed → remain in gut → local action."],
        ["<b>Lipophilicity (Log P)</b>",
         "Higher lipophilicity → better passive diffusion across membranes.",
         "Highly lipophilic drugs (e.g., diazepam) rapidly absorbed; extremely hydrophilic drugs (e.g., aminoglycosides) poorly absorbed orally."],
    ],
    [2.5*cm, 5.5*cm, 9*cm]
))
story.append(sp(6))

# 3b – Routes
story.append(sec("3b. Route of Administration"))
story.append(sp(3))
story.append(tbl(
    ["Route", "Bioavailability", "Onset", "Key Notes"],
    [
        ["Intravenous (IV)",       "100% (by definition)", "Immediate",  "No absorption step; 100% F; fastest; not recalled once given; drug must be in solution; risk of infection, thrombophlebitis"],
        ["Intramuscular (IM)",     "75–100%",              "Fast (15–30 min)", "Bypasses 1st pass; depot preparations possible (oil-based); not for irritant drugs in SC"],
        ["Subcutaneous (SC)",      "~75–90%",              "Slower than IM",   "Self-administration possible (insulin); depot implants possible; slow for vasoconstricted sites"],
        ["Oral (p.o.)",            "Variable (5–100%)",    "Slowest",    "Safe, convenient; subject to 1st pass metabolism, acid destruction, food interactions; most common route"],
        ["Sublingual (SL)",        "High (bypasses 1st pass)", "Rapid (2–5 min)", "Absorbed directly into systemic circulation via sublingual veins; avoids hepatic 1st pass. e.g., GTN, buprenorphine"],
        ["Rectal",                 "Variable",             "Moderate",   "Partial 1st-pass avoidance (inferior rectal vein bypasses portal). e.g., diazepam PR (status epilepticus in children), indomethacin suppository"],
        ["Transdermal (patch)",    "Good",                 "Slow onset, prolonged", "Bypasses 1st pass; rate controlled by skin permeability; lipid-soluble drugs only. e.g., GTN patch, fentanyl patch, nicotine patch"],
        ["Inhalation",             "Rapid/high",           "Very fast",  "High surface area; good blood supply; low dose needed; avoids 1st pass. e.g., salbutamol inhaler; volatile anaesthetics"],
    ],
    [2.8*cm, 2.8*cm, 2.8*cm, 8.6*cm]
))
story.append(sp(4))
story.append(tip(
    "Routes that BYPASS first-pass metabolism: IV, IM, SC, Sublingual, Transdermal, Inhalation, Rectal (partial). "
    "First-pass is relevant ONLY for oral (and partially rectal) routes."))
story.append(sp(6))

# 3c – GI Factors
story.append(sec("3c. Gastrointestinal (GI) Factors"))
story.append(sp(3))
story.append(tbl(
    ["GI Factor", "Effect on Absorption", "Examples"],
    [
        ["<b>pH of GI Tract</b>",
         "Stomach pH 1–3 (acidic): favours absorption of weak acids (un-ionised form). Small intestine pH 6–8: favours absorption of weak bases. Achlorhydria ↑ gastric pH → ↓ absorption of weak acids; ↑ absorption of weak bases.",
         "Aspirin (weak acid) absorbed in stomach. Ketoconazole requires acidic pH → ↓ absorption with antacids/PPIs. Atazanavir: proton pump inhibitors ↓ absorption."],
        ["<b>Gastric Emptying Rate</b>",
         "Most absorption occurs in small intestine (large SA). Faster gastric emptying → drug reaches intestine sooner → faster absorption (for most drugs). Slower emptying → prolonged stomach exposure → may ↓ absorption.",
         "Metoclopramide ↑ gastric emptying → ↑ drug absorption. Anticholinergic drugs ↓ gastric motility → ↓ absorption. Opioids ↓ GI motility → delayed absorption."],
        ["<b>Presence of Food</b>",
         "Food generally delays gastric emptying → delayed but may not reduce total absorption. Some drugs need food (fat-soluble); others must be given fasting.",
         "Fatty food ↑ griseofulvin absorption (bile salts help). Tetracycline: ↓ absorption with milk/dairy (chelation). Alendronate: take on empty stomach with plain water (food ↓ absorption by 60%). Metformin: give with food to ↓ GI side effects."],
        ["<b>GI Motility</b>",
         "↑ Motility (diarrhoea) → ↓ contact time → ↓ absorption. ↓ Motility → ↑ contact time → may ↑ or ↓ absorption.",
         "Diarrhoea reduces absorption of oral drugs. Prolonged constipation → drug accumulation in gut."],
        ["<b>GI Flora</b>",
         "Intestinal bacteria can metabolise drugs or their conjugates. Enterohepatic recycling disrupted by antibiotics.",
         "Oral contraceptive pills: antibiotics kill gut flora → ↓ enterohepatic recycling → ↓ oestrogen → contraceptive failure."],
        ["<b>Surface Area</b>",
         "Small intestine has villi + microvilli → vast surface area (~200 m²). Jejunum is the primary site of absorption.",
         "After bowel resection: ↓ surface area → ↓ drug absorption. Coeliac disease: damaged villi → variable absorption."],
        ["<b>GI Blood Supply</b>",
         "Rich blood flow to GI tract maintains concentration gradient → drives passive diffusion.",
         "In shock/heart failure: ↓ splanchnic blood flow → ↓ oral drug absorption → IV route preferred."],
    ],
    [3*cm, 6*cm, 8*cm]
))
story.append(sp(4))
story.append(colbox([
    "Henderson-Hasselbalch: For weak acid: pH = pKa + log([ionised]/[un-ionised]).",
    "Ion Trapping: A drug is 'trapped' in compartments where it is ionised. Acidic drug → trapped in alkaline compartment; Basic drug → trapped in acidic compartment.",
    "Aspirin (weak acid, pKa 3.5): In stomach (pH 1.4) → mostly un-ionised → absorbed. In plasma (pH 7.4) → mostly ionised → stays in blood (ion trapping exploited in poisoning treatment).",
], title="pH & Ionisation — Ion Trapping Concept", bg=LPURPLE, border=PURPLE))
story.append(sp(6))

# 3d – Drug Formulation
story.append(sec("3d. Drug Formulation"))
story.append(sp(3))
story.append(tbl(
    ["Formulation Type", "Characteristics", "Examples"],
    [
        ["Immediate-release tablet/capsule", "Standard disintegration and dissolution; predictable onset", "Most conventional tablets"],
        ["Enteric-coated (EC)", "Resists gastric acid; dissolves in intestinal pH 6+; protects drug from acid or protects stomach from drug", "EC Aspirin (↓ gastric irritation), Omeprazole (acid-labile), Erythromycin EC"],
        ["Sustained/Extended Release (SR/XR/ER)", "Controlled drug release over hours; reduces dosing frequency; avoids peak-related toxicity; maintains steady plasma levels", "Metformin XR, Nifedipine SR, Diltiazem SR, Morphine SR (MS Contin)"],
        ["Transdermal patch", "Drug released through skin at controlled rate; sustained action; avoids 1st pass; useful for drugs with short t½ orally", "GTN patch (24 h), Fentanyl patch (72 h), Nicotine patch, Oestradiol patch"],
        ["Depot injection (IM/SC)", "Oil-based or microcrystalline suspension; slow release from injection site; weeks-months of action", "Fluphenazine decanoate (schizophrenia), Medroxyprogesterone acetate (contraception), Benzathine penicillin"],
        ["Suppositories/enemas", "Rectal absorption; partial avoidance of 1st pass via inferior rectal veins; useful when oral not possible", "Diazepam PR (status epilepticus), Indomethacin suppository, Mesalazine enema"],
        ["Liposomes & Nanoparticles", "Targeted drug delivery; reduces toxicity to normal tissues; ↑ drug stability", "Liposomal doxorubicin (Doxil), Liposomal amphotericin B (↓ nephrotoxicity)"],
    ],
    [3.5*cm, 6*cm, 7.5*cm]
))
story.append(sp(4))
story.append(tip("SR formulations should NOT be crushed/chewed (dose dumping → toxicity). Enteric-coated tablets should also not be crushed. Important for prescribing MCQs."))
story.append(sp(6))

# 3e – Blood Flow
story.append(sec("3e. Blood Flow to Tissue (Absorption Site)"))
story.append(sp(3))
story.append(b("Greater blood flow to absorption site → maintains concentration gradient → faster absorption."))
story.append(b("IM injection in deltoid muscle (good blood supply) is absorbed faster than gluteus."))
story.append(b("Adding adrenaline (vasoconstrictive) to local anaesthetics → reduces local blood flow → prolongs local anaesthetic action by slowing systemic absorption."))
story.append(b("In shock/heart failure/hypotension: ↓ blood flow to gut → oral drug absorption unreliable → use IV route."))
story.append(b("Heat ↑ blood flow to skin → ↑ transdermal absorption (fever can increase fentanyl patch absorption → toxicity)."))
story.append(sp(4))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 4 – DISTRIBUTION
# ════════════════════════════════════════════════════════════════════
story.append(chapter_bar("4. DISTRIBUTION — FACTORS AFFECTING DISTRIBUTION"))
story.append(sp(6))
story.append(p(
    "<b>Distribution</b> = process by which a drug moves from the systemic circulation into tissues and fluids of the body. "
    "Determines the <b>volume of distribution (Vd)</b>, tissue concentrations, and whether the drug reaches its target.", BODY))
story.append(sp(4))

story.append(sec("Physicochemical Properties of the Drug"))
story.append(sp(3))
story.append(tbl(
    ["Property", "Effect on Distribution", "Examples"],
    [
        ["<b>Lipid Solubility</b>",
         "Highly lipophilic drugs: widely distributed; cross membranes freely; large Vd; accumulate in fat/brain.",
         "Thiopentone, Diazepam, Chloramphenicol → enter brain rapidly. Lipophilic opioids (fentanyl) → wide distribution."],
        ["<b>Ionisation</b>",
         "Un-ionised form → crosses cell membranes. Ionised form → stays in aqueous compartments.",
         "Acidic drugs mainly in plasma; basic drugs distribute widely into tissues."],
        ["<b>Molecular Size/Weight</b>",
         "Large molecules confined to vascular compartment.",
         "Heparin (MW >15,000) stays in plasma; does not cross BBB or placenta."],
        ["<b>Polarity (Hydrophilicity)</b>",
         "Hydrophilic drugs: confined to extracellular fluid; small Vd; do not cross BBB.",
         "Aminoglycosides (hydrophilic) → Vd ≈ ECF. Neuromuscular blockers → cannot cross BBB."],
    ],
    [3*cm, 6*cm, 8*cm]
))
story.append(sp(5))

story.append(sec("4b. Plasma Protein Binding (PPB)"))
story.append(sp(3))
story.append(colbox([
    "Most drugs bind reversibly to plasma proteins. Main proteins: Albumin (acidic drugs), α1-acid glycoprotein (basic drugs), Lipoproteins (lipophilic drugs).",
    "Only FREE (unbound) drug: crosses membranes, exerts pharmacological effect, is metabolised, is excreted.",
    "Highly protein-bound drugs: warfarin (~99%), phenytoin (~90%), diazepam (~99%), aspirin (~80–90%).",
    "PPB reduces Vd (drug stays in plasma) and prolongs half-life (bound drug not metabolised/excreted).",
], title="Plasma Protein Binding — Key Concepts", bg=LBLUE, border=MBLUE))
story.append(sp(4))
story.append(tbl(
    ["Aspect", "Details"],
    [
        ["Hypoalbuminaemia",
         "↓ Albumin (liver cirrhosis, nephrotic syndrome, malnutrition) → ↑ free drug fraction → ↑ pharmacological effect and toxicity. Dose reduction needed. e.g., Phenytoin toxicity in hypoalbuminaemia."],
        ["Drug Displacement",
         "One drug displaces another from plasma proteins → ↑ free concentration of displaced drug → toxicity. e.g., Aspirin displaces warfarin → ↑ free warfarin → bleeding. Sulfonamides displace bilirubin → kernicterus in neonates."],
        ["Drug–Drug Interaction",
         "Clinically significant only if: drug is >90% protein-bound AND has a small Vd AND narrow therapeutic index."],
        ["Saturable Binding",
         "At toxic doses, binding sites are saturated → free drug fraction disproportionately increases → zero-order kinetics."],
    ],
    [3.5*cm, 13.5*cm]
))
story.append(sp(4))
story.append(tip("PPB displacement interaction is clinically significant only when: (i) >90% protein bound, (ii) small Vd, AND (iii) narrow therapeutic index. Warfarin + aspirin is the classic example."))
story.append(sp(5))

story.append(sec("4c. Tissue Binding"))
story.append(sp(3))
story.append(b("Drugs can bind to tissue components (proteins, lipids, nucleic acids), producing a reservoir effect."))
story.append(b("<b>High Vd drugs</b>: Extensively bound to tissues; plasma levels are low but total body content is high."))
story.append(b("Chloroquine: Vd >300 L/kg — extensively bound to tissues (RBCs, liver, kidney). Long duration of action."))
story.append(b("Digoxin: Vd >500 L/kg — tissue binding to Na-K ATPase in myocardium."))
story.append(b("Amiodarone: extremely high Vd (~60 L/kg) due to accumulation in fat and organs."))
story.append(b("Lipophilic drugs (e.g., general anaesthetics, benzodiazepines) accumulate in adipose tissue — prolonged action in obese patients."))
story.append(b("Tetracyclines: bind to calcium in bone and teeth → not given to children <8 yrs or in pregnancy."))
story.append(sp(5))

story.append(sec("4d. Special Barriers"))
story.append(sp(3))
story.append(tbl(
    ["Barrier", "Structure", "What Crosses?", "What Does NOT Cross?", "Clinical Relevance"],
    [
        ["<b>Blood-Brain Barrier (BBB)</b>",
         "Tight junctions between brain capillary endothelial cells; surrounded by astrocyte foot processes. No intercellular pores.",
         "Lipid-soluble, un-ionised, small MW, non-protein-bound drugs. e.g., Diazepam, thiopentone, chloramphenicol.",
         "Ionised, hydrophilic, large MW, highly protein-bound drugs. e.g., Aminoglycosides, dopamine.",
         "Dopamine doesn't cross → give levodopa (prodrug). In meningitis: inflammation ↑ BBB permeability → penicillin can now enter. P-glycoprotein efflux pumps at BBB expel many drugs."],
        ["<b>Placental Barrier</b>",
         "Trophoblastic layer between maternal and foetal blood. Less selective than BBB — most lipid-soluble drugs cross.",
         "Lipid-soluble drugs: diazepam, thiopentone, most anaesthetics, alcohol, nicotine.",
         "Large MW drugs: heparin, insulin (proteins). Most highly ionised drugs.",
         "Teratogens: Warfarin (Vit K antagonist → foetal bleeding + nasal hypoplasia), ACE inhibitors (↓ foetal renal function), Methotrexate, Thalidomide (phocomelia), Retinoids. Heparin preferred over warfarin in pregnancy (heparin doesn't cross)."],
    ],
    [2*cm, 3.5*cm, 3.5*cm, 3.5*cm, 4.5*cm]
))
story.append(sp(4))
story.append(colbox([
    "P-glycoprotein (P-gp / MDR1): An efflux transporter at the BBB, gut, liver, kidney. Pumps drugs OUT of cells. Inhibited by verapamil, ciclosporin → ↑ drug entry into brain or ↑ oral absorption.",
    "P-gp inducers (rifampicin) → ↑ efflux → ↓ drug levels. Clinical impact: ↓ digoxin levels with rifampicin.",
], title="P-Glycoprotein (P-gp) — Emerging Exam Topic", bg=LPURPLE, border=PURPLE))
story.append(sp(6))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 5 – METABOLISM
# ════════════════════════════════════════════════════════════════════
story.append(chapter_bar("5. METABOLISM (BIOTRANSFORMATION)"))
story.append(sp(6))
story.append(p(
    "<b>Metabolism</b> = enzymatic conversion of drugs into more polar (water-soluble) compounds for easier excretion. "
    "Primary site: <b>liver</b>. Other sites: intestinal wall, lungs, kidney, plasma, skin.", BODY))
story.append(sp(3))
story.append(colbox([
    "Most drug metabolism → inactive metabolites (detoxification).",
    "Some drugs → active metabolites (prodrugs: e.g., codeine → morphine; enalapril → enalaprilat).",
    "Some metabolism → toxic metabolites (e.g., paracetamol → NAPQI via CYP2E1).",
    "Metabolism occurs in two phases: Phase I (functionalization) and Phase II (conjugation).",
], title="Purpose of Drug Metabolism", bg=LGREEN, border=colors.HexColor("#a5d6a7")))
story.append(sp(4))

story.append(sec("5a. Phase I Reactions (Functionalization Reactions)"))
story.append(sp(3))
story.append(p(
    "Phase I reactions introduce or expose a functional group (–OH, –NH₂, –COOH, –SH) on the drug molecule. "
    "Main catalyst: <b>Cytochrome P450 (CYP450)</b> enzymes in hepatocyte endoplasmic reticulum.", BODY))
story.append(sp(4))
story.append(tbl(
    ["Reaction", "Mechanism", "Enzyme/System", "Examples"],
    [
        ["<b>Oxidation</b> (most common Phase I)",
         "Addition of oxygen or removal of hydrogen",
         "CYP450 (most important), Monoamine oxidase (MAO), Alcohol dehydrogenase",
         "Propranolol, Phenytoin, Diazepam, Ethanol → acetaldehyde"],
        ["<b>Reduction</b>",
         "Addition of hydrogen or removal of oxygen",
         "NADPH-cytochrome P450 reductase",
         "Halothane → hepatotoxic metabolites; Warfarin (minor)"],
        ["<b>Hydrolysis</b>",
         "Breakdown of compound by addition of water; cleaves ester and amide bonds",
         "Esterases (plasma, liver), Amidases",
         "Aspirin → salicylate + acetate; Suxamethonium → succinic acid + choline (pseudocholinesterase); Procaine"],
        ["<b>Cyclization</b>",
         "Conversion of straight chain to ring structure",
         "Various enzymes",
         "Proguanil → cycloguanil (antimalarial)"],
        ["<b>Decyclization</b>",
         "Breaking of ring structure",
         "Various enzymes",
         "Phenobarbitone, Phenytoin (ring opening)"],
    ],
    [2.5*cm, 3.5*cm, 4*cm, 7*cm]
))
story.append(sp(4))

story.append(sub("CYP450 System — The Most Important Drug-Metabolising Enzyme System"))
story.append(sp(3))
story.append(tbl(
    ["CYP Isoform", "% Drugs Metabolised", "Key Drug Substrates", "Key Inducers", "Key Inhibitors"],
    [
        ["CYP3A4", ">50%", "Statins, BZDs, CCBs, Cyclosporin, HIV protease inhibitors, Erythromycin, Codeine",
         "Rifampicin, Phenytoin, Carbamazepine, Phenobarbitone, St. John's Wort",
         "Ketoconazole, Itraconazole, Erythromycin, Clarithromycin, Grapefruit juice, Ritonavir"],
        ["CYP2D6", "~25%", "Beta-blockers (metoprolol), Codeine, Tricyclic antidepressants, Fluoxetine, Haloperidol",
         "None clinically significant",
         "Fluoxetine, Paroxetine, Quinidine, Amiodarone"],
        ["CYP2C9", "~15%", "Warfarin (S-form), Phenytoin, NSAIDs (ibuprofen, diclofenac), Sulfonylureas",
         "Rifampicin",
         "Fluconazole, Amiodarone, Metronidazole"],
        ["CYP2C19", "~10%", "PPIs (omeprazole), Clopidogrel, Diazepam",
         "Rifampicin",
         "Omeprazole, Fluconazole, Fluvoxamine"],
        ["CYP2E1", "Minor", "Ethanol, Paracetamol, Isoniazid",
         "Ethanol (chronic), Isoniazid",
         "Disulfiram"],
        ["CYP1A2", "Minor", "Theophylline, Clozapine, Caffeine",
         "Cigarette smoke, Omeprazole (weak), Char-grilled food",
         "Fluvoxamine, Ciprofloxacin"],
    ],
    [1.8*cm, 2.5*cm, 5*cm, 4*cm, 4.7*cm]
))
story.append(sp(4))
story.append(colbox([
    "ENZYME INDUCERS — Mnemonic: 'RIPS PC3' — Rifampicin, Isoniazid (weak), Phenytoin, St. John's Wort, Phenobarbitone, Carbamazepine, Chronic Alcohol, Cigarette Smoke.",
    "ENZYME INHIBITORS — Mnemonic: 'CAGE KIM' — Cimetidine, Amiodarone, Grapefruit juice, Erythromycin/clarithromycin, Ketoconazole/Itraconazole, Isoniazid (acute), Metronidazole/Fluconazole.",
    "Induction: ↑ CYP enzyme synthesis → ↑ drug metabolism → ↓ plasma drug levels → therapeutic failure. Onset: days–weeks.",
    "Inhibition: ↓ CYP enzyme activity → ↓ drug metabolism → ↑ plasma drug levels → toxicity. Onset: rapid (hours).",
], title="Enzyme Inducers vs Inhibitors — High-Yield!", bg=LAMBER, border=colors.HexColor("#ffb74d")))
story.append(sp(6))

story.append(sec("5b. Phase II Reactions (Conjugation Reactions)"))
story.append(sp(3))
story.append(p(
    "Phase II reactions conjugate (attach) a polar endogenous molecule to the drug or Phase I metabolite → "
    "highly polar, water-soluble, inactive product → ready for excretion.", BODY))
story.append(sp(4))
story.append(tbl(
    ["Conjugation Reaction", "Endogenous Molecule Added", "Enzyme", "Examples"],
    [
        ["<b>Glucuronidation</b> (most common Phase II)",
         "Glucuronic acid",
         "UDP-glucuronosyltransferase (UGT)",
         "Morphine → morphine-6-glucuronide (active!); Paracetamol; Bilirubin; Chloramphenicol"],
        ["<b>Sulfation</b>",
         "Sulfate group",
         "Sulfotransferase",
         "Paracetamol (minor), Minoxidil (activation), Oestrogens"],
        ["<b>Acetylation</b>",
         "Acetyl group (from acetyl-CoA)",
         "N-acetyltransferase (NAT)",
         "INH (isoniazid), Dapsone, Procainamide, Hydralazine — genetic polymorphism (fast/slow acetylators)"],
        ["<b>Methylation</b>",
         "Methyl group",
         "Methyltransferase",
         "Adrenaline → metadrenaline; Histamine; Nicotinic acid"],
        ["<b>Glycine conjugation</b>",
         "Glycine (amino acid)",
         "Acyl-CoA synthetase",
         "Salicylates → salicyluric acid; Benzoic acid → hippuric acid"],
        ["<b>Glutathione conjugation</b>",
         "Glutathione (GSH)",
         "Glutathione-S-transferase",
         "Paracetamol → NAPQI + GSH → mercapturic acid (detoxification). When GSH depleted → hepatotoxicity."],
    ],
    [3.5*cm, 3*cm, 3.5*cm, 7*cm]
))
story.append(sp(4))
story.append(colbox([
    "Glucuronidation is deficient in NEONATES (immature UGT enzyme) → Chloramphenicol cannot be conjugated → accumulates → Grey Baby Syndrome (vascular collapse, cyanosis, death).",
    "Morphine-6-glucuronide (M6G) is MORE potent than morphine itself — Phase II does NOT always inactivate!",
    "Paracetamol: At therapeutic doses, metabolised by glucuronidation + sulfation → safe. In overdose, these pathways saturate → overflow to CYP2E1 → NAPQI (toxic) → depletes GSH → hepatotoxicity (Zone 3 centrilobular necrosis).",
], title="Key Phase II Concepts", bg=LRED, border=RED))
story.append(sp(6))

story.append(sec("5c. First-Pass (Presystemic) Metabolism"))
story.append(sp(3))
story.append(p(
    "After oral absorption, drugs travel via the portal vein to the liver before entering systemic circulation. "
    "The liver may metabolise a significant fraction of the drug on this first passage → "
    "reduced bioavailability. This is <b>first-pass (presystemic) metabolism</b>.", BODY))
story.append(sp(4))
story.append(tbl(
    ["Aspect", "Details"],
    [
        ["Definition", "Metabolism of drug in the gut wall and/or liver before it reaches systemic circulation."],
        ["Effect", "↓ Oral bioavailability. Drug with 90% first-pass → only 10% reaches circulation."],
        ["Drugs with HIGH first-pass", "GTN (nitroglycerin) <1%, Propranolol ~30%, Morphine ~30–40%, Lidocaine ~70%, Aspirin moderate, Testosterone, Oestradiol."],
        ["Clinical Consequence", "Higher oral doses needed vs parenteral. Alternative routes used: GTN (sublingual, patch), Testosterone (IM, patch), Oestradiol (patch, IM). Patients with severe liver disease: ↓ first-pass → ↑ drug levels → dose reduction needed."],
        ["Gut wall metabolism", "CYP3A4 in intestinal epithelium also contributes to first-pass. Grapefruit juice inhibits intestinal CYP3A4 → ↑ bioavailability of statins, nifedipine, ciclosporin."],
        ["Prodrug advantage", "Enalapril (prodrug) → converted to enalaprilat after absorption. First-pass converts prodrug to active form."],
    ],
    [3.5*cm, 13.5*cm]
))
story.append(sp(4))
story.append(tip("GTN is the classic example: oral bioavailability <1% due to massive first-pass → must be given sublingually or transdermally. Propranolol oral dose (80–160 mg) >> IV dose (1–5 mg) for same effect."))
story.append(sp(6))

story.append(sec("5d. Factors Affecting Metabolism"))
story.append(sp(4))

story.append(sub("Enzyme Activity — Induction"))
story.append(b("Induction: Certain drugs/substances ↑ synthesis of CYP450 enzymes → ↑ metabolism of substrate drugs → ↓ plasma levels → possible therapeutic failure."))
story.append(b("Onset: Gradual (days to 2 weeks); Offset: Gradual (similar timeline) after stopping inducer."))
story.append(b("<b>Key Enzyme Inducers:</b> Rifampicin (strongest), Phenytoin, Phenobarbitone, Carbamazepine, Chronic alcohol, Cigarette smoke, St. John's Wort."))
story.append(b("<b>Clinical Consequences:</b>"))
story.append(b2("Rifampicin + OCP → ↓ oestrogen levels → contraceptive failure (use barrier method)."))
story.append(b2("Rifampicin + Warfarin → ↓ warfarin levels → inadequate anticoagulation → thrombosis."))
story.append(b2("Rifampicin + Ciclosporin → ↓ immunosuppression → transplant rejection."))
story.append(b2("Phenytoin + OCP → contraceptive failure."))
story.append(sp(4))

story.append(sub("Enzyme Activity — Inhibition"))
story.append(b("Inhibition: Certain drugs block CYP450 enzyme activity → ↓ metabolism of substrate drugs → ↑ plasma levels → toxicity."))
story.append(b("Onset: Rapid (within hours of first dose); maximal when steady-state of inhibitor reached."))
story.append(b("<b>Key Enzyme Inhibitors:</b> Ketoconazole, Itraconazole (CYP3A4), Erythromycin, Clarithromycin, Cimetidine, Grapefruit juice, Ritonavir, Fluconazole, Metronidazole, Amiodarone."))
story.append(b("<b>Clinical Consequences:</b>"))
story.append(b2("Erythromycin + Simvastatin (CYP3A4 substrate) → ↑ statin levels → rhabdomyolysis."))
story.append(b2("Ketoconazole + Terfenadine → ↑ terfenadine → QT prolongation → torsades de pointes."))
story.append(b2("Cimetidine + Warfarin → ↑ warfarin → bleeding."))
story.append(b2("Grapefruit juice + Nifedipine/Ciclosporin → ↑ drug levels → toxicity."))
story.append(sp(4))

story.append(sub("Genetic Variability (Genetic Polymorphisms)"))
story.append(tbl(
    ["Enzyme", "Polymorphism", "Slow Metaboliser Consequence", "Fast Metaboliser Consequence", "Affected Drugs"],
    [
        ["N-acetyltransferase (NAT2)", "Slow vs Fast acetylators. Slow acetylators more common in Europeans (~50%), Fast acetylators in Japanese/Egyptians.",
         "↑ Drug accumulation → toxicity. e.g., INH → peripheral neuropathy; Hydralazine → drug-induced SLE.",
         "↓ Drug levels → ↓ efficacy; INH may fail.",
         "INH, Dapsone, Hydralazine, Procainamide, Sulfonamides"],
        ["CYP2D6", "Poor Metabolisers (PM) ~7–10% Caucasians; Ultra-Rapid Metabolisers (UM) ~5%.",
         "↑ Codeine, tricyclic levels → toxicity.",
         "Codeine → rapid morphine conversion → opioid toxicity (UM). Inadequate analgesia in PM.",
         "Codeine, Tamoxifen, Metoprolol, Tricyclics, Antipsychotics"],
        ["CYP2C9", "Poor Metabolisers (~1–3%).",
         "↑ Warfarin, Phenytoin → toxicity with standard doses. ↑ NSAID levels.",
         "Underdosing.",
         "Warfarin, Phenytoin, NSAIDs, Sulfonylureas"],
        ["CYP2C19", "Poor Metabolisers (~15–20% Asians, 3–5% Caucasians).",
         "↑ PPI levels → better acid suppression. Clopidogrel → poor activation → ↑ CV events.",
         "Clopidogrel → adequate activation.",
         "Clopidogrel (prodrug), PPIs, Diazepam"],
        ["Pseudocholinesterase", "Genetic deficiency (1:3000).",
         "Suxamethonium apnoea: prolonged paralysis after suxamethonium.",
         "N/A",
         "Suxamethonium, Mivacurium, Procaine"],
        ["TPMT (Thiopurine methyltransferase)", "Low activity (~1:300).",
         "↑ 6-mercaptopurine → severe myelosuppression.",
         "N/A",
         "Azathioprine, 6-mercaptopurine"],
    ],
    [2.5*cm, 4*cm, 3.5*cm, 3*cm, 4*cm]
))
story.append(sp(4))
story.append(tip("CYP2D6 poor metabolisers cannot activate codeine to morphine → no analgesia. Ultra-rapid metabolisers convert codeine → morphine very rapidly → opioid toxicity. This is a classic pharmacogenomics exam question."))
story.append(sp(4))

story.append(sub("First-Pass Metabolism"))
story.append(b("(Covered in detail in Section 5c above.)"))
story.append(sp(4))

story.append(sub("Age Effects on Metabolism"))
story.append(tbl(
    ["Age Group", "Metabolic Status", "Key Consequences"],
    [
        ["Neonates / Premature infants",
         "CYP450 enzymes (~30–70% of adult capacity); UGT (glucuronidation) immature; hepatic blood flow lower.",
         "Chloramphenicol → Grey Baby Syndrome. Morphine → prolonged respiratory depression. ALL doses must be reduced."],
        ["Infants (1–12 months)",
         "CYP activity matures rapidly; some exceed adult levels by 6–12 months.",
         "May need higher mg/kg doses for some drugs (e.g., theophylline faster metabolised in children)."],
        ["Children (1–12 years)",
         "Metabolic rate per kg may exceed adults; liver mass/body weight ratio higher.",
         "Higher weight-adjusted doses sometimes needed."],
        ["Elderly (>65 years)",
         "↓ Hepatic blood flow (40%), ↓ liver mass, ↓ CYP activity, ↓ phase II capacity; ↓ albumin.",
         "↑ Drug levels, ↑ half-lives. ↑ ADR risk. Reduce doses: diazepam, codeine, warfarin, antidepressants."],
    ],
    [3*cm, 5*cm, 9*cm]
))
story.append(sp(6))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 6 – EXCRETION
# ════════════════════════════════════════════════════════════════════
story.append(chapter_bar("6. EXCRETION — FACTORS AFFECTING EXCRETION"))
story.append(sp(6))
story.append(p(
    "<b>Excretion</b> = irreversible removal of drug or its metabolites from the body. "
    "Primary route: <b>kidneys (urine)</b>. Other routes: bile/faeces, lungs, saliva, sweat, breast milk.", BODY))
story.append(sp(4))

story.append(sec("6a. Renal Excretion (Primary Route)"))
story.append(sp(3))
story.append(p("Three processes involved in renal handling of drugs:", BODY))
story.append(sp(3))
story.append(tbl(
    ["Process", "Mechanism", "Which Drugs?", "Can It Be Manipulated?"],
    [
        ["<b>1. Glomerular Filtration</b>",
         "Passive filtration at glomerulus. Driven by hydrostatic pressure. MW <20,000 Da can be filtered. Only FREE (unbound) drug is filtered — protein-bound drug is not.",
         "Most drugs and metabolites. NOT large proteins, NOT highly protein-bound drugs (e.g., heparin, warfarin).",
         "GFR affected by renal blood flow, renal disease, age. In renal failure: ↓ GFR → ↓ drug excretion → accumulation → toxicity."],
        ["<b>2. Tubular Secretion</b>",
         "Active transport from peritubular capillaries into tubular lumen. Two systems: (i) Organic acid (anion) transporter — secretes acidic drugs; (ii) Organic base (cation) transporter — secretes basic drugs. Saturable; can be competitively inhibited.",
         "Acidic: Penicillin, methotrexate, NSAIDs, thiazides, probenecid. Basic: Morphine, quinine, procainamide.",
         "Probenecid competitively inhibits OAT → ↓ penicillin secretion → ↑ penicillin levels (therapeutic use). Also inhibits methotrexate secretion → ↑ methotrexate toxicity."],
        ["<b>3. Tubular Reabsorption</b>",
         "Passive diffusion of lipid-soluble, un-ionised drug from tubular fluid back into blood (works against excretion). Only occurs if drug concentration in tubule > blood.",
         "Lipid-soluble, un-ionised drugs. Highly ionised polar metabolites are NOT reabsorbed.",
         "Urinary pH manipulation (ion trapping): Alkalinise urine (NaHCO₃) for weak acid poisoning (aspirin, phenobarbitone) → drug ionises → less reabsorption → ↑ excretion. Acidify urine (NH₄Cl) for weak base poisoning (amphetamine, quinine) → drug ionises → less reabsorption → ↑ excretion."],
    ],
    [2.5*cm, 4.5*cm, 4.5*cm, 5.5*cm]
))
story.append(sp(4))

story.append(colbox([
    "ALKALINISE URINE (NaHCO₃): Aspirin poisoning, Phenobarbitone poisoning — ionises acidic drug → trapped in urine → faster excretion.",
    "ACIDIFY URINE (NH₄Cl / Vit C): Amphetamine poisoning, Quinine poisoning — ionises basic drug → trapped in urine → faster excretion.",
    "Remember: ION TRAPPING — you trap the drug in the compartment where it is IONISED.",
    "Forced diuresis (IV fluids + diuretics) combined with pH manipulation enhances renal drug excretion in poisoning.",
], title="Ion Trapping in Poisoning — Must Know!", bg=LRED, border=RED))
story.append(sp(5))

story.append(sec("6b. Biliary / Hepatic Excretion"))
story.append(sp(3))
story.append(b("Liver secretes drugs and metabolites into bile via active transport (OAT, P-gp)."))
story.append(b("Drugs excreted in bile → enter gut → may be reabsorbed (enterohepatic recycling) → prolongs drug action."))
story.append(b("<b>Drugs with significant enterohepatic cycling:</b> Rifampicin, Oestrogens (OCP), Digoxin, Tetracycline, Chloramphenicol, Morphine glucuronide."))
story.append(b("<b>Clinical Implication:</b> Antibiotics (e.g., ampicillin) disrupt gut flora → ↓ deconjugation of oestrogen metabolites → ↓ reabsorption → ↓ OCP efficacy → contraceptive failure (combined with enzyme induction)."))
story.append(b("Cholestyramine interrupts enterohepatic recycling of digoxin → useful in digoxin toxicity."))
story.append(sp(4))

story.append(tbl(
    ["Hepatic Excretion Factor", "Details"],
    [
        ["Molecular weight",       "MW >500 Da favours biliary excretion. Small MW drugs → more renal excretion."],
        ["Polarity",               "Polar conjugates (glucuronides, sulfates) actively secreted into bile."],
        ["Active transport",       "OAT, MDR (P-gp) transporters in canalicular membrane. Inhibition → ↓ biliary excretion → ↑ plasma levels."],
        ["Liver disease",          "Cirrhosis, cholestasis → ↓ biliary secretion → ↑ drug accumulation. Dose adjustment required."],
    ],
    [4*cm, 13*cm]
))
story.append(sp(4))

story.append(sec("6c. Other Routes of Excretion"))
story.append(sp(3))
story.append(tbl(
    ["Route", "Mechanism", "Drugs / Examples", "Clinical Importance"],
    [
        ["Lungs",        "Exhalation of volatile substances; proportional to blood/gas partition coefficient", "Volatile anaesthetics (halothane, isoflurane), Ethanol, Acetone (DKA)", "Breathalyser test (ethanol in expired air) is proportional to blood alcohol level"],
        ["Breast milk",  "Passive diffusion of lipid-soluble, un-ionised, low MW drugs; pH of milk (6.8) favours basic drugs",
         "Alcohol, Nicotine, Caffeine, Metronidazole, Lithium, Chloramphenicol, Tetracycline, Amiodarone, Anticancer drugs",
         "Neonates can be exposed via breast milk. Contraindicated in breastfeeding: Metronidazole, Lithium, Chloramphenicol, Anticancer agents, Amiodarone"],
        ["Saliva",       "Passive diffusion; useful for therapeutic drug monitoring (non-invasive)", "Phenytoin, Carbamazepine, Theophylline", "Saliva drug levels correlate with free plasma levels"],
        ["Sweat",        "Minor route; passive diffusion", "Rifampicin (orange sweat), Heavy metals", "Rifampicin stains all body fluids orange — warn patients"],
        ["Tears",        "Passive diffusion", "Rifampicin (orange tears)", "Contacts lenses may be stained — warn patients"],
    ],
    [1.8*cm, 4*cm, 4.5*cm, 6.7*cm]
))
story.append(sp(4))
story.append(tip("Drugs CONTRAINDICATED in breastfeeding — Mnemonic: 'LATCH' — Lithium, Amiodarone, Tetracycline (and doxycycline), Chloramphenicol, High-dose/anticancer drugs + Metronidazole."))
story.append(sp(5))

story.append(sec("6d. Patient-Related Factors Affecting Excretion"))
story.append(sp(3))
story.append(tbl(
    ["Factor", "Effect on Excretion", "Key Examples & Clinical Action"],
    [
        ["<b>Renal Function</b>",
         "↓ GFR (CKD, AKI) → ↓ drug excretion → drug accumulation → toxicity. Monitor with serum creatinine, GFR (eGFR).",
         "Aminoglycosides: reduce dose + increase dosing interval in renal failure (renal + ototoxicity risk). Digoxin, Metformin (lactic acidosis risk — stop if eGFR <30), Methotrexate, Lithium: all require dose adjustment in renal impairment."],
        ["<b>Hepatic Function</b>",
         "Liver disease → ↓ bile secretion, ↓ protein synthesis (↑ free drug), altered hepatic blood flow.",
         "Morphine, Metronidazole, Rifampicin, Warfarin, Phenytoin: all need dose reduction in liver failure. Hepatic Extraction Ratio (HER): high HER drugs (lidocaine, propranolol) → very sensitive to ↓ hepatic blood flow."],
        ["<b>Age</b>",
         "Neonates: ↓ GFR (~30% of adult), ↓ tubular secretion. Elderly: GFR declines ~1% per year after 30 (serum creatinine may be normal due to ↓ muscle mass). GFR may be <30 mL/min even with 'normal' creatinine.",
         "Penicillin: 12-hourly in infants (immature renal excretion) vs 6-hourly in adults. Gentamicin, digoxin: lower doses in elderly. Cockcroft-Gault formula estimates CrCl for dose adjustment."],
        ["<b>Gender</b>",
         "Women: Generally lower renal clearance for some drugs (~10–15% lower GFR); differences in body composition (higher %fat), different hormone levels affecting P-gp and CYP activity.",
         "Women have higher risk of QT prolongation with QT-prolonging drugs (erythromycin, quinidine). Methotrexate: women have higher drug levels."],
        ["<b>Genetic Variations</b>",
         "Polymorphisms in transporters (OAT, P-gp/MDR1) affect renal and biliary secretion.",
         "SLCO1B1 polymorphism → ↓ hepatic uptake of statins → ↑ plasma statin levels → myopathy risk."],
        ["<b>Disease States</b>",
         "Heart failure: ↓ renal blood flow → ↓ GFR → ↓ drug excretion. Dehydration: ↑ drug concentration → ↑ toxicity. Alkalosis/acidosis: alters urinary pH → alters tubular reabsorption.",
         "Digoxin toxicity in heart failure (↓ renal excretion). Lithium toxicity in dehydration (Na⁺ depletion → ↑ lithium reabsorption). NSAIDs in heart failure → ↓ renal prostaglandins → acute kidney injury."],
        ["<b>Lifestyle Factors</b>",
         "Diet, exercise, smoking, alcohol all affect excretion indirectly.",
         "High-protein diet ↑ hepatic blood flow → ↑ first-pass metabolism → ↓ bioavailability of some drugs. Smoking (polycyclic hydrocarbons) induces CYP1A2 → ↑ theophylline metabolism (smokers need higher theophylline doses). Sodium restriction → ↑ lithium reabsorption → ↑ lithium levels → toxicity."],
    ],
    [3*cm, 5*cm, 9*cm]
))
story.append(sp(4))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 7 – KEY PK PARAMETERS
# ════════════════════════════════════════════════════════════════════
story.append(chapter_bar("7. KEY PHARMACOKINETIC PARAMETERS"))
story.append(sp(6))

story.append(tbl(
    ["Parameter", "Symbol", "Definition", "Formula", "Clinical Significance"],
    [
        ["Bioavailability",      "F",    "Fraction of dose reaching systemic circulation unchanged",
         "F = AUC(oral) / AUC(IV) × 100%",
         "IV = 100%. Oral F reduced by poor absorption + first-pass metabolism. Low F drugs need higher oral doses."],
        ["Volume of Distribution", "Vd", "Apparent volume the drug distributes into (not a real volume)",
         "Vd = Dose / Cp₀ (initial plasma conc.)",
         "Low Vd (~4 L) = plasma only (heparin). High Vd (hundreds of L) = extensive tissue binding (chloroquine, amiodarone, digoxin)."],
        ["Clearance",           "Cl",   "Volume of plasma cleared of drug per unit time",
         "Cl = Dose / AUC or Cl = Vd × Ke",
         "Determines maintenance dose. If Cl ↓ (renal/liver failure) → dose reduction needed."],
        ["Half-life",           "t½",   "Time for plasma drug concentration to fall by 50%",
         "t½ = 0.693 × Vd / Cl",
         "Determines dosing interval + time to steady state (4–5 half-lives). Does NOT change with dose in first-order kinetics."],
        ["Steady State",        "Css",  "Plasma concentration when rate of administration = rate of elimination",
         "Reached after ~4–5 × t½",
         "For drugs with long t½ (digoxin t½ ~36 h), takes days to weeks to reach Css. Loading dose used to reach Css faster."],
        ["Loading Dose",        "LD",   "Initial large dose to rapidly attain target Css",
         "LD = Target Css × Vd / F",
         "Used for: Digoxin (t½ 36h), Amiodarone (t½ weeks), Lidocaine (in VT), Phenytoin (in status epilepticus). Without LD, takes too long to reach therapeutic levels."],
        ["Maintenance Dose",    "MD",   "Dose to maintain Css at steady state",
         "MD = Target Css × Cl / F",
         "Accounts for clearance. Must be adjusted for renal/hepatic failure."],
        ["AUC (Area Under Curve)", "AUC", "Total drug exposure over time — measure of systemic exposure",
         "AUC = Dose / Cl",
         "Used to calculate F, clearance, and in bioequivalence studies."],
    ],
    [2.5*cm, 1.2*cm, 3.5*cm, 4*cm, 6.3*cm]
))
story.append(sp(4))

story.append(sec("Orders of Elimination Kinetics"))
story.append(sp(3))
story.append(tbl(
    ["Feature", "First-Order Kinetics", "Zero-Order Kinetics"],
    [
        ["Rate of elimination", "Constant FRACTION eliminated per unit time", "Constant AMOUNT eliminated per unit time"],
        ["Plasma level vs time", "Exponential decrease (straight line on semi-log plot)", "Linear decrease"],
        ["Half-life", "CONSTANT — independent of dose or concentration", "NOT constant — increases as dose increases"],
        ["Enzyme status", "Enzymes NOT saturated", "Enzymes ARE saturated"],
        ["Dose proportionality", "Doubling dose → doubles AUC proportionally", "Small ↑ in dose → disproportionate large ↑ in plasma levels → toxicity"],
        ["Examples", "Most drugs at therapeutic doses", "Ethanol, Phenytoin (high doses), Aspirin (toxic doses)"],
        ["TDM needed?", "Usually not unless narrow TI", "YES — especially phenytoin (TDM essential)"],
    ],
    [4*cm, 6.5*cm, 6.5*cm]
))
story.append(sp(4))
story.append(colbox([
    "Phenytoin shows MIXED (Michaelis-Menten / saturation) kinetics: First-order at low concentrations, Zero-order at higher concentrations.",
    "Above ~10 mg/L plasma level of phenytoin → small dose increments → LARGE rises in plasma level → seizures/toxicity.",
    "Therefore phenytoin MUST be monitored by Therapeutic Drug Monitoring (TDM).",
    "Other drugs needing TDM: Digoxin, Lithium, Aminoglycosides, Vancomycin, Cyclosporin, Theophylline, Warfarin (via INR).",
], title="Phenytoin Kinetics & TDM — High-Yield", bg=LPURPLE, border=PURPLE))
story.append(sp(6))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 8 – DRUG-DRUG INTERACTIONS
# ════════════════════════════════════════════════════════════════════
story.append(chapter_bar("8. DRUG–DRUG INTERACTIONS (Pharmacokinetic Basis)"))
story.append(sp(6))
story.append(p(
    "Pharmacokinetic drug–drug interactions (DDIs) occur when one drug alters the ADME of another drug. "
    "These are distinct from pharmacodynamic interactions (which occur at the receptor/target level).", BODY))
story.append(sp(4))

story.append(tbl(
    ["PK Phase", "Interaction Mechanism", "Drug A (Perpetrator)", "Drug B (Victim)", "Outcome"],
    [
        ["Absorption",    "Drug A slows GI motility → delayed absorption of Drug B",
         "Opioids, Anticholinergics", "Most oral drugs", "Delayed onset; sometimes ↓ extent"],
        ["Absorption",    "Drug A chelates Drug B in GI tract → prevents absorption",
         "Antacids (Ca²⁺, Mg²⁺, Al³⁺), Milk (Ca²⁺), Iron supplements",
         "Tetracyclines, Fluoroquinolones (Cipro), Bisphosphonates",
         "↓ Absorption → ↓ efficacy. Give 2 hours apart."],
        ["Absorption",    "Drug A accelerates gastric emptying → ↑ absorption rate of Drug B",
         "Metoclopramide",
         "Paracetamol, alcohol",
         "↑ Rate of absorption → earlier peak levels"],
        ["Distribution",  "Drug A displaces Drug B from plasma protein binding → ↑ free Drug B",
         "Aspirin, Sulfonamides",
         "Warfarin, Phenytoin, Bilirubin",
         "↑ Free warfarin → bleeding; ↑ free phenytoin → toxicity; Kernicterus in neonates"],
        ["Metabolism",    "Drug A induces CYP450 → ↑ metabolism of Drug B → ↓ Drug B levels",
         "Rifampicin, Phenytoin, Carbamazepine, Phenobarbitone",
         "Warfarin, OCP, Ciclosporin, Statins, Antiretrovirals",
         "↓ Drug B efficacy: contraceptive failure, transplant rejection, thrombosis"],
        ["Metabolism",    "Drug A inhibits CYP450 → ↓ metabolism of Drug B → ↑ Drug B levels",
         "Ketoconazole, Erythromycin, Cimetidine, Grapefruit juice, Ritonavir",
         "Statins (simvastatin), Warfarin, Ciclosporin, Terfenadine",
         "↑ Drug B toxicity: rhabdomyolysis, bleeding, QT prolongation, nephrotoxicity"],
        ["Excretion",     "Drug A competitively inhibits tubular secretion of Drug B → ↑ Drug B levels",
         "Probenecid",
         "Penicillin, Methotrexate, NSAIDs",
         "Used therapeutically (↑ penicillin): Probenecid given with penicillin. DANGER: probenecid + methotrexate → methotrexate toxicity."],
        ["Excretion",     "Drug A alters urinary pH → alters tubular reabsorption of Drug B",
         "NaHCO₃ (alkalinises), NH₄Cl (acidifies)",
         "Acidic drugs (aspirin, phenobarb), Basic drugs (amphetamine)",
         "Used in poisoning treatment to enhance elimination."],
        ["Excretion",     "Drug A ↓ renal blood flow → ↓ Drug B clearance → ↑ Drug B levels",
         "NSAIDs (↓ prostaglandin-mediated vasodilation)",
         "Lithium, Methotrexate, Aminoglycosides",
         "↑ Lithium toxicity (NSAIDs + Lithium is a classic interaction)"],
    ],
    [1.8*cm, 3.5*cm, 3.2*cm, 3.2*cm, 5.3*cm]
))
story.append(sp(4))

story.append(sub("Patient-Related Factors in Drug Interactions"))
story.append(b("<b>Polypharmacy</b> (≥5 drugs): Exponentially increases the risk of DDIs. Elderly patients on multiple drugs are at highest risk."))
story.append(b("<b>Age:</b> Elderly have reduced metabolic and excretory reserve → DDIs more likely to cause toxicity."))
story.append(b("<b>Genetic polymorphisms:</b> CYP2D6 poor metabolisers have higher baseline drug levels → interaction more likely to cause toxicity."))
story.append(b("<b>Hepatic/Renal disease:</b> Impaired drug handling amplifies PK interactions."))
story.append(b("<b>Nutritional status:</b> Hypoalbuminaemia → ↑ free drug fraction → amplifies displacement interactions."))
story.append(sp(6))
story.append(PageBreak())

# ════════════════════════════════════════════════════════════════════
# SECTION 9 – QUICK REVISION
# ════════════════════════════════════════════════════════════════════
story.append(chapter_bar("9. QUICK REVISION — HIGH-YIELD FACTS & MNEMONICS"))
story.append(sp(6))

story.append(tbl(
    ["Topic", "Mnemonic / Key Fact"],
    [
        ["ADME",
         "A = Absorption (entry into blood), D = Distribution (spread to tissues), M = Metabolism (biotransformation), E = Excretion (removal from body)."],
        ["Drug transport",
         "Passive diffusion: no energy, no carrier, high→low. Active transport: energy, carrier, low→high (e.g., levodopa)."],
        ["Un-ionised form",
         "Crosses membranes better (lipid-soluble). Weak acids un-ionised in acidic (stomach). Weak bases un-ionised in alkaline (intestine)."],
        ["1st-pass metabolism drugs",
         "Mnemonic 'GPMLA': GTN (<1%), Propranolol (~30%), Morphine (~30–40%), Lidocaine (~70%), Aspirin (moderate)."],
        ["Routes bypassing 1st pass",
         "IV, IM, SC, Sublingual, Transdermal, Inhalation, Rectal (partial)."],
        ["Enzyme Inducers",
         "'RIPS PC3' — Rifampicin, Isoniazid (weak), Phenytoin, St. John's Wort, Phenobarbitone, Carbamazepine, Chronic alcohol, Cigarette smoke. → ↓ drug levels → therapeutic failure."],
        ["Enzyme Inhibitors",
         "'CAGE KIM' — Cimetidine, Amiodarone, Grapefruit juice, Erythromycin, Ketoconazole/Itraconazole, Isoniazid (acute), Metronidazole/Fluconazole. → ↑ drug levels → toxicity."],
        ["CYP3A4",
         "Most important; metabolises >50% of all drugs. Inhibited by grapefruit juice (intestinal CYP3A4). Strongly induced by rifampicin."],
        ["Phase I vs Phase II",
         "Phase I = Functionalization (CYP450: oxidation most common). Phase II = Conjugation (Glucuronidation most common). Phase II usually = inactive + polar = excreted."],
        ["Morphine-6-glucuronide",
         "Phase II metabolite more potent than parent drug (exception to Phase II = inactivation rule)."],
        ["Paracetamol toxicity",
         "OD → CYP2E1 pathway → NAPQI (toxic) → depletes GSH → hepatotoxicity (Zone 3 necrosis). Antidote: NAC (replenishes GSH). Most effective within 8–10 hours."],
        ["Grey baby syndrome",
         "Chloramphenicol in neonates. Immature UDP-glucuronosyltransferase → chloramphenicol accumulation → vascular collapse, cyanosis."],
        ["G6PD deficiency",
         "Primaquine, Dapsone, Nitrofurantoin, Chloroquine → haemolytic anaemia. Mechanism: ↓ NADPH → ↓ reduced glutathione → oxidative Hb damage."],
        ["Suxamethonium apnoea",
         "Pseudocholinesterase deficiency (1:3000) → prolonged paralysis. Test: Dibucaine number (normal ~80; homozygous atypical ~20)."],
        ["Slow vs Fast acetylators",
         "INH: Slow acetylators → peripheral neuropathy + ↑ drug levels. Fast acetylators → ↓ efficacy. Hydralazine slow acetylators → drug-induced SLE."],
        ["Clopidogrel",
         "Prodrug — requires CYP2C19 activation. CYP2C19 poor metabolisers (Asian >15%) → inadequate platelet inhibition → ↑ cardiovascular events. PPIs (omeprazole) inhibit CYP2C19 → ↓ clopidogrel activation."],
        ["BBB",
         "Only lipid-soluble, un-ionised, small MW, non-protein-bound drugs cross. Dopamine does NOT cross → give levodopa. In meningitis: BBB permeability ↑ → penicillin can enter."],
        ["Placenta",
         "Heparin does NOT cross (large MW) — preferred anticoagulant in pregnancy. Warfarin crosses → teratogenic."],
        ["Ion trapping in poisoning",
         "Acid poisoning (aspirin) → NaHCO₃ to alkalinise urine → ionises drug → trapped → excreted. Base poisoning (amphetamine) → NH₄Cl to acidify urine → ionises drug → trapped → excreted."],
        ["Enterohepatic recycling",
         "OCP + Antibiotics → kill gut flora → ↓ oestrogen deconjugation → ↓ reabsorption → ↓ OCP efficacy → contraceptive failure."],
        ["Plasma protein binding DDI",
         "Only significant if: >90% protein bound + small Vd + narrow TI. Classic: Warfarin displaced by aspirin → ↑ free warfarin → bleeding."],
        ["TDM drugs",
         "Phenytoin, Digoxin, Lithium, Aminoglycosides, Vancomycin, Cyclosporin, Theophylline, Warfarin (INR), Methotrexate."],
        ["t½ and steady state",
         "Steady state reached after 4–5 × t½ regardless of dose or frequency."],
        ["Renal failure key drugs",
         "Aminoglycosides (nephrotoxic + ototoxic), Metformin (lactic acidosis — stop if eGFR <30), Digoxin, Lithium, NSAIDs (avoid), Methotrexate — ALL need dose reduction/avoidance."],
        ["NSAIDs + Lithium",
         "NSAIDs ↓ renal prostaglandins → ↓ renal blood flow → ↓ lithium excretion → ↑ lithium levels → toxicity. Classic DDI."],
        ["Transdermal drug delivery",
         "Bypasses 1st pass; sustained levels; only lipid-soluble drugs. GTN (24h), Fentanyl (72h), Nicotine, Oestradiol. Heat ↑ absorption from patches (e.g., fentanyl toxicity with fever)."],
    ],
    [4.5*cm, 12.5*cm]
))
story.append(sp(8))
story.append(hr(NAVY, 2))
story.append(p(
    "End of Pharmacokinetics (ADME) Notes  |  Source: Tara V. Shanbhag & Smita Shenoy, Pharmacology for Medical Graduates, 3rd Edition",
    S("foot", fontName="Helvetica-Oblique", fontSize=7.5,
      textColor=colors.HexColor("#9e9e9e"), alignment=TA_CENTER)))

# ════════════════════════════════════════════════════════════════════
doc.build(story)
print(f"PDF saved: {OUTPUT}")
Your credits are exhausted. Your daily credits reset tomorrow, or you can purchase a top-up for more.

Make a noted

Your credits are exhausted. Your daily credits reset tomorrow, or you can purchase a top-up for more.
This is a shared conversation. Sign in to Orris to start your own chat.