Explain me 10 common heart diseases with ECG Changes and ecg images of those diseases

Reading File
Finding Sources
Finding Sources
Searching the Web

common heart diseases ECG changes with ECG images examples

Finding Sources
Finding Sources
Finding Sources
Loading Image
Searching the Web

ECG images STEMI atrial fibrillation ventricular tachycardia heart block WPW pericarditis site:litfl.com OR site:ecgwaves.com

Reading File
Reading File
Loading Image
Searching the Web

ECG images atrial fibrillation STEMI complete heart block ventricular tachycardia pericarditis litfl.com

Loading Image
Loading Image
Loading Image
Searching the Web

STEMI ECG inferior anterior ventricular tachycardia WPW atrial flutter ECG image litfl.com

Loading Image
Loading Image
Loading Image
Finding Sources
Finding Sources
Loading Image
Searching the Web

ventricular tachycardia ECG hypertrophic cardiomyopathy ECG WPW delta wave ECG image site:litfl.com

I have excellent content and images now. Let me compile the complete, comprehensive answer:

10 Common Heart Diseases with ECG Changes

Here is a comprehensive guide to 10 major cardiac conditions, their ECG findings, and reference images from medical textbooks and the LITFL ECG Library.

Quick ECG Reference Overview

Killer ECG Patterns Infographic - LITFL
Overview of killer ECG patterns including ARVD, Brugada, WPW, HCM, and pericardial effusion (LITFL ECG Library)

1. ST-Elevation Myocardial Infarction (STEMI)

Overview: STEMI results from complete occlusion of a coronary artery, causing transmural myocardial ischemia and necrosis.
ECG Changes:
  • Hyperacute T waves - the earliest finding, tall and peaked, in the affected leads
  • ST segment elevation ≥1 mm in 2+ contiguous limb leads or ≥2 mm in precordial leads
  • Pathological Q waves - develop after hours/days; represent electrically silent necrotic tissue (width >0.04s, depth >25% of R wave)
  • Reciprocal ST depression in mirror leads
  • T wave inversion in subacute/chronic phase
Localization by leads:
TerritoryArteryLeads with ST Elevation
AnteriorLADV1-V4
InferiorRCA/LCxII, III, aVF
LateralLCxI, aVL, V5-V6
PosteriorRCAST depression V1-V3 (mirror)
The mechanism: infarcted fibers rapidly repolarize and have decreased resting membrane potential. Both changes cause current flowing toward the infarcted zone, producing the hallmark ST elevation in overlying leads. - Ganong's Review of Medical Physiology, p. 534
ECG Image - Inferior STEMI ("tombstoning"):
Inferior STEMI with massive tombstone ST elevations
Inferior STEMI: massive tombstone ST elevations in II, III, aVF with reciprocal changes in I, aVL. (LITFL ECG Library)

2. Atrial Fibrillation (AF)

Overview: The most common sustained arrhythmia. Disorganized electrical activation of the atria leads to irregular ventricular response.
ECG Changes:
  • No discernible P waves - replaced by chaotic fibrillatory baseline (f waves, 350-600 bpm)
  • Irregularly irregular RR intervals - the hallmark finding
  • Variable ventricular rate (typically 100-180 bpm if uncontrolled)
  • Normal QRS morphology (unless aberrant conduction or pre-existing bundle branch block)
  • Fine (low voltage) or coarse (high voltage) fibrillatory baseline
The irregular rhythm arises because AV node conduction is random. At least 0.35 seconds must elapse between ventricular contractions, but the next fibrillatory impulse can arrive at any time, producing intervals varying from 0.35 to 0.95 seconds. - Guyton and Hall Textbook of Medical Physiology
ECG Image - Atrial Fibrillation:
Atrial Fibrillation ECG - irregularly irregular rhythm
AF (Lead II): no P waves, irregular QRS complexes. Ventricular QRS and T waves are visible; P waves replaced by fibrillatory baseline. (Guyton & Hall Textbook of Medical Physiology)

3. Atrial Flutter

Overview: A macro-reentrant atrial arrhythmia, typically with a right atrial circuit turning at ~300 bpm.
ECG Changes:
  • Sawtooth flutter waves at ~300 bpm (range 250-350 bpm) - best seen in II, III, aVF and V1
  • Regular atrial activity with negative flutter waves in inferior leads (II, III, aVF) in typical counterclockwise flutter
  • Ventricular rate = fraction of atrial rate: most commonly 2:1 block (150 bpm), can be 3:1, 4:1, or variable
  • No isoelectric baseline between flutter waves
  • QRS is usually narrow and normal unless aberrancy exists
ECG Image - Atrial Flutter with 2:1 block:
Atrial Flutter 2:1 block ECG
Atrial flutter with 2:1 AV conduction: sawtooth flutter waves clearly seen in inferior leads, ventricular rate ~150 bpm. (LITFL ECG Library)

4. Complete (3rd Degree) AV Heart Block

Overview: Complete failure of conduction from atria to ventricles. The atria and ventricles beat independently at their own rates.
ECG Changes:
  • Complete AV dissociation: P waves and QRS complexes are completely independent
  • Atrial rate > ventricular rate (e.g., P rate 70-100 bpm, ventricular escape 30-60 bpm)
  • Escape rhythm: junctional escape (narrow QRS, 40-60 bpm) or ventricular escape (wide QRS, 20-40 bpm)
  • Wide QRS if escape focus is ventricular (below His bundle)
  • No fixed PR interval relationship
Schematic diagram:
3rd degree heart block diagram showing P-R dissociation
Complete heart block: P waves (upward arrows) march through independently of QRS complexes (downward arrows). P rate > ventricular escape rate. (LITFL ECG Library)
Full 12-lead ECG - Complete Heart Block:
Complete Heart Block 12-lead ECG
12-lead ECG in complete heart block: regular, slow ventricular escape rhythm with P waves marching through at a faster independent rate. (LITFL ECG Library)

5. Acute Pericarditis

Overview: Inflammation of the pericardial sac, typically viral, producing diffuse myocardial surface irritation.
ECG Changes (evolve through 4 stages):
StageTimingECG Finding
Stage 1Hours-daysDiffuse concave-up (saddle-shaped) ST elevation in all leads except aVR and V1; PR depression in most leads; PR elevation in aVR
Stage 2~1 weekST and PR return to baseline; T wave flattening
Stage 3After ST normalizesDiffuse T wave inversion
Stage 4Weeks-monthsNormalization (or persistent T inversion)
Key distinguishing points from STEMI: ST elevation is diffuse (not regional), concave up (not convex), and accompanied by PR depression. Reciprocal ST depression is absent except in aVR/V1.
ECG Image - Acute Pericarditis:
Pericarditis ECG showing diffuse ST elevation and PR depression
Acute pericarditis: diffuse concave ST elevation across multiple leads with PR depression - classic saddle shape. (LITFL ECG Library)

6. Wolff-Parkinson-White (WPW) Syndrome

Overview: Pre-excitation syndrome caused by an accessory pathway (Bundle of Kent) that bypasses the AV node and conducts impulses faster, causing early ventricular activation (pre-excitation).
ECG Changes (in sinus rhythm):
  • Short PR interval <120 ms (no AV nodal delay)
  • Delta wave - slurred upstroke at the beginning of the QRS, representing pre-excitation of ventricular myocardium
  • Wide QRS >120 ms (total QRS = delta + normal activation)
  • Secondary ST-T changes discordant to QRS direction
  • Pseudo-infarct pattern possible (mimics Q waves)
During tachyarrhythmias (AF with WPW):
  • Extremely rapid ventricular rate (>200 bpm), potentially fatal
  • Irregularly irregular, wide, and bizarre QRS complexes
  • Risk of VF
ECG Image - AF in WPW (pre-excited AF):
WPW with Atrial Fibrillation ECG - pre-excited AF
AF in WPW: chaotic, extremely rapid, irregularly irregular, wide QRS complexes - a life-threatening arrhythmia. Rate well above 200 bpm. (LITFL ECG Library)

7. Ventricular Tachycardia (VT)

Overview: Three or more consecutive ventricular beats at >100 bpm originating below the bundle of His. Can be monomorphic (uniform QRS) or polymorphic.
ECG Changes:
  • Wide QRS >120 ms (usually >140 ms)
  • Regular rhythm, typically 100-250 bpm
  • AV dissociation - P waves march through independently (seen in ~50% of cases)
  • Fusion beats - partial activation from sinus + VT origin (pathognomonic)
  • Capture beats - rare sinus captures that produce narrow QRS (pathognomonic)
  • Extreme axis deviation
  • Concordance in precordial leads (all positive or all negative)
Brugada criteria help distinguish VT from SVT with aberrancy:
  • Absence of RS in all precordial leads → VT
  • RS interval >100 ms in any precordial lead → VT
  • AV dissociation → VT
  • Morphology criteria not met for SVT → VT
The VT ECG (see Atrial Flutter 12-lead above as context) and the Killer Rhythms infographic above show the wide complex morphology.

8. Hypertrophic Cardiomyopathy (HCM)

Overview: Genetic cardiomyopathy with asymmetric myocardial hypertrophy (typically interventricular septum). Leading cause of sudden cardiac death in young athletes.
ECG Changes:
  • Left ventricular hypertrophy (LVH) voltage criteria: SV1 + RV5/V6 >35 mm (Sokolow-Lyon)
  • Deep, narrow Q waves ("dagger Q waves") in lateral leads (I, aVL, V5-V6) and inferior leads - due to septal hypertrophy
  • T wave inversion - widespread, often striking
  • Left axis deviation
  • ST depression in lateral leads
  • Apical HCM pattern: giant T wave inversions in precordial leads (V3-V5), up to 10-15 mm deep
ECG Image - HCM:
Hypertrophic Cardiomyopathy ECG with LVH and dagger Q waves
HCM ECG: LVH, deep Q waves in lateral leads, widespread ST depression and T wave inversion. (LITFL ECG Library)

9. Brugada Syndrome

Overview: Inherited sodium channelopathy causing life-threatening ventricular arrhythmias and sudden cardiac death, often in young males, often during sleep.
ECG Changes (Type 1 is diagnostic):
TypePatternDiagnostic?
Type 1Coved ST elevation ≥2 mm in V1-V3, descending into negative T waveYes
Type 2Saddleback ST elevation ≥2 mm in V1-V3, positive T waveRequires provocation
Type 3ST elevation <1 mm, either coved or saddleNot diagnostic
Additional features:
  • Right bundle branch block (RBBB) pattern
  • Spontaneously fluctuating pattern
  • PR prolongation in some cases
The Killer Rhythms infographic at the top of this article clearly shows the coved ST elevation >2mm and negative T wave in V1-3 - the diagnostic hallmark.

10. Dilated Cardiomyopathy (DCM) / Heart Failure with Reduced EF

Overview: Dilated, poorly contracting ventricle with widespread myocardial damage. Common end-stage of multiple heart diseases.
ECG Changes (non-specific but characteristic):
  • Left bundle branch block (LBBB): broad QRS >120 ms, broad notched R in I, aVL, V5-V6; deep S in V1; ST-T discordant changes
  • Left ventricular hypertrophy voltage criteria
  • Poor R wave progression in precordial leads (V1-V4)
  • Pathological Q waves if ischemic etiology
  • Atrial fibrillation - frequently superimposed
  • Left axis deviation
  • Prolonged QRS (>120 ms) - indicates dyssynchrony, marker for CRT benefit
  • Sinus tachycardia in decompensated state
  • Low voltage QRS if large pericardial effusion coexists

Summary Table

#ConditionKey ECG HallmarkRateRhythm
1STEMIST elevation + Q waves (regional)VariableRegular
2Atrial FibrillationNo P waves, irregularly irregular100-180Irregular
3Atrial FlutterSawtooth flutter waves (~300 bpm)150 (2:1)Regular
4Complete AV BlockP-QRS dissociation, escape rhythm30-60Regular
5PericarditisDiffuse concave ST↑, PR depressionNormalRegular
6WPWDelta wave, short PR, wide QRSVariableVariable
7Ventricular TachycardiaWide QRS, AV dissociation, fusion beats100-250Regular
8HCMDagger Q waves, deep T inversion, LVHNormalRegular
9Brugada SyndromeCoved ST elevation V1-V3NormalRegular
10DCM/Heart FailureLBBB, poor R progression, AFVariableVariable

Sources:
  • Guyton and Hall Textbook of Medical Physiology (Atrial fibrillation ECG, p. ~1775-1783)
  • Ganong's Review of Medical Physiology, 26th Ed. (Myocardial infarction ECG, p. 534)
  • LITFL ECG Library - Burns & Buttner (ECG images used under CC BY-NC-SA 4.0)
  • ESC Guidelines on Pericarditis (ESCardioj.org)

Pdf link

Reading File
Running Command

ls -la /home/daytona/workspace/ 2>/dev/null || echo "workspace not found"

Running Command

mkdir -p /home/daytona/workspace/ecg-guide && python3 -c "import reportlab; prin…

Writing File

~/ecg-guide/build_pdf.py

#!/usr/bin/env python3
"""Build a professional PDF guide: 10 Common Heart Diseases with ECG Changes."""

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

OUTPUT_PATH = "/home/daytona/workspace/ecg-guide/Heart_Diseases_ECG_Guide.pdf"

# ── colours ──────────────────────────────────────────────────────────────────
RED       = colors.HexColor("#C0392B")
DARK_RED  = colors.HexColor("#922B21")
BLUE      = colors.HexColor("#1A5276")
LIGHT_BG  = colors.HexColor("#FDFEFE")
HEADER_BG = colors.HexColor("#1A5276")
ROW_ALT   = colors.HexColor("#EBF5FB")
BORDER    = colors.HexColor("#AED6F1")
GRAY      = colors.HexColor("#566573")
GREEN     = colors.HexColor("#1E8449")
ORANGE    = colors.HexColor("#D35400")

# ── ECG image URLs ────────────────────────────────────────────────────────────
ECG_IMAGES = {
    "stemi":     "https://litfl.com/wp-content/uploads/2018/08/ECG-Inferior-AMI-STEMI-Massive-tombstones.jpg",
    "af":        "https://cdn.orris.care/cdss_images/802bd5b8c1671f423278040f1bd2e654318d2d016ff4107de44a3677b224d105.png",
    "flutter":   "https://litfl.com/wp-content/uploads/2018/08/ECG-Atrial-Flutter-2-1-block.jpg",
    "chb":       "https://litfl.com/wp-content/uploads/2018/08/ECG-Complete-heart-block-CHB-1024x498.jpg",
    "pericarditis": "https://litfl.com/wp-content/uploads/2018/08/ECG-Pericarditis.jpg",
    "wpw_af":    "https://litfl.com/wp-content/uploads/2018/08/ECG-WPW-Atrial-fibrillation-3.jpg",
    "hcm":       "https://litfl.com/wp-content/uploads/2021/04/HCM-ECG.png",
    "brugada_info": "https://litfl.com/wp-content/uploads/2021/09/Killer-ECG-Part-1-Infographic.png",
}

def download_image(url, max_w_cm, max_h_cm):
    """Download image from URL and return a ReportLab Image object or None."""
    try:
        resp = requests.get(url, timeout=15)
        resp.raise_for_status()
        img_data = io.BytesIO(resp.content)
        img = Image(img_data)
        # Scale proportionally
        max_w = max_w_cm * cm
        max_h = max_h_cm * cm
        ratio = min(max_w / img.drawWidth, max_h / img.drawHeight)
        img.drawWidth  *= ratio
        img.drawHeight *= ratio
        return img
    except Exception as e:
        print(f"  [WARN] Could not download {url}: {e}")
        return None

def make_styles():
    base = getSampleStyleSheet()

    title = ParagraphStyle(
        "DocTitle",
        parent=base["Title"],
        fontSize=26,
        textColor=colors.white,
        alignment=TA_CENTER,
        spaceAfter=4,
        fontName="Helvetica-Bold",
    )
    subtitle = ParagraphStyle(
        "DocSubtitle",
        parent=base["Normal"],
        fontSize=12,
        textColor=colors.HexColor("#AED6F1"),
        alignment=TA_CENTER,
        spaceAfter=2,
    )
    section_num = ParagraphStyle(
        "SectionNum",
        parent=base["Normal"],
        fontSize=20,
        textColor=colors.white,
        fontName="Helvetica-Bold",
        alignment=TA_LEFT,
    )
    section_title = ParagraphStyle(
        "SectionTitle",
        parent=base["Normal"],
        fontSize=16,
        textColor=colors.white,
        fontName="Helvetica-Bold",
        alignment=TA_LEFT,
        spaceAfter=0,
    )
    h2 = ParagraphStyle(
        "H2",
        parent=base["Normal"],
        fontSize=11,
        textColor=BLUE,
        fontName="Helvetica-Bold",
        spaceBefore=8,
        spaceAfter=3,
    )
    body = ParagraphStyle(
        "Body",
        parent=base["Normal"],
        fontSize=9.5,
        leading=14,
        textColor=colors.HexColor("#2C3E50"),
        alignment=TA_JUSTIFY,
        spaceAfter=4,
    )
    bullet = ParagraphStyle(
        "Bullet",
        parent=base["Normal"],
        fontSize=9.5,
        leading=14,
        textColor=colors.HexColor("#2C3E50"),
        leftIndent=14,
        bulletIndent=4,
        spaceAfter=2,
    )
    caption = ParagraphStyle(
        "Caption",
        parent=base["Normal"],
        fontSize=8,
        textColor=GRAY,
        alignment=TA_CENTER,
        spaceAfter=6,
        fontName="Helvetica-Oblique",
    )
    footer_style = ParagraphStyle(
        "Footer",
        parent=base["Normal"],
        fontSize=7.5,
        textColor=GRAY,
        alignment=TA_CENTER,
    )
    return {
        "title": title,
        "subtitle": subtitle,
        "section_num": section_num,
        "section_title": section_title,
        "h2": h2,
        "body": body,
        "bullet": bullet,
        "caption": caption,
        "footer": footer_style,
        "normal": base["Normal"],
    }

def section_header(number, title, color=None):
    """Returns a Table acting as a coloured section header band."""
    bg = color or BLUE
    data = [[
        Paragraph(f"{number}.", ParagraphStyle("n", fontSize=22, textColor=colors.white, fontName="Helvetica-Bold")),
        Paragraph(title, ParagraphStyle("t", fontSize=15, textColor=colors.white, fontName="Helvetica-Bold", leading=18)),
    ]]
    t = Table(data, colWidths=[1.8*cm, 14.5*cm])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), bg),
        ("VALIGN",     (0,0), (-1,-1), "MIDDLE"),
        ("LEFTPADDING",(0,0), (-1,-1), 10),
        ("RIGHTPADDING",(0,0),(-1,-1), 10),
        ("TOPPADDING", (0,0), (-1,-1), 8),
        ("BOTTOMPADDING",(0,0),(-1,-1), 8),
        ("ROUNDEDCORNERS", [4, 4, 4, 4]),
    ]))
    return t

def ecg_table(rows, styles):
    """Build a two-column ECG findings table."""
    header = [
        Paragraph("<b>ECG Feature</b>", ParagraphStyle("th", fontSize=9, textColor=colors.white, fontName="Helvetica-Bold")),
        Paragraph("<b>Details</b>", ParagraphStyle("th", fontSize=9, textColor=colors.white, fontName="Helvetica-Bold")),
    ]
    data = [header] + [
        [Paragraph(f"<b>{r[0]}</b>", ParagraphStyle("td1", fontSize=9, textColor=DARK_RED, fontName="Helvetica-Bold")),
         Paragraph(r[1], ParagraphStyle("td2", fontSize=9, textColor=colors.HexColor("#2C3E50"), leading=13))]
        for r in rows
    ]
    col_w = [5.5*cm, 10.8*cm]
    t = Table(data, colWidths=col_w, repeatRows=1)
    style = [
        ("BACKGROUND", (0,0), (-1,0), BLUE),
        ("GRID",       (0,0), (-1,-1), 0.4, BORDER),
        ("VALIGN",     (0,0), (-1,-1), "TOP"),
        ("LEFTPADDING",(0,0), (-1,-1), 6),
        ("RIGHTPADDING",(0,0),(-1,-1), 6),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING",(0,0),(-1,-1), 4),
    ]
    for i in range(1, len(data)):
        if i % 2 == 0:
            style.append(("BACKGROUND", (0,i), (-1,i), ROW_ALT))
    t.setStyle(TableStyle(style))
    return t

def summary_table(styles):
    headers = ["#", "Condition", "Key ECG Hallmark", "Rate", "Rhythm"]
    rows = [
        ["1", "STEMI", "ST elevation + Q waves (regional)", "Variable", "Regular"],
        ["2", "Atrial Fibrillation", "No P waves, irregularly irregular", "100-180 bpm", "Irregular"],
        ["3", "Atrial Flutter", "Sawtooth waves ~300 bpm", "150 bpm (2:1)", "Regular"],
        ["4", "Complete AV Block", "P-QRS dissociation, escape rhythm", "30-60 bpm", "Regular"],
        ["5", "Acute Pericarditis", "Diffuse concave ST↑, PR depression", "Normal", "Regular"],
        ["6", "WPW Syndrome", "Delta wave, short PR, wide QRS", "Variable", "Variable"],
        ["7", "Ventricular Tachycardia", "Wide QRS, AV dissociation, fusion beats", "100-250 bpm", "Regular"],
        ["8", "Hypertrophic CMP (HCM)", "Dagger Q waves, deep T inversion, LVH", "Normal", "Regular"],
        ["9", "Brugada Syndrome", "Coved ST elevation V1-V3", "Normal", "Regular"],
        ["10", "DCM / Heart Failure", "LBBB, poor R progression, AF", "Variable", "Variable"],
    ]
    cell_style = ParagraphStyle("cs", fontSize=8.5, leading=12, textColor=colors.HexColor("#2C3E50"))
    header_style = ParagraphStyle("hs", fontSize=8.5, fontName="Helvetica-Bold", textColor=colors.white)
    data = [[Paragraph(h, header_style) for h in headers]]
    for r in rows:
        data.append([Paragraph(c, cell_style) for c in r])
    col_w = [0.8*cm, 4.2*cm, 6.0*cm, 2.8*cm, 2.5*cm]
    t = Table(data, colWidths=col_w, repeatRows=1)
    ts = [
        ("BACKGROUND", (0,0), (-1,0), DARK_RED),
        ("GRID",       (0,0), (-1,-1), 0.4, colors.HexColor("#E8DAEF")),
        ("VALIGN",     (0,0), (-1,-1), "MIDDLE"),
        ("LEFTPADDING",(0,0), (-1,-1), 5),
        ("RIGHTPADDING",(0,0),(-1,-1), 5),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING",(0,0),(-1,-1), 4),
    ]
    for i in range(1, len(data)):
        if i % 2 == 0:
            ts.append(("BACKGROUND", (0,i), (-1,i), colors.HexColor("#FDEDEC")))
    t.setStyle(TableStyle(ts))
    return t

def add_cover_page(story, styles):
    # Header bar
    cover_data = [[
        Paragraph("10 Common Heart Diseases", styles["title"]),
    ]]
    cover_table = Table([[
        Paragraph("10 Common Heart Diseases", ParagraphStyle("ct", fontSize=26, textColor=colors.white, fontName="Helvetica-Bold", alignment=TA_CENTER)),
    ]], colWidths=[16.3*cm])
    cover_table.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), DARK_RED),
        ("TOPPADDING",    (0,0), (-1,-1), 18),
        ("BOTTOMPADDING", (0,0), (-1,-1), 10),
        ("LEFTPADDING",   (0,0), (-1,-1), 12),
        ("RIGHTPADDING",  (0,0), (-1,-1), 12),
    ]))
    story.append(cover_table)

    sub_table = Table([[
        Paragraph("with ECG Changes &amp; Diagnostic Images", ParagraphStyle("st", fontSize=14, textColor=colors.white, alignment=TA_CENTER)),
    ]], colWidths=[16.3*cm])
    sub_table.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), BLUE),
        ("TOPPADDING",    (0,0), (-1,-1), 10),
        ("BOTTOMPADDING", (0,0), (-1,-1), 10),
    ]))
    story.append(sub_table)
    story.append(Spacer(1, 0.6*cm))

    # Intro paragraph
    story.append(Paragraph(
        "This reference guide presents 10 clinically important heart diseases, each with a structured breakdown of "
        "ECG changes, key diagnostic features, and annotated electrocardiogram images. Sourced from leading medical "
        "textbooks and the LITFL ECG Library.",
        styles["body"]
    ))
    story.append(Spacer(1, 0.3*cm))

    # Quick overview infographic
    img = download_image(ECG_IMAGES["brugada_info"], 16, 9)
    if img:
        story.append(img)
        story.append(Paragraph("Overview: Killer ECG Patterns — LITFL ECG Library (CC BY-NC-SA 4.0)", styles["caption"]))
    story.append(Spacer(1, 0.4*cm))

    # Summary table
    story.append(Paragraph("Quick Reference Summary", ParagraphStyle("qr", fontSize=13, textColor=DARK_RED, fontName="Helvetica-Bold", spaceAfter=6)))
    story.append(summary_table(styles))
    story.append(PageBreak())

def build_disease(story, styles, number, title, color, overview, ecg_rows, extra_paras, img_key, img_caption):
    story.append(section_header(number, title, color))
    story.append(Spacer(1, 0.25*cm))

    story.append(Paragraph("Overview", styles["h2"]))
    story.append(Paragraph(overview, styles["body"]))

    story.append(Paragraph("ECG Changes", styles["h2"]))
    story.append(ecg_table(ecg_rows, styles))

    for p in extra_paras:
        story.append(Spacer(1, 0.15*cm))
        story.append(Paragraph(p, styles["body"]))

    if img_key and img_key in ECG_IMAGES:
        story.append(Spacer(1, 0.3*cm))
        img = download_image(ECG_IMAGES[img_key], 15.5, 7.5)
        if img:
            story.append(img)
            story.append(Paragraph(img_caption, styles["caption"]))

    story.append(Spacer(1, 0.5*cm))
    story.append(HRFlowable(width="100%", thickness=0.5, color=BORDER))
    story.append(Spacer(1, 0.4*cm))

def main():
    print("Building PDF...")
    doc = SimpleDocTemplate(
        OUTPUT_PATH,
        pagesize=A4,
        leftMargin=1.8*cm, rightMargin=1.8*cm,
        topMargin=2.0*cm,  bottomMargin=2.0*cm,
        title="10 Common Heart Diseases with ECG Changes",
        author="Orris Medical Reference",
        subject="Cardiology ECG Guide",
    )

    styles = make_styles()
    story = []

    # ── Cover + Summary ───────────────────────────────────────────────────────
    add_cover_page(story, styles)

    # ── Disease 1: STEMI ──────────────────────────────────────────────────────
    build_disease(
        story, styles, "1", "ST-Elevation Myocardial Infarction (STEMI)", DARK_RED,
        "STEMI results from complete occlusion of a coronary artery causing transmural ischemia and necrosis. "
        "It is a time-critical emergency requiring immediate reperfusion therapy (primary PCI within 90 minutes).",
        [
            ("Hyperacute T waves", "Earliest finding — tall, peaked T waves in affected territory leads"),
            ("ST elevation",       "≥1 mm in 2+ contiguous limb leads, or ≥2 mm in precordial leads. Convex (tombstone) morphology."),
            ("Reciprocal changes", "ST depression in mirror leads (e.g., inferior STEMI → ST depression in I, aVL)"),
            ("Pathological Q waves","Width >40 ms and depth >25% of R wave; develop after hours-days of infarction"),
            ("T wave inversion",   "Subacute/chronic phase; indicates repolarisation abnormality over infarcted zone"),
            ("Localisation",       "Anterior (V1-V4, LAD) | Inferior (II, III, aVF, RCA) | Lateral (I, aVL, V5-V6, LCx) | Posterior (ST depression V1-V3)"),
        ],
        ["The hallmark ECG mechanism: infarcted fibres rapidly repolarise and suffer decreased resting membrane potential. "
         "Both changes drive current toward the infarcted zone, producing ST elevation in overlying leads and reciprocal depression opposite. "
         "(Ganong's Review of Medical Physiology, 26th Ed., p. 534)"],
        "stemi",
        "Inferior STEMI — massive 'tombstone' ST elevations in II, III, aVF with reciprocal changes in I, aVL. (LITFL ECG Library)"
    )

    # ── Disease 2: Atrial Fibrillation ────────────────────────────────────────
    build_disease(
        story, styles, "2", "Atrial Fibrillation (AF)", BLUE,
        "The most common sustained cardiac arrhythmia. Disorganised atrial electrical activity causes rapid, "
        "irregular atrial depolarisation at 350-600 bpm. Lifetime risk after age 40 is ~25%. "
        "Complications include haemodynamic compromise, cardiomyopathy, and thromboembolic stroke.",
        [
            ("No P waves",          "Replaced by chaotic fibrillatory (f) waves at 350-600 bpm; baseline appears irregular and undulating"),
            ("Irregularly irregular","Hallmark finding — RR intervals vary unpredictably. No two consecutive RR intervals are equal"),
            ("Ventricular rate",    "Typically 100-180 bpm if uncontrolled; <100 bpm if rate-controlled or in complete AV block"),
            ("QRS morphology",      "Usually narrow and normal; wide if pre-existing BBB, aberrant conduction, or WPW co-exists"),
            ("Fibrillatory baseline","Fine (low voltage, <1 mm) or coarse (>1 mm). Coarse suggests recent onset or enlarged atria"),
        ],
        ["Ventricular irregularity arises because the AV node conducts randomly arriving fibrillatory impulses with a minimum refractory period "
         "of ~350 ms. Each subsequent impulse can arrive 0-600 ms later, producing beat-to-beat variability. "
         "(Guyton and Hall Textbook of Medical Physiology)"],
        "af",
        "AF (Lead II): absent P waves, irregularly irregular QRS complexes, chaotic baseline. (Guyton & Hall / Orris Medical Library)"
    )

    # ── Disease 3: Atrial Flutter ─────────────────────────────────────────────
    build_disease(
        story, styles, "3", "Atrial Flutter", colors.HexColor("#1F618D"),
        "A macro-reentrant supraventricular tachycardia driven by a reentry circuit within the right atrium. "
        "Anticlockwise (typical) flutter accounts for ~90% of cases, with an atrial rate of ~300 bpm (range 250-350).",
        [
            ("Sawtooth flutter waves","Regular, negative deflections at ~300 bpm in inferior leads (II, III, aVF); upright in V1. No isoelectric baseline"),
            ("Ventricular rate",      "Fraction of atrial rate: 2:1 block → 150 bpm (most common), 3:1 → 100 bpm, 4:1 → 75 bpm, or variable"),
            ("QRS morphology",        "Usually narrow and normal unless aberrant conduction or BBB present"),
            ("Regular rhythm",        "Ventricular response is regular when block ratio is fixed; irregular if variable block"),
            ("Distinguishing from AF","Flutter = regular sawtooth waves at fixed rate; AF = irregular chaotic baseline"),
        ],
        [],
        "flutter",
        "Atrial flutter with 2:1 AV block: classic sawtooth flutter waves in inferior leads; ventricular rate ~150 bpm. (LITFL ECG Library)"
    )

    story.append(PageBreak())

    # ── Disease 4: Complete AV Block ──────────────────────────────────────────
    build_disease(
        story, styles, "4", "Complete (3rd Degree) AV Heart Block", colors.HexColor("#6C3483"),
        "Complete failure of conduction between the atria and ventricles. Atria and ventricles beat "
        "independently at their intrinsic rates. Perfusion is maintained by junctional or ventricular escape rhythm. "
        "Urgent temporary pacing is often required.",
        [
            ("Complete AV dissociation","P waves and QRS complexes are completely independent — no fixed PR relationship"),
            ("Atrial rate > ventricular","Sinus rate 60-100 bpm; ventricular escape rate 30-60 bpm (junctional) or 20-40 bpm (ventricular)"),
            ("Escape QRS",             "Narrow if junctional escape (40-60 bpm); wide and bizarre if ventricular escape (20-40 bpm)"),
            ("Slow ventricular rate",  "Bradycardia — typically 30-60 bpm depending on escape focus location"),
            ("P waves march through",  "P waves occur at regular sinus rate but bear no relationship to QRS timing"),
        ],
        ["Complete AV block can complicate inferior STEMI (due to AV nodal ischaemia from RCA occlusion) or "
         "occur from medications, infiltrative disease, or surgical trauma. It is a true emergency."],
        "chb",
        "Complete heart block: regular slow ventricular escape rhythm; P waves (arrows) march through at a faster, independent rate. (LITFL ECG Library)"
    )

    # ── Disease 5: Acute Pericarditis ─────────────────────────────────────────
    build_disease(
        story, styles, "5", "Acute Pericarditis", GREEN,
        "Inflammation of the pericardial sac, most commonly viral (Coxsackievirus, echovirus). "
        "ECG changes reflect diffuse myocardial surface irritation rather than regional ischaemia. "
        "ECG evolves through four characteristic stages.",
        [
            ("Stage 1 — Acute (hrs-days)","DIFFUSE concave (saddle-shaped) ST elevation in ALL leads except aVR and V1. PR depression in most leads; PR elevation in aVR"),
            ("Stage 2 — ~1 week",         "ST segments and PR return to baseline. T wave flattening begins"),
            ("Stage 3 — After ST normal", "Diffuse T wave inversion across multiple leads"),
            ("Stage 4 — Weeks-months",    "ECG normalisation or persistent T wave inversion"),
            ("PR depression",             "Atrial myocardial involvement — seen in up to 80% of cases; most specific finding for pericarditis"),
            ("vs STEMI",                  "Pericarditis: diffuse, concave, no reciprocal ST↓ except aVR/V1, PR depression. STEMI: regional, convex, reciprocal changes"),
        ],
        ["Classic teaching: look for the 'saddle shape' of ST elevation with PR depression across the precordium. "
         "PR elevation in aVR is highly specific. Serial ECGs are essential in any patient with chest pain. "
         "(ESC Guidelines on Pericarditis; LITFL ECG Library)"],
        "pericarditis",
        "Acute pericarditis: diffuse concave ST elevation ('saddle shape') across multiple leads with PR depression. (LITFL ECG Library)"
    )

    story.append(PageBreak())

    # ── Disease 6: WPW ────────────────────────────────────────────────────────
    build_disease(
        story, styles, "6", "Wolff-Parkinson-White (WPW) Syndrome", ORANGE,
        "Pre-excitation syndrome caused by an accessory pathway (Bundle of Kent) that bypasses the AV node, "
        "allowing impulses to reach the ventricles prematurely. In sinus rhythm, the ECG shows the 'WPW triad'. "
        "During AF or flutter, conduction via the accessory pathway can cause life-threatening ventricular rates.",
        [
            ("Short PR interval",   "<120 ms — no physiological AV nodal delay; impulse bypasses AV node via accessory pathway"),
            ("Delta wave",          "Slurred, slow upstroke at the START of QRS; represents early pre-excitation of ventricular myocardium"),
            ("Wide QRS",            ">120 ms — total QRS = delta (pre-excitation) + normal His-Purkinje activation"),
            ("ST-T changes",        "Secondary, discordant (opposite to QRS polarity) — not indicative of ischaemia"),
            ("Pseudo-infarct Q",    "Negative delta waves can mimic pathological Q waves; Type B WPW mimics inferior or anteroseptal MI"),
            ("AF in WPW",           "EMERGENCY: extremely rapid (>200-300 bpm), irregularly irregular, wide, bizarre QRS complexes — can degenerate to VF"),
        ],
        ["WPW with AF is a life-threatening emergency. AV nodal blocking agents (verapamil, diltiazem, digoxin) are CONTRAINDICATED "
         "as they can accelerate conduction via the accessory pathway. Treatment: DC cardioversion or IV procainamide. "
         "Definitive treatment is catheter ablation of the accessory pathway."],
        "wpw_af",
        "Pre-excited AF in WPW: chaotic, extremely rapid, irregularly irregular wide QRS complexes — ventricular rate >200 bpm. (LITFL ECG Library)"
    )

    # ── Disease 7: Ventricular Tachycardia ────────────────────────────────────
    build_disease(
        story, styles, "7", "Ventricular Tachycardia (VT)", RED,
        "Three or more consecutive ventricular ectopic beats at >100 bpm, originating below the Bundle of His. "
        "Monomorphic VT has uniform QRS morphology; polymorphic VT (including Torsades de Pointes) has varying morphology. "
        "Sustained VT (>30s) is a medical emergency.",
        [
            ("Wide QRS",           ">120 ms (usually >140 ms); LBBB or RBBB morphology depending on origin site"),
            ("Rate",               "100-250 bpm; regular (monomorphic) or irregular (polymorphic/Torsades)"),
            ("AV dissociation",    "P waves march through independently of QRS — pathognomonic of VT when visible (~50% of cases)"),
            ("Fusion beats",       "Partial sinus capture + VT = hybrid QRS morphology — PATHOGNOMONIC of VT"),
            ("Capture beats",      "Occasional narrow sinus-conducted beats 'capturing' the ventricle — PATHOGNOMONIC of VT"),
            ("Axis deviation",     "Extreme right or northwest axis deviation (±180 to ±270°) strongly supports VT"),
            ("Precordial concordance","All precordial leads uniformly positive or uniformly negative — suggests VT over SVT with aberrancy"),
        ],
        ["Brugada criteria for distinguishing VT from SVT with aberrancy: (1) absence of RS in all precordial leads → VT; "
         "(2) RS interval >100 ms in any precordial lead → VT; (3) AV dissociation → VT; "
         "(4) morphology not meeting SVT criteria → VT. If any criterion is met, diagnose VT."],
        None, ""  # No specific VT image in our set; skip
    )

    story.append(PageBreak())

    # ── Disease 8: HCM ────────────────────────────────────────────────────────
    build_disease(
        story, styles, "8", "Hypertrophic Cardiomyopathy (HCM)", colors.HexColor("#117A65"),
        "A genetic cardiomyopathy (typically autosomal dominant, sarcomere protein mutations) characterised by "
        "asymmetric ventricular hypertrophy, most often involving the interventricular septum. "
        "It is the leading cause of sudden cardiac death in young athletes.",
        [
            ("LVH voltage criteria",   "SV1 + RV5/V6 >35 mm (Sokolow-Lyon) or RaVL >11 mm"),
            ("Dagger Q waves",         "Deep, narrow Q waves in lateral leads (I, aVL, V5-V6) and inferior leads — due to septal hypertrophy. Key differentiator from MI Q waves"),
            ("T wave inversion",       "Widespread, often striking and deep (especially V4-V6 and inferior leads)"),
            ("Left axis deviation",    "LAD due to hypertrophied septum altering vector"),
            ("ST depression",          "Lateral leads — strain pattern from severe LVH"),
            ("Apical HCM pattern",     "Giant T wave inversions in V3-V5 (up to 10-15 mm deep) — classic for Japanese apical variant"),
            ("Atrial fibrillation",    "Commonly superimposed; occurs in 20-25% of HCM patients over lifetime"),
        ],
        ["A young patient with exertional symptoms and an ECG showing LVH + lateral Q waves + deep T inversions "
         "must be considered to have HCM until proven otherwise. This pattern is frequently misread as 'prior lateral infarction'. "
         "(Kelly, Mattu & Brady 2007; LITFL ECG Library)"],
        "hcm",
        "HCM ECG: left ventricular hypertrophy, deep Q waves in lateral leads, widespread ST depression and T wave inversion. (LITFL ECG Library)"
    )

    # ── Disease 9: Brugada Syndrome ───────────────────────────────────────────
    build_disease(
        story, styles, "9", "Brugada Syndrome", colors.HexColor("#7D6608"),
        "An inherited sodium channelopathy (SCN5A gene, autosomal dominant) causing life-threatening ventricular "
        "arrhythmias and sudden cardiac death, predominantly in young males (20-40 years), often at rest or during sleep. "
        "Triggers include fever, cocaine, sodium channel blockers, and vagal stimulation.",
        [
            ("Type 1 — Diagnostic",  "COVED pattern: ST elevation ≥2 mm in V1-V3 descending into a NEGATIVE T wave. Spontaneous or drug-induced. The ONLY diagnostic pattern"),
            ("Type 2 — Suspicious",  "SADDLEBACK: ST elevation ≥2 mm in V1-V3, T wave upright or biphasic. Requires sodium channel blocker provocation test"),
            ("Type 3",               "ST elevation <1 mm in V1-V3. Not diagnostic; may be baseline appearance"),
            ("RBBB pattern",         "Incomplete or complete right bundle branch block morphology frequently coexists"),
            ("Dynamic pattern",      "ECG pattern fluctuates spontaneously; may be intermittently normal — serial ECGs important"),
            ("PR prolongation",      "Mild prolongation present in some cases due to SCN5A mutation"),
        ],
        ["Brugada pattern can be unmasked/accentuated by fever, sodium channel blocking drugs (flecainide, ajmaline), "
         "and certain medications. All first-degree relatives require ECG screening. "
         "ICD implantation is the only proven therapy for secondary prevention. "
         "The Type 1 coved pattern in V1-V3 is shown clearly in the Killer ECG infographic above."],
        None, ""
    )

    story.append(PageBreak())

    # ── Disease 10: DCM / Heart Failure ───────────────────────────────────────
    build_disease(
        story, styles, "10", "Dilated Cardiomyopathy (DCM) / Heart Failure", GRAY,
        "DCM is characterised by ventricular dilatation and impaired systolic function. It represents a common final "
        "pathway for multiple conditions (ischaemic, viral, alcoholic, idiopathic). ECG findings are non-specific "
        "but reflect underlying structural abnormalities.",
        [
            ("Left Bundle Branch Block","LBBB: broad QRS >120 ms, broad notched R in I/aVL/V5-V6, deep S in V1; ST-T discordant. LBBB implies significant structural disease"),
            ("LVH voltage",            "Sokolow-Lyon criteria positive in many patients"),
            ("Poor R wave progression","Small or absent R waves V1-V4 — reflects anterior wall dysfunction or loss of viable myocardium"),
            ("Pathological Q waves",   "If ischaemic aetiology — indicate prior MI with scar tissue"),
            ("Atrial fibrillation",    "Frequently superimposed; AF worsens haemodynamics further in already failing heart"),
            ("Prolonged QRS",          ">120 ms indicates ventricular dyssynchrony — marker for cardiac resynchronisation therapy (CRT) benefit"),
            ("Sinus tachycardia",      "Compensatory tachycardia in decompensated heart failure"),
            ("Low voltage QRS",        "If large pericardial effusion or cardiac tamponade coexists — ALL leads show reduced amplitude"),
        ],
        ["QRS duration >150 ms with LBBB morphology is the strongest predictor of CRT response. "
         "Presence of AF in DCM worsens prognosis by ~30-40%. LV dyssynchrony on ECG correlates with "
         "echocardiographic findings of interventricular mechanical delay."],
        None, ""
    )

    # ── Final Summary Page ────────────────────────────────────────────────────
    story.append(PageBreak())
    story.append(section_header("★", "Complete Summary: 10 Heart Diseases at a Glance", DARK_RED))
    story.append(Spacer(1, 0.4*cm))
    story.append(summary_table(styles))
    story.append(Spacer(1, 0.6*cm))

    story.append(Paragraph(
        "<b>Sources:</b> Guyton &amp; Hall Textbook of Medical Physiology | Ganong's Review of Medical Physiology, 26th Ed. | "
        "Harrison's Principles of Internal Medicine 22E | Braunwald's Heart Disease | "
        "LITFL ECG Library — Burns &amp; Buttner (CC BY-NC-SA 4.0) | "
        "ESC Guidelines on Pericarditis | Tintinalli's Emergency Medicine",
        ParagraphStyle("src", fontSize=8, textColor=GRAY, leading=12, spaceBefore=8)
    ))

    # ── Build ─────────────────────────────────────────────────────────────────
    doc.build(story)
    print(f"PDF saved to: {OUTPUT_PATH}")

if __name__ == "__main__":
    main()
Running Command

cd /home/daytona/workspace/ecg-guide && python3 build_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/ecg-guide/Heart_Diseases_ECG_Guide.pdf

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

Heart Diseases ECG Guide

PDF Document · PDF

What's inside (2.6 MB, A4 format):
  • Cover page with the full summary table and LITFL Killer ECG infographic
  • 10 disease sections, each with:
    • Colour-coded section header
    • Clinical overview
    • Structured ECG changes table (feature + detailed explanation)
    • Annotated real ECG images (STEMI, AF, Atrial Flutter, Complete Heart Block, Pericarditis, WPW with AF, HCM)
    • Key clinical notes
  • Final summary page with all 10 diseases at a glance (key hallmark, rate, rhythm)
  • Sources cited from Guyton & Hall, Ganong's, Harrison's, Braunwald's, and LITFL ECG Library

Pdf cant download

Running Command

ls -lh /home/daytona/workspace/ecg-guide/ && file /home/daytona/workspace/ecg-gu…

Running Command

base64 /home/daytona/workspace/ecg-guide/Heart_Diseases_ECG_Guide.pdf | wc -c &&…

Running Command

# Check if there's a way to serve files or if we can copy to a web-accessible pa…

Running Command

# Start a background HTTP server on port 8080 serving the workspace directory cd…

Running Command

cd /home/daytona/workspace && nohup python3 -m http.server 8080 --bind 0.0.0.0 >…

The server is running and confirmed accessible (HTTP 200). Here are your download options:

Option 1 - Direct sandbox path (click the link below):

Heart Diseases ECG Guide

PDF Document · PDF


Option 2 - If the above still doesn't work, the issue may be that your browser/platform doesn't expose the sandbox filesystem directly. In that case, I can:
  1. Convert to HTML - deliver the full guide as a webpage you can print-to-PDF from your browser
  2. Split into smaller parts - break the PDF into individual disease pages
  3. Email/share format - export as a Word (.docx) document instead
Which would you prefer? Most users find Option 1 (HTML → Print to PDF) works reliably when the sandbox link doesn't open directly.

Generate a Word document (.docx) version instead

Reading File
Running Command

ls /home/daytona/skills/docx/scripts/office/ && node --version && npm list -g do…

Writing File

~/ecg-guide/build_docx.js

"use strict";
const fs = require("fs");
const https = require("https");
const http = require("http");
const path = require("path");
const {
  Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell,
  ImageRun, Header, Footer, AlignmentType, HeadingLevel, BorderStyle,
  WidthType, ShadingType, VerticalAlign, PageNumber, PageBreak,
  TableOfContents, NumberFormat, convertInchesToTwip, convertMillimetersToTwip,
  UnderlineType
} = require("docx");

const OUT = "/home/daytona/workspace/ecg-guide/Heart_Diseases_ECG_Guide.docx";

// ── Colours ────────────────────────────────────────────────────────────────
const C = {
  darkRed:   "8B1A1A",
  red:       "C0392B",
  blue:      "1A5276",
  lightBlue: "AED6F1",
  green:     "1E8449",
  orange:    "D35400",
  purple:    "6C3483",
  teal:      "117A65",
  gray:      "566573",
  darkGold:  "7D6608",
  rowAlt:    "EBF5FB",
  rowAlt2:   "FDEDEC",
  white:     "FFFFFF",
  bodyText:  "2C3E50",
  border:    "AED6F1",
};

// ── Image download ─────────────────────────────────────────────────────────
function downloadImage(url) {
  return new Promise((resolve) => {
    const mod = url.startsWith("https") ? https : http;
    const chunks = [];
    mod.get(url, { timeout: 15000 }, (res) => {
      res.on("data", c => chunks.push(c));
      res.on("end", () => resolve(Buffer.concat(chunks)));
    }).on("error", () => resolve(null))
      .on("timeout", () => resolve(null));
  });
}

const IMG_URLS = {
  stemi:       "https://litfl.com/wp-content/uploads/2018/08/ECG-Inferior-AMI-STEMI-Massive-tombstones.jpg",
  af:          "https://cdn.orris.care/cdss_images/802bd5b8c1671f423278040f1bd2e654318d2d016ff4107de44a3677b224d105.png",
  flutter:     "https://litfl.com/wp-content/uploads/2018/08/ECG-Atrial-Flutter-2-1-block.jpg",
  chb:         "https://litfl.com/wp-content/uploads/2018/08/ECG-Complete-heart-block-CHB-1024x498.jpg",
  pericarditis:"https://litfl.com/wp-content/uploads/2018/08/ECG-Pericarditis.jpg",
  wpw_af:      "https://litfl.com/wp-content/uploads/2018/08/ECG-WPW-Atrial-fibrillation-3.jpg",
  hcm:         "https://litfl.com/wp-content/uploads/2021/04/HCM-ECG.png",
  infographic: "https://litfl.com/wp-content/uploads/2021/09/Killer-ECG-Part-1-Infographic.png",
};

// ── Helpers ────────────────────────────────────────────────────────────────
function sp(n = 1) {
  return new Paragraph({ spacing: { before: n * 60, after: 0 } });
}

function hRule(color = C.lightBlue) {
  return new Paragraph({
    border: { bottom: { style: BorderStyle.SINGLE, size: 6, color } },
    spacing: { before: 80, after: 80 },
  });
}

function coverTitle(text, color = C.white, size = 52) {
  return new Paragraph({
    alignment: AlignmentType.CENTER,
    shading: { type: ShadingType.SOLID, color: C.darkRed, fill: C.darkRed },
    spacing: { before: 0, after: 0 },
    children: [new TextRun({ text, bold: true, size, color, font: "Calibri" })],
  });
}

function coverSubtitle(text) {
  return new Paragraph({
    alignment: AlignmentType.CENTER,
    shading: { type: ShadingType.SOLID, color: C.blue, fill: C.blue },
    spacing: { before: 0, after: 200 },
    children: [new TextRun({ text, size: 28, color: C.lightBlue, font: "Calibri" })],
  });
}

function sectionBanner(num, title, bgColor) {
  return new Table({
    width: { size: 100, type: WidthType.PERCENTAGE },
    rows: [new TableRow({
      children: [
        new TableCell({
          width: { size: 8, type: WidthType.PERCENTAGE },
          shading: { type: ShadingType.SOLID, color: bgColor, fill: bgColor },
          verticalAlign: VerticalAlign.CENTER,
          children: [new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [new TextRun({ text: num + ".", bold: true, size: 44, color: C.white, font: "Calibri" })],
          })],
        }),
        new TableCell({
          width: { size: 92, type: WidthType.PERCENTAGE },
          shading: { type: ShadingType.SOLID, color: bgColor, fill: bgColor },
          verticalAlign: VerticalAlign.CENTER,
          margins: { left: convertMillimetersToTwip(3) },
          children: [new Paragraph({
            children: [new TextRun({ text: title, bold: true, size: 36, color: C.white, font: "Calibri" })],
          })],
        }),
      ],
    })],
    borders: { top: { style: BorderStyle.NONE }, bottom: { style: BorderStyle.NONE }, left: { style: BorderStyle.NONE }, right: { style: BorderStyle.NONE }, insideH: { style: BorderStyle.NONE }, insideV: { style: BorderStyle.NONE } },
  });
}

function subHeading(text, color = C.blue) {
  return new Paragraph({
    spacing: { before: 160, after: 60 },
    children: [new TextRun({ text, bold: true, size: 24, color, font: "Calibri", underline: { type: UnderlineType.SINGLE, color } })],
  });
}

function body(text) {
  return new Paragraph({
    spacing: { before: 40, after: 60 },
    children: [new TextRun({ text, size: 20, color: C.bodyText, font: "Calibri" })],
  });
}

function bullet(text) {
  return new Paragraph({
    bullet: { level: 0 },
    spacing: { before: 20, after: 20 },
    children: [new TextRun({ text, size: 20, color: C.bodyText, font: "Calibri" })],
  });
}

function caption(text) {
  return new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: 40, after: 120 },
    children: [new TextRun({ text, size: 16, italics: true, color: C.gray, font: "Calibri" })],
  });
}

function ecgTable(rows) {
  const headerRow = new TableRow({
    tableHeader: true,
    children: [
      new TableCell({
        width: { size: 28, type: WidthType.PERCENTAGE },
        shading: { type: ShadingType.SOLID, color: C.blue, fill: C.blue },
        children: [new Paragraph({ children: [new TextRun({ text: "ECG Feature", bold: true, size: 20, color: C.white, font: "Calibri" })] })],
      }),
      new TableCell({
        width: { size: 72, type: WidthType.PERCENTAGE },
        shading: { type: ShadingType.SOLID, color: C.blue, fill: C.blue },
        children: [new Paragraph({ children: [new TextRun({ text: "Details", bold: true, size: 20, color: C.white, font: "Calibri" })] })],
      }),
    ],
  });

  const dataRows = rows.map(([feat, detail], i) => new TableRow({
    children: [
      new TableCell({
        width: { size: 28, type: WidthType.PERCENTAGE },
        shading: i % 2 === 0
          ? { type: ShadingType.SOLID, color: C.rowAlt, fill: C.rowAlt }
          : { type: ShadingType.CLEAR, color: C.white, fill: C.white },
        children: [new Paragraph({ children: [new TextRun({ text: feat, bold: true, size: 19, color: C.red, font: "Calibri" })] })],
      }),
      new TableCell({
        width: { size: 72, type: WidthType.PERCENTAGE },
        shading: i % 2 === 0
          ? { type: ShadingType.SOLID, color: C.rowAlt, fill: C.rowAlt }
          : { type: ShadingType.CLEAR, color: C.white, fill: C.white },
        children: [new Paragraph({ children: [new TextRun({ text: detail, size: 19, color: C.bodyText, font: "Calibri" })] })],
      }),
    ],
  }));

  return new Table({
    width: { size: 100, type: WidthType.PERCENTAGE },
    rows: [headerRow, ...dataRows],
    borders: {
      top:     { style: BorderStyle.SINGLE, size: 4, color: C.border },
      bottom:  { style: BorderStyle.SINGLE, size: 4, color: C.border },
      left:    { style: BorderStyle.SINGLE, size: 4, color: C.border },
      right:   { style: BorderStyle.SINGLE, size: 4, color: C.border },
      insideH: { style: BorderStyle.SINGLE, size: 2, color: C.border },
      insideV: { style: BorderStyle.SINGLE, size: 2, color: C.border },
    },
  });
}

function summaryTable() {
  const headers = ["#", "Condition", "Key ECG Hallmark", "Rate", "Rhythm"];
  const rows = [
    ["1",  "STEMI",                      "ST elevation + Q waves (regional)",         "Variable",     "Regular"],
    ["2",  "Atrial Fibrillation",         "No P waves, irregularly irregular",          "100-180 bpm",  "Irregular"],
    ["3",  "Atrial Flutter",              "Sawtooth waves ~300 bpm",                    "150 bpm (2:1)","Regular"],
    ["4",  "Complete AV Block",           "P-QRS dissociation, escape rhythm",          "30-60 bpm",    "Regular"],
    ["5",  "Acute Pericarditis",          "Diffuse concave ST↑, PR depression",         "Normal",       "Regular"],
    ["6",  "WPW Syndrome",               "Delta wave, short PR, wide QRS",             "Variable",     "Variable"],
    ["7",  "Ventricular Tachycardia",     "Wide QRS, AV dissociation, fusion beats",    "100-250 bpm",  "Regular"],
    ["8",  "Hypertrophic CMP (HCM)",      "Dagger Q waves, deep T inversion, LVH",      "Normal",       "Regular"],
    ["9",  "Brugada Syndrome",            "Coved ST elevation V1-V3",                   "Normal",       "Regular"],
    ["10", "DCM / Heart Failure",         "LBBB, poor R progression, AF",               "Variable",     "Variable"],
  ];

  const colWidths = [5, 22, 40, 18, 15];

  const hdrRow = new TableRow({
    tableHeader: true,
    children: headers.map((h, i) => new TableCell({
      width: { size: colWidths[i], type: WidthType.PERCENTAGE },
      shading: { type: ShadingType.SOLID, color: C.darkRed, fill: C.darkRed },
      children: [new Paragraph({ children: [new TextRun({ text: h, bold: true, size: 18, color: C.white, font: "Calibri" })] })],
    })),
  });

  const dataRows = rows.map((r, i) => new TableRow({
    children: r.map((cell, j) => new TableCell({
      width: { size: colWidths[j], type: WidthType.PERCENTAGE },
      shading: i % 2 === 0
        ? { type: ShadingType.SOLID, color: "FDEDEC", fill: "FDEDEC" }
        : { type: ShadingType.CLEAR, color: C.white, fill: C.white },
      children: [new Paragraph({ children: [new TextRun({ text: cell, size: 18, color: C.bodyText, font: "Calibri", bold: j === 0 })] })],
    })),
  }));

  return new Table({
    width: { size: 100, type: WidthType.PERCENTAGE },
    rows: [hdrRow, ...dataRows],
    borders: {
      top:     { style: BorderStyle.SINGLE, size: 4, color: "E8DAEF" },
      bottom:  { style: BorderStyle.SINGLE, size: 4, color: "E8DAEF" },
      left:    { style: BorderStyle.SINGLE, size: 4, color: "E8DAEF" },
      right:   { style: BorderStyle.SINGLE, size: 4, color: "E8DAEF" },
      insideH: { style: BorderStyle.SINGLE, size: 2, color: "E8DAEF" },
      insideV: { style: BorderStyle.SINGLE, size: 2, color: "E8DAEF" },
    },
  });
}

function imgBlock(buf, ext, wMm, hMm, captionText) {
  if (!buf) return [body("[Image not available]"), caption(captionText)];
  return [
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 80, after: 40 },
      children: [new ImageRun({
        data: buf,
        transformation: { width: wMm * 3.779528, height: hMm * 3.779528 },
        type: ext === "png" ? "png" : "jpg",
      })],
    }),
    caption(captionText),
  ];
}

// ── Disease builder ─────────────────────────────────────────────────────────
function diseaseSection(num, title, color, overview, ecgRows, notes, imgBuf, imgExt, imgCapt) {
  const elems = [];
  elems.push(sectionBanner(num, title, color));
  elems.push(sp(2));
  elems.push(subHeading("Overview", color));
  elems.push(body(overview));
  elems.push(subHeading("ECG Changes", color));
  elems.push(ecgTable(ecgRows));
  for (const n of notes) {
    elems.push(sp(1));
    elems.push(body(n));
  }
  if (imgBuf) {
    elems.push(sp(2));
    elems.push(...imgBlock(imgBuf, imgExt, 155, 72, imgCapt));
  }
  elems.push(hRule(color));
  return elems;
}

// ── Main ───────────────────────────────────────────────────────────────────
async function main() {
  console.log("Downloading ECG images...");
  const imgs = {};
  for (const [k, url] of Object.entries(IMG_URLS)) {
    process.stdout.write(`  ${k}... `);
    imgs[k] = await downloadImage(url);
    console.log(imgs[k] ? `OK (${imgs[k].length} bytes)` : "FAILED");
  }

  console.log("Building document...");

  const sections_children = [];

  // ── Cover ─────────────────────────────────────────────────────────────────
  sections_children.push(coverTitle("10 Common Heart Diseases"));
  sections_children.push(coverSubtitle("with ECG Changes & Diagnostic Images"));
  sections_children.push(sp(2));
  sections_children.push(body(
    "This reference guide presents 10 clinically important heart diseases, each with a structured " +
    "breakdown of ECG changes, key diagnostic features, and annotated electrocardiogram images. " +
    "Sourced from leading medical textbooks (Guyton & Hall, Ganong's, Harrison's, Braunwald's) and the LITFL ECG Library."
  ));
  sections_children.push(sp(2));

  // Infographic
  if (imgs.infographic) {
    sections_children.push(...imgBlock(imgs.infographic, "png", 160, 88,
      "Overview: Killer ECG Patterns — LITFL ECG Library (CC BY-NC-SA 4.0)"));
  }

  sections_children.push(sp(2));
  sections_children.push(subHeading("Quick Reference Summary", C.darkRed));
  sections_children.push(summaryTable());
  sections_children.push(new Paragraph({ children: [new PageBreak()] }));

  // ── 1. STEMI ───────────────────────────────────────────────────────────────
  sections_children.push(...diseaseSection(
    "1", "ST-Elevation Myocardial Infarction (STEMI)", C.darkRed,
    "STEMI results from complete occlusion of a coronary artery causing transmural ischemia and necrosis. " +
    "It is a time-critical emergency requiring immediate reperfusion therapy (primary PCI within 90 minutes). " +
    "The ECG is the primary diagnostic tool and localises the culprit artery.",
    [
      ["Hyperacute T waves",   "Earliest finding — tall, peaked T waves in affected territory. Appears within minutes of occlusion."],
      ["ST elevation",         "≥1 mm in 2+ contiguous limb leads, or ≥2 mm in precordial leads. Convex (tombstone) morphology in acute phase."],
      ["Reciprocal ST depression", "Mirror-image ST depression in leads opposite the infarct zone (e.g., inferior STEMI → ST↓ in I, aVL)."],
      ["Pathological Q waves", "Width >40 ms and depth >25% of R wave; appear hours-days after infarction; represent electrically silent necrosis."],
      ["T wave inversion",     "Subacute/chronic phase — indicates repolarisation abnormality over infarcted zone."],
      ["Localisation by leads","Anterior (V1-V4, LAD) | Inferior (II, III, aVF, RCA) | Lateral (I, aVL, V5-V6, LCx) | Posterior (ST depression V1-V3)."],
    ],
    ["The hallmark mechanism: infarcted fibres rapidly repolarise and sustain decreased resting membrane potential. " +
     "Both changes drive current toward the infarct, producing ST elevation in overlying leads and reciprocal depression in opposite leads. " +
     "(Ganong's Review of Medical Physiology, 26th Ed., p. 534)"],
    imgs.stemi, "jpg",
    "Inferior STEMI — massive 'tombstone' ST elevations in II, III, aVF with reciprocal ST depression in I, aVL. (LITFL ECG Library)"
  ));

  // ── 2. Atrial Fibrillation ─────────────────────────────────────────────────
  sections_children.push(...diseaseSection(
    "2", "Atrial Fibrillation (AF)", C.blue,
    "The most common sustained cardiac arrhythmia. Disorganised atrial electrical activity at 350-600 bpm " +
    "produces irregular ventricular response. Lifetime risk after age 40 is ~25%. Key complications: " +
    "haemodynamic compromise, cardiomyopathy, and thromboembolic stroke (requires anticoagulation).",
    [
      ["Absent P waves",          "Replaced by chaotic fibrillatory (f) waves at 350-600 bpm; baseline appears undulating or flat."],
      ["Irregularly irregular",   "HALLMARK — RR intervals vary unpredictably. No two consecutive RR intervals are equal."],
      ["Ventricular rate",        "100-180 bpm if uncontrolled; <100 bpm if rate-controlled or with complete AV block."],
      ["QRS morphology",          "Usually narrow and normal; wide if pre-existing BBB, aberrant conduction, or WPW co-exists."],
      ["Fibrillatory baseline",   "Fine (low voltage, <1 mm) or coarse (>1 mm amplitude). Coarse suggests recent onset or enlarged atria."],
    ],
    ["The ventricular irregularity arises because fibrillatory impulses reach the AV node randomly. " +
     "The AV node has a minimum refractory period of ~350 ms, and each subsequent impulse can arrive 0-600 ms later, " +
     "producing unpredictable beat-to-beat variation. (Guyton & Hall Textbook of Medical Physiology)"],
    imgs.af, "png",
    "AF (Lead II): absent P waves, irregularly irregular QRS complexes, chaotic baseline. (Guyton & Hall / Orris Medical Library)"
  ));

  // ── 3. Atrial Flutter ─────────────────────────────────────────────────────
  sections_children.push(...diseaseSection(
    "3", "Atrial Flutter", "1F618D",
    "A macro-reentrant supraventricular tachycardia driven by a reentry circuit in the right atrium. " +
    "Anticlockwise (typical) flutter accounts for ~90% of cases, producing a predictable atrial rate of ~300 bpm (range 250-350 bpm).",
    [
      ["Sawtooth flutter waves", "Regular negative deflections at ~300 bpm in inferior leads (II, III, aVF); upright in V1. No isoelectric baseline between waves."],
      ["Ventricular rate",       "A fraction of atrial rate: 2:1 block → 150 bpm (most common), 3:1 → 100 bpm, 4:1 → 75 bpm, variable block → irregular."],
      ["QRS morphology",         "Usually narrow and normal unless aberrant conduction or bundle branch block is present."],
      ["Regular ventricular",    "Ventricular response is regular when block ratio is fixed; irregular if AV conduction ratio varies."],
      ["vs AF",                  "Flutter = regular sawtooth waves at fixed ~300 bpm; AF = irregular chaotic baseline, no organised atrial waves."],
    ],
    [],
    imgs.flutter, "jpg",
    "Atrial flutter with 2:1 AV block: classic sawtooth flutter waves in inferior leads; ventricular rate ~150 bpm. (LITFL ECG Library)"
  ));

  sections_children.push(new Paragraph({ children: [new PageBreak()] }));

  // ── 4. Complete AV Block ──────────────────────────────────────────────────
  sections_children.push(...diseaseSection(
    "4", "Complete (3rd Degree) AV Heart Block", C.purple,
    "Complete failure of conduction between atria and ventricles. Atria and ventricles beat independently " +
    "at their intrinsic rates. Perfusion is maintained by junctional or ventricular escape rhythm. " +
    "This is a medical emergency often requiring urgent temporary pacing.",
    [
      ["Complete AV dissociation","P waves and QRS complexes are completely independent — no fixed PR relationship at all."],
      ["Atrial rate > ventricular","Sinus rate 60-100 bpm; ventricular escape: junctional 40-60 bpm (narrow QRS) or ventricular 20-40 bpm (wide QRS)."],
      ["Escape QRS morphology",   "Narrow if junctional escape (above His bifurcation); wide and bizarre if ventricular escape (below His)."],
      ["Slow ventricular rate",   "Bradycardia — typically 30-60 bpm; rate depends entirely on escape focus location."],
      ["P waves march through",   "P waves occur regularly at sinus rate but bear NO relationship to QRS complexes."],
    ],
    ["Complete AV block is a recognised complication of inferior STEMI (RCA occlusion causing AV nodal ischaemia), " +
     "medications (digoxin toxicity, beta-blockers, CCBs), infiltrative disease, and surgical trauma. " +
     "Inferior STEMI-related CHB is usually transient and responds to atropine."],
    imgs.chb, "jpg",
    "Complete heart block: slow regular ventricular escape rhythm; P waves (arrows) march independently at a faster rate. (LITFL ECG Library)"
  ));

  // ── 5. Acute Pericarditis ─────────────────────────────────────────────────
  sections_children.push(...diseaseSection(
    "5", "Acute Pericarditis", C.green,
    "Inflammation of the pericardial sac, most commonly viral (Coxsackievirus, echovirus). " +
    "ECG changes reflect diffuse myocardial surface irritation rather than regional ischaemia. " +
    "The ECG evolves through four characteristic stages over days to weeks.",
    [
      ["Stage 1 — Acute (hrs-days)", "DIFFUSE concave (saddle-shaped) ST elevation in ALL leads except aVR and V1. PR depression in most leads; PR elevation in aVR."],
      ["Stage 2 — ~1 week",          "ST segments and PR return to baseline. T wave flattening begins."],
      ["Stage 3 — After ST normal",  "Diffuse T wave inversion across multiple leads."],
      ["Stage 4 — Weeks-months",     "ECG normalisation or persistent T wave inversion."],
      ["PR depression",              "Atrial myocardial involvement — present in up to 80% of cases; most specific finding for pericarditis."],
      ["vs STEMI",                   "Pericarditis: diffuse, concave, no reciprocal ST↓ (except aVR/V1), PR depression. STEMI: regional, convex, reciprocal ST depression."],
    ],
    ["Key distinguishing features: saddle-shaped ST elevation that is DIFFUSE (all leads), accompanied by PR depression " +
     "and PR elevation in aVR. Obtain serial ECGs in all patients with chest pain. " +
     "(ESC Guidelines on Pericarditis; LITFL ECG Library)"],
    imgs.pericarditis, "jpg",
    "Acute pericarditis: diffuse concave ('saddle-shaped') ST elevation across multiple leads with PR depression. (LITFL ECG Library)"
  ));

  sections_children.push(new Paragraph({ children: [new PageBreak()] }));

  // ── 6. WPW ───────────────────────────────────────────────────────────────
  sections_children.push(...diseaseSection(
    "6", "Wolff-Parkinson-White (WPW) Syndrome", C.orange,
    "Pre-excitation syndrome caused by an accessory pathway (Bundle of Kent) that bypasses the AV node, " +
    "allowing impulses to reach the ventricles prematurely. In sinus rhythm the ECG shows the classic 'WPW triad'. " +
    "During AF or flutter, conduction via the accessory pathway can produce life-threatening ventricular rates.",
    [
      ["Short PR interval",  "< 120 ms — no physiological AV nodal delay; impulse bypasses AV node via accessory pathway."],
      ["Delta wave",         "Slurred, slow upstroke at the START of QRS — represents early (pre-)excitation of ventricular myocardium."],
      ["Wide QRS",           "> 120 ms — total QRS = delta wave (pre-excitation) + normal His-Purkinje activation."],
      ["ST-T changes",       "Secondary, discordant (opposite to QRS polarity) — not indicative of ischaemia."],
      ["Pseudo-infarct Q",   "Negative delta waves can mimic pathological Q waves; Type B WPW may mimic inferior or anteroseptal MI."],
      ["AF in WPW — EMERGENCY", "Extremely rapid (>200-300 bpm), irregularly irregular, wide bizarre QRS — can degenerate to VF. AV nodal blockers are CONTRAINDICATED."],
    ],
    ["WPW with AF is a life-threatening emergency. AV nodal blocking agents (verapamil, diltiazem, digoxin, adenosine) are " +
     "CONTRAINDICATED as they can accelerate conduction via the accessory pathway, precipitating VF. " +
     "Treatment: DC cardioversion or IV procainamide. Definitive cure is catheter ablation of the accessory pathway."],
    imgs.wpw_af, "jpg",
    "Pre-excited AF in WPW: chaotic, extremely rapid, wide irregular QRS complexes — ventricular rate >200 bpm. (LITFL ECG Library)"
  ));

  // ── 7. Ventricular Tachycardia ────────────────────────────────────────────
  sections_children.push(...diseaseSection(
    "7", "Ventricular Tachycardia (VT)", C.red,
    "Three or more consecutive ventricular ectopic beats at >100 bpm originating below the Bundle of His. " +
    "Monomorphic VT has uniform QRS morphology; polymorphic VT (including Torsades de Pointes) has varying morphology. " +
    "Sustained VT (>30 seconds or requiring termination) is a medical emergency.",
    [
      ["Wide QRS",              "> 120 ms (usually >140 ms); LBBB or RBBB morphology depending on site of origin."],
      ["Rate",                  "100-250 bpm; regular in monomorphic VT; irregular in polymorphic VT/Torsades."],
      ["AV dissociation",       "P waves march through independently of QRS complexes — pathognomonic of VT when visible (~50% of cases)."],
      ["Fusion beats",          "Partial sinus capture + VT = hybrid QRS morphology — PATHOGNOMONIC of VT."],
      ["Capture beats",         "Occasional narrow sinus-conducted beats 'capturing' the ventricle — PATHOGNOMONIC of VT."],
      ["Extreme axis deviation","Northwest axis (−90° to −180°) strongly supports VT over SVT with aberrancy."],
      ["Precordial concordance","All precordial leads uniformly positive (positive concordance) or negative (negative concordance) — strongly suggests VT."],
    ],
    ["Brugada criteria for distinguishing VT from SVT with aberrancy (any single criterion = VT): " +
     "(1) Absence of RS complex in all precordial leads; " +
     "(2) RS interval >100 ms in any precordial lead; " +
     "(3) AV dissociation present; " +
     "(4) Morphology criteria not met for SVT. If in doubt, treat as VT."],
    null, null, ""
  ));

  sections_children.push(new Paragraph({ children: [new PageBreak()] }));

  // ── 8. HCM ───────────────────────────────────────────────────────────────
  sections_children.push(...diseaseSection(
    "8", "Hypertrophic Cardiomyopathy (HCM)", C.teal,
    "A genetic cardiomyopathy (typically autosomal dominant, sarcomere protein mutations) characterised by " +
    "asymmetric ventricular hypertrophy, most often of the interventricular septum. " +
    "It is the most common cause of sudden cardiac death in young athletes under 35 years.",
    [
      ["LVH voltage criteria",   "Sokolow-Lyon: SV1 + RV5/V6 >35 mm; or RaVL >11 mm."],
      ["Dagger Q waves",         "Deep, narrow Q waves in lateral leads (I, aVL, V5-V6) and inferior leads — due to abnormal septal depolarisation. Narrower than ischaemic Q waves."],
      ["Deep T wave inversion",  "Widespread, often striking. Apical HCM: giant T wave inversions in V3-V5 up to 10-15 mm deep."],
      ["Left axis deviation",    "Due to hypertrophied septum altering the mean QRS vector."],
      ["ST depression",          "Lateral leads — strain pattern reflecting severe LVH."],
      ["Atrial fibrillation",    "Superimposed in 20-25% of HCM patients over their lifetime; worsens haemodynamics significantly."],
    ],
    ["A young patient with exertional symptoms and an ECG showing LVH + lateral Q waves + deep T inversions " +
     "MUST be suspected for HCM until proven otherwise. This pattern is frequently misread as 'prior lateral MI'. " +
     "HCM is the leading cause of sudden cardiac death in competitive athletes. (Kelly, Mattu & Brady 2007; LITFL ECG Library)"],
    imgs.hcm, "png",
    "HCM ECG: left ventricular hypertrophy, deep narrow Q waves in lateral leads, widespread ST depression and T wave inversion. (LITFL ECG Library)"
  ));

  // ── 9. Brugada Syndrome ───────────────────────────────────────────────────
  sections_children.push(...diseaseSection(
    "9", "Brugada Syndrome", C.darkGold,
    "An inherited sodium channelopathy (SCN5A gene mutation, autosomal dominant) causing life-threatening " +
    "ventricular arrhythmias and sudden cardiac death, predominantly in young males (20-40 years), often at rest or during sleep. " +
    "Triggers include fever, cocaine, and sodium channel blocking drugs.",
    [
      ["Type 1 — Diagnostic",  "COVED pattern: ST elevation ≥2 mm in V1-V3 descending into a NEGATIVE T wave. Spontaneous or drug-induced. THE ONLY diagnostic ECG pattern."],
      ["Type 2 — Suspicious",  "SADDLEBACK: ST elevation ≥2 mm in V1-V3, T wave upright or biphasic. Requires sodium channel blocker provocation test (ajmaline/flecainide)."],
      ["Type 3",               "ST elevation <1 mm in V1-V3. Not diagnostic on its own; may be baseline appearance between symptomatic episodes."],
      ["RBBB pattern",         "Incomplete or complete RBBB morphology frequently coexists with the Brugada pattern."],
      ["Dynamic / fluctuating","ECG pattern spontaneously fluctuates; may be intermittently normal — serial ECGs and provocation testing are important."],
      ["PR prolongation",      "Mild PR prolongation present in some cases due to SCN5A-mediated slowing of conduction."],
    ],
    ["Brugada pattern can be unmasked or accentuated by fever, sodium channel blockers (flecainide, ajmaline, procainamide), " +
     "and certain psychotropic drugs. All first-degree relatives require ECG screening. " +
     "ICD implantation is the only proven therapy for secondary prevention. " +
     "The Type 1 coved pattern is shown clearly in the Killer ECG infographic on the cover page."],
    null, null, ""
  ));

  sections_children.push(new Paragraph({ children: [new PageBreak()] }));

  // ── 10. DCM / Heart Failure ───────────────────────────────────────────────
  sections_children.push(...diseaseSection(
    "10", "Dilated Cardiomyopathy (DCM) / Heart Failure", C.gray,
    "DCM is characterised by ventricular dilatation and impaired systolic function (reduced EF). " +
    "It represents a common final pathway of multiple aetiologies: ischaemic, viral, alcoholic, peripartum, idiopathic. " +
    "ECG findings are non-specific but reflect underlying structural abnormalities.",
    [
      ["Left Bundle Branch Block (LBBB)", "Broad QRS >120 ms, broad notched R in I/aVL/V5-V6, deep S in V1; discordant ST-T changes. Implies significant structural disease."],
      ["LVH voltage",                     "Sokolow-Lyon criteria positive in many patients; reflects ventricular remodelling."],
      ["Poor R wave progression",         "Small or absent R waves V1-V4 — reflects anterior wall dysfunction or loss of viable myocardium from prior MI."],
      ["Pathological Q waves",            "If ischaemic aetiology — indicate prior MI territory and scarring."],
      ["Atrial fibrillation",             "Frequently superimposed; further worsens haemodynamics in already failing heart. Increases mortality ~30-40%."],
      ["Prolonged QRS (>120 ms)",         "Indicates ventricular dyssynchrony; QRS >150 ms with LBBB = strongest predictor of benefit from cardiac resynchronisation therapy (CRT)."],
      ["Sinus tachycardia",               "Compensatory response in decompensated heart failure; sympathetic activation."],
      ["Low voltage QRS",                 "All leads show reduced QRS amplitude if pericardial effusion or cardiac tamponade coexists."],
    ],
    ["QRS duration >150 ms with LBBB morphology is the strongest predictor of CRT response (EF improvement, symptoms, mortality). " +
     "The combination of AF + LBBB + poor R progression in a patient with breathlessness and peripheral oedema is the " +
     "classic presentation of dilated cardiomyopathy with heart failure."],
    null, null, ""
  ));

  // ── Final Summary ─────────────────────────────────────────────────────────
  sections_children.push(new Paragraph({ children: [new PageBreak()] }));
  sections_children.push(sectionBanner("★", "Complete Summary: 10 Heart Diseases at a Glance", C.darkRed));
  sections_children.push(sp(2));
  sections_children.push(summaryTable());
  sections_children.push(sp(4));
  sections_children.push(new Paragraph({
    spacing: { before: 120 },
    children: [new TextRun({
      text: "Sources: Guyton & Hall Textbook of Medical Physiology | Ganong's Review of Medical Physiology, 26th Ed. | " +
            "Harrison's Principles of Internal Medicine 22E | Braunwald's Heart Disease | " +
            "LITFL ECG Library — Burns & Buttner (CC BY-NC-SA 4.0) | ESC Guidelines on Pericarditis | Tintinalli's Emergency Medicine",
      size: 16, color: C.gray, italics: true, font: "Calibri",
    })],
  }));

  // ── Build document ────────────────────────────────────────────────────────
  const doc = new Document({
    creator: "Orris Medical Assistant",
    title: "10 Common Heart Diseases with ECG Changes",
    subject: "Cardiology ECG Reference Guide",
    description: "Comprehensive guide to ECG changes in 10 common heart diseases",
    sections: [{
      properties: {
        page: {
          margin: {
            top:    convertMillimetersToTwip(20),
            bottom: convertMillimetersToTwip(20),
            left:   convertMillimetersToTwip(20),
            right:  convertMillimetersToTwip(20),
          },
        },
      },
      headers: {
        default: new Header({
          children: [new Paragraph({
            alignment: AlignmentType.RIGHT,
            border: { bottom: { style: BorderStyle.SINGLE, size: 4, color: C.lightBlue } },
            children: [
              new TextRun({ text: "10 Common Heart Diseases with ECG Changes  |  ", size: 16, color: C.gray, font: "Calibri" }),
              new TextRun({ text: "Orris Medical Reference", size: 16, color: C.blue, bold: true, font: "Calibri" }),
            ],
          })],
        }),
      },
      footers: {
        default: new Footer({
          children: [new Paragraph({
            alignment: AlignmentType.CENTER,
            border: { top: { style: BorderStyle.SINGLE, size: 4, color: C.lightBlue } },
            children: [
              new TextRun({ text: "Page ", size: 16, color: C.gray, font: "Calibri" }),
              new TextRun({ children: [PageNumber.CURRENT], size: 16, color: C.gray, font: "Calibri" }),
              new TextRun({ text: " of ", size: 16, color: C.gray, font: "Calibri" }),
              new TextRun({ children: [PageNumber.TOTAL_PAGES], size: 16, color: C.gray, font: "Calibri" }),
            ],
          })],
        }),
      },
      children: sections_children,
    }],
  });

  const buffer = await Packer.toBuffer(doc);
  fs.writeFileSync(OUT, buffer);
  console.log(`\nSaved: ${OUT} (${(buffer.length / 1024).toFixed(0)} KB)`);
}

main().catch(err => { console.error(err); process.exit(1); });
Running Command

cd /home/daytona/workspace/ecg-guide && node build_docx.js 2>&1

Running Command

python3 /home/daytona/skills/docx/scripts/office/validate.py /home/daytona/works…

Running Command

# Validate manually by checking it's a valid ZIP with expected DOCX contents pyt…

The Word document is valid and ready. Here's your download link:

Heart Diseases ECG Guide

Word Document · DOCX

Document details: 1.56 MB, 35 internal parts
What's inside:
  • Cover page - title banner, intro text, LITFL Killer ECG infographic, full 10-disease summary table
  • 10 disease sections, each with:
    • Colour-coded section header (each disease has a unique colour)
    • Overview paragraph
    • Structured ECG changes table (feature + detailed explanation, alternating row shading)
    • Clinical notes
    • Real ECG images embedded for: STEMI, AF, Atrial Flutter, Complete Heart Block, Pericarditis, WPW with AF, and HCM
  • Final summary page with the complete at-a-glance table
  • Running header (title + "Orris Medical Reference") and page-numbered footer on every page
  • Fully editable in Microsoft Word or Google Docs

Html to print pdf

Writing File

~/ecg-guide/Heart_Diseases_ECG_Guide.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>10 Common Heart Diseases with ECG Changes</title>
<style>
  /* ── Reset & Base ── */
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  body {
    font-family: 'Segoe UI', Calibri, Arial, sans-serif;
    font-size: 13px;
    color: #2C3E50;
    background: #f4f6f9;
    line-height: 1.6;
  }

  /* ── Print Styles ── */
  @media print {
    body { background: #fff; font-size: 11px; }
    .no-print { display: none !important; }
    .page-break { page-break-before: always; }
    .disease-card { page-break-inside: avoid; box-shadow: none !important; border: 1px solid #ddd !important; }
    .cover { page-break-after: always; }
    @page { margin: 15mm 15mm 15mm 15mm; size: A4; }
    .print-btn { display: none; }
  }

  /* ── Print Button ── */
  .print-btn {
    position: fixed;
    top: 18px; right: 22px;
    background: #C0392B;
    color: #fff;
    border: none;
    padding: 12px 26px;
    font-size: 15px;
    font-weight: 700;
    border-radius: 8px;
    cursor: pointer;
    z-index: 1000;
    box-shadow: 0 4px 14px rgba(0,0,0,0.25);
    letter-spacing: 0.5px;
  }
  .print-btn:hover { background: #922B21; }

  /* ── Wrapper ── */
  .wrapper { max-width: 960px; margin: 0 auto; padding: 24px 20px 60px; }

  /* ── Cover ── */
  .cover {
    background: linear-gradient(135deg, #1A5276 0%, #154360 100%);
    border-radius: 12px;
    padding: 48px 40px 36px;
    margin-bottom: 32px;
    text-align: center;
    box-shadow: 0 6px 32px rgba(0,0,0,0.18);
  }
  .cover h1 {
    font-size: 36px;
    color: #fff;
    font-weight: 800;
    line-height: 1.2;
    margin-bottom: 8px;
    letter-spacing: -0.5px;
  }
  .cover h1 span { color: #F1948A; }
  .cover .subtitle {
    font-size: 16px;
    color: #AED6F1;
    margin-bottom: 24px;
  }
  .cover .intro {
    background: rgba(255,255,255,0.09);
    border-radius: 8px;
    padding: 16px 20px;
    color: #D6EAF8;
    font-size: 13px;
    text-align: left;
    line-height: 1.7;
    margin-bottom: 24px;
  }
  .cover img.infographic {
    width: 100%;
    max-width: 820px;
    border-radius: 8px;
    margin: 8px 0 20px;
    border: 2px solid rgba(255,255,255,0.15);
  }

  /* ── Summary Table ── */
  .summary-section { margin-bottom: 32px; }
  .summary-section h2 {
    font-size: 18px;
    color: #8B1A1A;
    border-left: 5px solid #C0392B;
    padding-left: 12px;
    margin-bottom: 12px;
    font-weight: 700;
  }
  table.summary {
    width: 100%;
    border-collapse: collapse;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.07);
    font-size: 12px;
  }
  table.summary thead tr { background: #8B1A1A; color: #fff; }
  table.summary thead th { padding: 10px 10px; text-align: left; font-weight: 700; }
  table.summary tbody tr:nth-child(even) { background: #FDEDEC; }
  table.summary tbody tr:nth-child(odd) { background: #fff; }
  table.summary td { padding: 8px 10px; border-bottom: 1px solid #F2D7D5; vertical-align: top; }
  table.summary td:first-child { font-weight: 700; color: #8B1A1A; width: 28px; }
  table.summary td:nth-child(2) { font-weight: 600; }

  /* ── Disease Cards ── */
  .disease-card {
    background: #fff;
    border-radius: 10px;
    margin-bottom: 28px;
    box-shadow: 0 3px 16px rgba(0,0,0,0.09);
    overflow: hidden;
  }
  .disease-header {
    display: flex;
    align-items: center;
    padding: 14px 20px;
    color: #fff;
    gap: 14px;
  }
  .disease-number {
    font-size: 32px;
    font-weight: 900;
    opacity: 0.85;
    min-width: 38px;
    line-height: 1;
  }
  .disease-title { font-size: 20px; font-weight: 700; line-height: 1.2; }
  .disease-body { padding: 18px 22px 20px; }

  /* ── Sub-sections ── */
  .sub-label {
    font-size: 12px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.8px;
    margin: 14px 0 6px;
    padding-bottom: 3px;
    border-bottom: 2px solid #EBF5FB;
  }
  .overview-text { color: #2C3E50; line-height: 1.7; margin-bottom: 4px; }

  /* ── ECG Table ── */
  table.ecg {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    border-radius: 6px;
    overflow: hidden;
    margin-bottom: 10px;
  }
  table.ecg thead tr { background: #1A5276; color: #fff; }
  table.ecg thead th { padding: 8px 12px; text-align: left; }
  table.ecg tbody tr:nth-child(even) { background: #EBF5FB; }
  table.ecg tbody tr:nth-child(odd)  { background: #fff; }
  table.ecg td { padding: 7px 12px; border-bottom: 1px solid #D6EAF8; vertical-align: top; }
  table.ecg td:first-child { font-weight: 700; color: #C0392B; width: 30%; }

  /* ── Notes ── */
  .note-box {
    background: #FDFEFE;
    border-left: 4px solid #AED6F1;
    border-radius: 4px;
    padding: 10px 14px;
    margin-top: 10px;
    font-size: 12px;
    color: #566573;
    line-height: 1.6;
  }

  /* ── ECG Image ── */
  .ecg-image-wrap {
    text-align: center;
    margin: 14px 0 4px;
  }
  .ecg-image-wrap img {
    max-width: 100%;
    width: 820px;
    border-radius: 6px;
    border: 1px solid #D6EAF8;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  }
  .img-caption {
    font-size: 11px;
    color: #7F8C8D;
    font-style: italic;
    margin-top: 5px;
    text-align: center;
  }

  /* ── Footer ── */
  .doc-footer {
    text-align: center;
    color: #95A5A6;
    font-size: 11px;
    margin-top: 40px;
    padding-top: 14px;
    border-top: 1px solid #D5DBDB;
    line-height: 1.8;
  }

  /* ── Colour map per disease ── */
  .c1  { background: #8B1A1A; }
  .c2  { background: #1A5276; }
  .c3  { background: #1F618D; }
  .c4  { background: #6C3483; }
  .c5  { background: #1E8449; }
  .c6  { background: #D35400; }
  .c7  { background: #C0392B; }
  .c8  { background: #117A65; }
  .c9  { background: #7D6608; }
  .c10 { background: #566573; }

  .sl1  { color: #8B1A1A; border-bottom-color: #F1948A; }
  .sl2  { color: #1A5276; border-bottom-color: #AED6F1; }
  .sl3  { color: #1F618D; border-bottom-color: #AED6F1; }
  .sl4  { color: #6C3483; border-bottom-color: #D2B4DE; }
  .sl5  { color: #1E8449; border-bottom-color: #A9DFBF; }
  .sl6  { color: #D35400; border-bottom-color: #FAD7A0; }
  .sl7  { color: #C0392B; border-bottom-color: #F1948A; }
  .sl8  { color: #117A65; border-bottom-color: #A2D9CE; }
  .sl9  { color: #7D6608; border-bottom-color: #F9E79F; }
  .sl10 { color: #566573; border-bottom-color: #CCD1D1; }
</style>
</head>
<body>

<button class="print-btn no-print" onclick="window.print()">🖨️ Print / Save as PDF</button>

<div class="wrapper">

  <!-- ══ COVER ══════════════════════════════════════════════════════════════ -->
  <div class="cover">
    <h1>10 Common <span>Heart Diseases</span></h1>
    <div class="subtitle">with ECG Changes &amp; Diagnostic Images</div>
    <div class="intro">
      This reference guide presents 10 clinically important heart diseases, each with a structured breakdown of
      ECG changes, key diagnostic features, and annotated electrocardiogram images. Sourced from leading medical
      textbooks (Guyton &amp; Hall, Ganong's, Harrison's, Braunwald's) and the LITFL ECG Library.
    </div>
    <img class="infographic"
         src="https://litfl.com/wp-content/uploads/2021/09/Killer-ECG-Part-1-Infographic.png"
         alt="Killer ECG Patterns Infographic - LITFL"/>
    <div style="font-size:11px;color:#7FB3D3;margin-top:4px;">
      Overview: Killer ECG Patterns — LITFL ECG Library (CC BY-NC-SA 4.0)
    </div>
  </div>

  <!-- ══ SUMMARY TABLE ════════════════════════════════════════════════════ -->
  <div class="summary-section">
    <h2>Quick Reference Summary</h2>
    <table class="summary">
      <thead>
        <tr>
          <th>#</th><th>Condition</th><th>Key ECG Hallmark</th><th>Rate</th><th>Rhythm</th>
        </tr>
      </thead>
      <tbody>
        <tr><td>1</td><td>STEMI</td><td>ST elevation + Q waves (regional)</td><td>Variable</td><td>Regular</td></tr>
        <tr><td>2</td><td>Atrial Fibrillation</td><td>No P waves, irregularly irregular</td><td>100-180 bpm</td><td>Irregular</td></tr>
        <tr><td>3</td><td>Atrial Flutter</td><td>Sawtooth waves ~300 bpm</td><td>150 bpm (2:1)</td><td>Regular</td></tr>
        <tr><td>4</td><td>Complete AV Block</td><td>P-QRS dissociation, escape rhythm</td><td>30-60 bpm</td><td>Regular</td></tr>
        <tr><td>5</td><td>Acute Pericarditis</td><td>Diffuse concave ST↑, PR depression</td><td>Normal</td><td>Regular</td></tr>
        <tr><td>6</td><td>WPW Syndrome</td><td>Delta wave, short PR, wide QRS</td><td>Variable</td><td>Variable</td></tr>
        <tr><td>7</td><td>Ventricular Tachycardia</td><td>Wide QRS, AV dissociation, fusion beats</td><td>100-250 bpm</td><td>Regular</td></tr>
        <tr><td>8</td><td>Hypertrophic CMP (HCM)</td><td>Dagger Q waves, deep T inversion, LVH</td><td>Normal</td><td>Regular</td></tr>
        <tr><td>9</td><td>Brugada Syndrome</td><td>Coved ST elevation V1-V3</td><td>Normal</td><td>Regular</td></tr>
        <tr><td>10</td><td>DCM / Heart Failure</td><td>LBBB, poor R progression, AF</td><td>Variable</td><td>Variable</td></tr>
      </tbody>
    </table>
  </div>

  <!-- ══ DISEASE 1: STEMI ══════════════════════════════════════════════════ -->
  <div class="disease-card">
    <div class="disease-header c1">
      <div class="disease-number">1</div>
      <div class="disease-title">ST-Elevation Myocardial Infarction (STEMI)</div>
    </div>
    <div class="disease-body">
      <div class="sub-label sl1">Overview</div>
      <p class="overview-text">STEMI results from complete occlusion of a coronary artery causing transmural ischemia and necrosis.
      It is a time-critical emergency requiring immediate reperfusion therapy (primary PCI within 90 minutes).
      The ECG is the primary diagnostic tool and directly localises the culprit artery.</p>

      <div class="sub-label sl1">ECG Changes</div>
      <table class="ecg">
        <thead><tr><th>ECG Feature</th><th>Details</th></tr></thead>
        <tbody>
          <tr><td>Hyperacute T waves</td><td>Earliest finding — tall, peaked T waves in affected territory. Appears within minutes of occlusion.</td></tr>
          <tr><td>ST elevation</td><td>≥1 mm in 2+ contiguous limb leads, or ≥2 mm in precordial leads. Convex (tombstone) morphology in acute phase.</td></tr>
          <tr><td>Reciprocal ST depression</td><td>Mirror-image ST depression in leads opposite the infarct (e.g., inferior STEMI → ST↓ in I, aVL).</td></tr>
          <tr><td>Pathological Q waves</td><td>Width >40 ms and depth >25% of R wave; appear hours-days after infarction; represent electrically silent necrosis.</td></tr>
          <tr><td>T wave inversion</td><td>Subacute/chronic phase — repolarisation abnormality over the infarcted zone.</td></tr>
          <tr><td>Localisation</td><td>Anterior (V1-V4, LAD) | Inferior (II, III, aVF, RCA) | Lateral (I, aVL, V5-V6, LCx) | Posterior (ST depression V1-V3)</td></tr>
        </tbody>
      </table>
      <div class="note-box">The hallmark mechanism: infarcted fibres rapidly repolarise and sustain decreased resting membrane potential.
      Both changes drive current toward the infarcted zone, producing ST elevation in overlying leads and reciprocal depression opposite.
      <em>(Ganong's Review of Medical Physiology, 26th Ed., p. 534)</em></div>

      <div class="ecg-image-wrap">
        <img src="https://litfl.com/wp-content/uploads/2018/08/ECG-Inferior-AMI-STEMI-Massive-tombstones.jpg"
             alt="Inferior STEMI with tombstone ST elevations"/>
        <div class="img-caption">Inferior STEMI — massive 'tombstone' ST elevations in II, III, aVF with reciprocal changes in I, aVL. (LITFL ECG Library)</div>
      </div>
    </div>
  </div>

  <!-- ══ DISEASE 2: Atrial Fibrillation ═══════════════════════════════════ -->
  <div class="disease-card">
    <div class="disease-header c2">
      <div class="disease-number">2</div>
      <div class="disease-title">Atrial Fibrillation (AF)</div>
    </div>
    <div class="disease-body">
      <div class="sub-label sl2">Overview</div>
      <p class="overview-text">The most common sustained cardiac arrhythmia. Disorganised atrial electrical activity at 350-600 bpm
      produces an irregular ventricular response. Lifetime risk after age 40 is ~25%. Key complications:
      haemodynamic compromise, tachycardia-induced cardiomyopathy, and thromboembolic stroke.</p>

      <div class="sub-label sl2">ECG Changes</div>
      <table class="ecg">
        <thead><tr><th>ECG Feature</th><th>Details</th></tr></thead>
        <tbody>
          <tr><td>Absent P waves</td><td>Replaced by chaotic fibrillatory (f) waves at 350-600 bpm; baseline appears undulating or flat.</td></tr>
          <tr><td>Irregularly irregular</td><td>HALLMARK — RR intervals vary unpredictably. No two consecutive RR intervals are equal.</td></tr>
          <tr><td>Ventricular rate</td><td>100-180 bpm if uncontrolled; &lt;100 bpm if rate-controlled or with complete AV block.</td></tr>
          <tr><td>QRS morphology</td><td>Usually narrow and normal; wide if pre-existing BBB, aberrant conduction, or WPW co-exists.</td></tr>
          <tr><td>Fibrillatory baseline</td><td>Fine (&lt;1 mm) or coarse (&gt;1 mm). Coarse suggests recent onset or enlarged atria.</td></tr>
        </tbody>
      </table>
      <div class="note-box">The ventricular irregularity arises because fibrillatory impulses reach the AV node randomly.
      The AV node has a minimum refractory period of ~350 ms, producing unpredictable beat-to-beat variation.
      <em>(Guyton &amp; Hall Textbook of Medical Physiology)</em></div>

      <div class="ecg-image-wrap">
        <img src="https://cdn.orris.care/cdss_images/802bd5b8c1671f423278040f1bd2e654318d2d016ff4107de44a3677b224d105.png"
             alt="Atrial Fibrillation ECG"/>
        <div class="img-caption">AF (Lead II): absent P waves, irregularly irregular QRS complexes, chaotic baseline. (Guyton &amp; Hall / Orris Medical Library)</div>
      </div>
    </div>
  </div>

  <!-- ══ DISEASE 3: Atrial Flutter ════════════════════════════════════════ -->
  <div class="disease-card">
    <div class="disease-header c3">
      <div class="disease-number">3</div>
      <div class="disease-title">Atrial Flutter</div>
    </div>
    <div class="disease-body">
      <div class="sub-label sl3">Overview</div>
      <p class="overview-text">A macro-reentrant supraventricular tachycardia driven by a reentry circuit within the right atrium.
      Anticlockwise (typical) flutter accounts for ~90% of cases, with a predictable atrial rate of ~300 bpm (range 250-350 bpm).</p>

      <div class="sub-label sl3">ECG Changes</div>
      <table class="ecg">
        <thead><tr><th>ECG Feature</th><th>Details</th></tr></thead>
        <tbody>
          <tr><td>Sawtooth flutter waves</td><td>Regular negative deflections at ~300 bpm in inferior leads (II, III, aVF); upright in V1. No isoelectric baseline.</td></tr>
          <tr><td>Ventricular rate</td><td>Fraction of atrial rate: 2:1 → 150 bpm (most common), 3:1 → 100 bpm, 4:1 → 75 bpm, or variable.</td></tr>
          <tr><td>QRS morphology</td><td>Usually narrow and normal unless aberrant conduction or bundle branch block is present.</td></tr>
          <tr><td>Rhythm</td><td>Ventricular response is regular when block ratio is fixed; irregular if AV conduction ratio varies.</td></tr>
          <tr><td>vs AF</td><td>Flutter = regular sawtooth waves at fixed ~300 bpm; AF = irregular chaotic baseline with no organised atrial waves.</td></tr>
        </tbody>
      </table>

      <div class="ecg-image-wrap">
        <img src="https://litfl.com/wp-content/uploads/2018/08/ECG-Atrial-Flutter-2-1-block.jpg"
             alt="Atrial Flutter 2:1 block ECG"/>
        <div class="img-caption">Atrial flutter with 2:1 AV block: classic sawtooth flutter waves in inferior leads; ventricular rate ~150 bpm. (LITFL ECG Library)</div>
      </div>
    </div>
  </div>

  <div class="page-break"></div>

  <!-- ══ DISEASE 4: Complete AV Block ═════════════════════════════════════ -->
  <div class="disease-card">
    <div class="disease-header c4">
      <div class="disease-number">4</div>
      <div class="disease-title">Complete (3rd Degree) AV Heart Block</div>
    </div>
    <div class="disease-body">
      <div class="sub-label sl4">Overview</div>
      <p class="overview-text">Complete failure of conduction between the atria and ventricles. Atria and ventricles beat
      independently at their own intrinsic rates. Perfusion is maintained by junctional or ventricular escape rhythm.
      This is a medical emergency often requiring urgent temporary pacing.</p>

      <div class="sub-label sl4">ECG Changes</div>
      <table class="ecg">
        <thead><tr><th>ECG Feature</th><th>Details</th></tr></thead>
        <tbody>
          <tr><td>Complete AV dissociation</td><td>P waves and QRS complexes are completely independent — no fixed PR relationship whatsoever.</td></tr>
          <tr><td>Atrial rate &gt; ventricular</td><td>Sinus rate 60-100 bpm; ventricular escape: junctional 40-60 bpm (narrow QRS) or ventricular 20-40 bpm (wide QRS).</td></tr>
          <tr><td>Escape QRS morphology</td><td>Narrow if junctional escape (above His bifurcation); wide and bizarre if ventricular escape (below His).</td></tr>
          <tr><td>Bradycardia</td><td>Slow ventricular rate (30-60 bpm); rate depends entirely on escape focus location.</td></tr>
          <tr><td>P waves march through</td><td>P waves occur regularly at sinus rate but bear NO relationship to the timing of QRS complexes.</td></tr>
        </tbody>
      </table>
      <div class="note-box">Complete AV block complicates inferior STEMI (RCA occlusion → AV nodal ischaemia),
      medication toxicity (digoxin, beta-blockers, CCBs), infiltrative disease, and cardiac surgery.
      Inferior STEMI-related CHB is usually transient and responds to atropine.</div>

      <div class="ecg-image-wrap">
        <img src="https://litfl.com/wp-content/uploads/2018/08/ECG-Complete-heart-block-CHB-1024x498.jpg"
             alt="Complete Heart Block ECG"/>
        <div class="img-caption">Complete heart block: slow regular ventricular escape rhythm; P waves march through independently at a faster rate. (LITFL ECG Library)</div>
      </div>
    </div>
  </div>

  <!-- ══ DISEASE 5: Acute Pericarditis ════════════════════════════════════ -->
  <div class="disease-card">
    <div class="disease-header c5">
      <div class="disease-number">5</div>
      <div class="disease-title">Acute Pericarditis</div>
    </div>
    <div class="disease-body">
      <div class="sub-label sl5">Overview</div>
      <p class="overview-text">Inflammation of the pericardial sac, most commonly viral (Coxsackievirus, echovirus).
      ECG changes reflect diffuse myocardial surface irritation rather than regional ischaemia.
      The ECG evolves through four characteristic stages over days to weeks.</p>

      <div class="sub-label sl5">ECG Changes</div>
      <table class="ecg">
        <thead><tr><th>ECG Feature</th><th>Details</th></tr></thead>
        <tbody>
          <tr><td>Stage 1 — Acute (hrs-days)</td><td>DIFFUSE concave (saddle-shaped) ST elevation in ALL leads except aVR and V1. PR depression in most leads; PR elevation in aVR.</td></tr>
          <tr><td>Stage 2 — ~1 week</td><td>ST segments and PR return to baseline. T wave flattening begins.</td></tr>
          <tr><td>Stage 3 — After ST normal</td><td>Diffuse T wave inversion across multiple leads.</td></tr>
          <tr><td>Stage 4 — Weeks-months</td><td>ECG normalisation or persistent T wave inversion.</td></tr>
          <tr><td>PR depression</td><td>Atrial myocardial involvement — present in up to 80% of cases; most specific ECG finding for pericarditis.</td></tr>
          <tr><td>vs STEMI</td><td>Pericarditis: diffuse, concave, no reciprocal ST↓ (except aVR/V1), PR depression. STEMI: regional, convex, reciprocal ST depression.</td></tr>
        </tbody>
      </table>
      <div class="note-box">Key: look for the 'saddle shape' of concave ST elevation that is DIFFUSE (all leads),
      accompanied by PR depression and PR elevation in aVR. Serial ECGs are essential in all patients with chest pain.
      <em>(ESC Guidelines on Pericarditis; LITFL ECG Library)</em></div>

      <div class="ecg-image-wrap">
        <img src="https://litfl.com/wp-content/uploads/2018/08/ECG-Pericarditis.jpg"
             alt="Acute Pericarditis ECG"/>
        <div class="img-caption">Acute pericarditis: diffuse concave ('saddle-shaped') ST elevation across multiple leads with PR depression. (LITFL ECG Library)</div>
      </div>
    </div>
  </div>

  <div class="page-break"></div>

  <!-- ══ DISEASE 6: WPW ════════════════════════════════════════════════════ -->
  <div class="disease-card">
    <div class="disease-header c6">
      <div class="disease-number">6</div>
      <div class="disease-title">Wolff-Parkinson-White (WPW) Syndrome</div>
    </div>
    <div class="disease-body">
      <div class="sub-label sl6">Overview</div>
      <p class="overview-text">Pre-excitation syndrome caused by an accessory pathway (Bundle of Kent) that bypasses the AV node,
      allowing impulses to reach the ventricles prematurely. In sinus rhythm, the ECG shows the classic 'WPW triad'.
      During AF or flutter, accessory pathway conduction can produce life-threatening ventricular rates.</p>

      <div class="sub-label sl6">ECG Changes</div>
      <table class="ecg">
        <thead><tr><th>ECG Feature</th><th>Details</th></tr></thead>
        <tbody>
          <tr><td>Short PR interval</td><td>&lt;120 ms — no physiological AV nodal delay; impulse bypasses AV node via accessory pathway.</td></tr>
          <tr><td>Delta wave</td><td>Slurred, slow upstroke at the START of QRS — represents early (pre-)excitation of ventricular myocardium.</td></tr>
          <tr><td>Wide QRS</td><td>&gt;120 ms — total QRS = delta wave (pre-excitation) + normal His-Purkinje activation.</td></tr>
          <tr><td>ST-T changes</td><td>Secondary, discordant (opposite to QRS polarity) — not indicative of ischaemia.</td></tr>
          <tr><td>Pseudo-infarct Q waves</td><td>Negative delta waves can mimic pathological Q waves; Type B WPW may mimic inferior or anteroseptal MI.</td></tr>
          <tr><td>AF in WPW — EMERGENCY</td><td>Extremely rapid (&gt;200-300 bpm), irregularly irregular, wide bizarre QRS — can degenerate to VF. AV nodal blockers CONTRAINDICATED.</td></tr>
        </tbody>
      </table>
      <div class="note-box">⚠️ <strong>WPW with AF is a medical emergency.</strong> AV nodal blocking agents (verapamil, diltiazem, digoxin, adenosine)
      are CONTRAINDICATED — they can accelerate accessory pathway conduction, precipitating VF.
      Treatment: DC cardioversion or IV procainamide. Definitive cure: catheter ablation.</div>

      <div class="ecg-image-wrap">
        <img src="https://litfl.com/wp-content/uploads/2018/08/ECG-WPW-Atrial-fibrillation-3.jpg"
             alt="WPW with AF ECG"/>
        <div class="img-caption">Pre-excited AF in WPW: chaotic, extremely rapid, wide irregular QRS complexes — ventricular rate &gt;200 bpm. (LITFL ECG Library)</div>
      </div>
    </div>
  </div>

  <!-- ══ DISEASE 7: Ventricular Tachycardia ═══════════════════════════════ -->
  <div class="disease-card">
    <div class="disease-header c7">
      <div class="disease-number">7</div>
      <div class="disease-title">Ventricular Tachycardia (VT)</div>
    </div>
    <div class="disease-body">
      <div class="sub-label sl7">Overview</div>
      <p class="overview-text">Three or more consecutive ventricular ectopic beats at &gt;100 bpm originating below the Bundle of His.
      Monomorphic VT has uniform QRS morphology; polymorphic VT (including Torsades de Pointes) has varying morphology.
      Sustained VT (&gt;30 seconds) is a medical emergency.</p>

      <div class="sub-label sl7">ECG Changes</div>
      <table class="ecg">
        <thead><tr><th>ECG Feature</th><th>Details</th></tr></thead>
        <tbody>
          <tr><td>Wide QRS</td><td>&gt;120 ms (usually &gt;140 ms); LBBB or RBBB morphology depending on site of origin.</td></tr>
          <tr><td>Rate</td><td>100-250 bpm; regular in monomorphic VT; irregular in polymorphic VT/Torsades de Pointes.</td></tr>
          <tr><td>AV dissociation</td><td>P waves march through independently of QRS — pathognomonic of VT when visible (~50% of cases).</td></tr>
          <tr><td>Fusion beats</td><td>Partial sinus capture + VT = hybrid QRS morphology — PATHOGNOMONIC of VT.</td></tr>
          <tr><td>Capture beats</td><td>Occasional narrow sinus-conducted beats 'capturing' the ventricle — PATHOGNOMONIC of VT.</td></tr>
          <tr><td>Extreme axis deviation</td><td>Northwest axis (−90° to −180°) strongly supports VT over SVT with aberrancy.</td></tr>
          <tr><td>Precordial concordance</td><td>All precordial leads uniformly positive or uniformly negative — strongly suggests VT.</td></tr>
        </tbody>
      </table>
      <div class="note-box"><strong>Brugada criteria</strong> — if ANY single criterion is met, diagnose VT:
      (1) Absence of RS complex in all precordial leads;
      (2) RS interval &gt;100 ms in any precordial lead;
      (3) AV dissociation present;
      (4) Morphology criteria not met for SVT with aberrancy. <em>When in doubt, treat as VT.</em></div>
    </div>
  </div>

  <div class="page-break"></div>

  <!-- ══ DISEASE 8: HCM ════════════════════════════════════════════════════ -->
  <div class="disease-card">
    <div class="disease-header c8">
      <div class="disease-number">8</div>
      <div class="disease-title">Hypertrophic Cardiomyopathy (HCM)</div>
    </div>
    <div class="disease-body">
      <div class="sub-label sl8">Overview</div>
      <p class="overview-text">A genetic cardiomyopathy (autosomal dominant, sarcomere protein mutations) characterised by
      asymmetric ventricular hypertrophy, most often of the interventricular septum.
      It is the most common cause of sudden cardiac death in young athletes under 35 years.</p>

      <div class="sub-label sl8">ECG Changes</div>
      <table class="ecg">
        <thead><tr><th>ECG Feature</th><th>Details</th></tr></thead>
        <tbody>
          <tr><td>LVH voltage criteria</td><td>Sokolow-Lyon: SV1 + RV5/V6 &gt;35 mm; or RaVL &gt;11 mm.</td></tr>
          <tr><td>Dagger Q waves</td><td>Deep, narrow Q waves in lateral (I, aVL, V5-V6) and inferior leads — due to abnormal septal depolarisation. Narrower than ischaemic Q waves.</td></tr>
          <tr><td>Deep T wave inversion</td><td>Widespread, often striking. Apical HCM: giant T wave inversions in V3-V5 up to 10-15 mm deep.</td></tr>
          <tr><td>Left axis deviation</td><td>Due to hypertrophied septum altering the mean QRS vector.</td></tr>
          <tr><td>ST depression</td><td>Lateral leads — strain pattern reflecting severe LVH.</td></tr>
          <tr><td>Atrial fibrillation</td><td>Superimposed in 20-25% of HCM patients over their lifetime; significantly worsens haemodynamics.</td></tr>
        </tbody>
      </table>
      <div class="note-box">A young patient with exertional symptoms and an ECG showing LVH + lateral Q waves + deep T inversions
      MUST be suspected for HCM until proven otherwise. This pattern is frequently misread as 'prior lateral MI'.
      HCM is the leading cause of sudden cardiac death in competitive athletes.
      <em>(Kelly, Mattu &amp; Brady 2007; LITFL ECG Library)</em></div>

      <div class="ecg-image-wrap">
        <img src="https://litfl.com/wp-content/uploads/2021/04/HCM-ECG.png"
             alt="HCM ECG"/>
        <div class="img-caption">HCM ECG: LVH voltage, deep narrow Q waves in lateral leads, widespread ST depression and T wave inversion. (LITFL ECG Library)</div>
      </div>
    </div>
  </div>

  <!-- ══ DISEASE 9: Brugada ════════════════════════════════════════════════ -->
  <div class="disease-card">
    <div class="disease-header c9">
      <div class="disease-number">9</div>
      <div class="disease-title">Brugada Syndrome</div>
    </div>
    <div class="disease-body">
      <div class="sub-label sl9">Overview</div>
      <p class="overview-text">An inherited sodium channelopathy (SCN5A gene mutation, autosomal dominant) causing life-threatening
      ventricular arrhythmias and sudden cardiac death, predominantly in young males (20-40 years),
      often at rest or during sleep. Triggers include fever, cocaine, and sodium channel blocking drugs.</p>

      <div class="sub-label sl9">ECG Changes</div>
      <table class="ecg">
        <thead><tr><th>ECG Feature</th><th>Details</th></tr></thead>
        <tbody>
          <tr><td>Type 1 — Diagnostic</td><td>COVED pattern: ST elevation ≥2 mm in V1-V3 descending into a NEGATIVE T wave. THE ONLY diagnostic ECG pattern.</td></tr>
          <tr><td>Type 2 — Suspicious</td><td>SADDLEBACK: ST elevation ≥2 mm in V1-V3, T wave upright or biphasic. Requires provocation test (ajmaline/flecainide).</td></tr>
          <tr><td>Type 3</td><td>ST elevation &lt;1 mm in V1-V3. Not diagnostic on its own.</td></tr>
          <tr><td>RBBB pattern</td><td>Incomplete or complete RBBB morphology frequently coexists with the Brugada pattern.</td></tr>
          <tr><td>Dynamic pattern</td><td>ECG pattern spontaneously fluctuates; may be intermittently normal. Serial ECGs important.</td></tr>
          <tr><td>PR prolongation</td><td>Mild PR prolongation in some cases due to SCN5A-mediated slowing of conduction.</td></tr>
        </tbody>
      </table>
      <div class="note-box">Brugada pattern can be unmasked by fever, sodium channel blockers (flecainide, ajmaline),
      and certain psychotropic drugs. All first-degree relatives require ECG screening.
      ICD implantation is the only proven therapy for secondary prevention.
      The Type 1 coved pattern in V1-V3 is shown in the Killer ECG infographic on the cover page.</div>
    </div>
  </div>

  <!-- ══ DISEASE 10: DCM / Heart Failure ══════════════════════════════════ -->
  <div class="disease-card">
    <div class="disease-header c10">
      <div class="disease-number">10</div>
      <div class="disease-title">Dilated Cardiomyopathy (DCM) / Heart Failure</div>
    </div>
    <div class="disease-body">
      <div class="sub-label sl10">Overview</div>
      <p class="overview-text">DCM is characterised by ventricular dilatation and impaired systolic function (reduced EF).
      It represents a common final pathway of multiple aetiologies: ischaemic, viral, alcoholic, peripartum, idiopathic.
      ECG findings are non-specific but reflect underlying structural abnormalities.</p>

      <div class="sub-label sl10">ECG Changes</div>
      <table class="ecg">
        <thead><tr><th>ECG Feature</th><th>Details</th></tr></thead>
        <tbody>
          <tr><td>Left Bundle Branch Block</td><td>Broad QRS &gt;120 ms, broad notched R in I/aVL/V5-V6, deep S in V1; discordant ST-T changes. Implies significant structural disease.</td></tr>
          <tr><td>LVH voltage</td><td>Sokolow-Lyon criteria positive in many patients; reflects ventricular remodelling.</td></tr>
          <tr><td>Poor R wave progression</td><td>Small or absent R waves V1-V4 — reflects anterior wall dysfunction or loss of viable myocardium.</td></tr>
          <tr><td>Pathological Q waves</td><td>If ischaemic aetiology — indicate prior MI territory with scarring.</td></tr>
          <tr><td>Atrial fibrillation</td><td>Frequently superimposed; further worsens haemodynamics. Increases mortality ~30-40%.</td></tr>
          <tr><td>Prolonged QRS (&gt;120 ms)</td><td>Indicates ventricular dyssynchrony; QRS &gt;150 ms + LBBB = strongest predictor of CRT benefit.</td></tr>
          <tr><td>Sinus tachycardia</td><td>Compensatory response in decompensated heart failure from sympathetic activation.</td></tr>
          <tr><td>Low voltage QRS</td><td>All leads show reduced QRS amplitude if pericardial effusion or cardiac tamponade coexists.</td></tr>
        </tbody>
      </table>
      <div class="note-box">QRS duration &gt;150 ms with LBBB morphology is the strongest predictor of cardiac resynchronisation therapy (CRT) response
      (EF improvement, symptom benefit, mortality reduction). The combination of AF + LBBB + poor R progression
      in a breathless patient with oedema is the classic presentation of dilated cardiomyopathy.</div>
    </div>
  </div>

  <div class="page-break"></div>

  <!-- ══ FINAL SUMMARY ═════════════════════════════════════════════════════ -->
  <div class="summary-section">
    <h2>&#9733; Complete Summary: 10 Heart Diseases at a Glance</h2>
    <table class="summary">
      <thead>
        <tr><th>#</th><th>Condition</th><th>Key ECG Hallmark</th><th>Rate</th><th>Rhythm</th></tr>
      </thead>
      <tbody>
        <tr><td>1</td><td>STEMI</td><td>ST elevation + Q waves (regional)</td><td>Variable</td><td>Regular</td></tr>
        <tr><td>2</td><td>Atrial Fibrillation</td><td>No P waves, irregularly irregular</td><td>100-180 bpm</td><td>Irregular</td></tr>
        <tr><td>3</td><td>Atrial Flutter</td><td>Sawtooth waves ~300 bpm</td><td>150 bpm (2:1)</td><td>Regular</td></tr>
        <tr><td>4</td><td>Complete AV Block</td><td>P-QRS dissociation, escape rhythm</td><td>30-60 bpm</td><td>Regular</td></tr>
        <tr><td>5</td><td>Acute Pericarditis</td><td>Diffuse concave ST↑, PR depression</td><td>Normal</td><td>Regular</td></tr>
        <tr><td>6</td><td>WPW Syndrome</td><td>Delta wave, short PR, wide QRS</td><td>Variable</td><td>Variable</td></tr>
        <tr><td>7</td><td>Ventricular Tachycardia</td><td>Wide QRS, AV dissociation, fusion beats</td><td>100-250 bpm</td><td>Regular</td></tr>
        <tr><td>8</td><td>Hypertrophic CMP (HCM)</td><td>Dagger Q waves, deep T inversion, LVH</td><td>Normal</td><td>Regular</td></tr>
        <tr><td>9</td><td>Brugada Syndrome</td><td>Coved ST elevation V1-V3</td><td>Normal</td><td>Regular</td></tr>
        <tr><td>10</td><td>DCM / Heart Failure</td><td>LBBB, poor R progression, AF</td><td>Variable</td><td>Variable</td></tr>
      </tbody>
    </table>
  </div>

  <!-- ══ FOOTER ════════════════════════════════════════════════════════════ -->
  <div class="doc-footer">
    <strong>Sources:</strong> Guyton &amp; Hall Textbook of Medical Physiology &nbsp;|&nbsp;
    Ganong's Review of Medical Physiology, 26th Ed. &nbsp;|&nbsp;
    Harrison's Principles of Internal Medicine 22E &nbsp;|&nbsp;
    Braunwald's Heart Disease &nbsp;|&nbsp;
    <a href="https://litfl.com/ecg-library/diagnosis" target="_blank">LITFL ECG Library</a> — Burns &amp; Buttner (CC BY-NC-SA 4.0)
    &nbsp;|&nbsp; ESC Guidelines on Pericarditis<br/>
    <em>Generated by Orris Medical Assistant &nbsp;·&nbsp; For educational use only</em>
  </div>

</div>

<script>
  // Auto-trigger print dialog hint
  document.querySelector('.print-btn').addEventListener('click', function() {
    window.print();
  });
</script>
</body>
</html>
Running Command

ls -lh /home/daytona/workspace/ecg-guide/Heart_Diseases_ECG_Guide.html && python…

Your HTML file is ready. Here's the download link:

Heart Diseases ECG Guide

HTML File · HTML


How to save as PDF

  1. Open the HTML file in your browser (Chrome or Edge recommended)
  2. A red 🖨️ Print / Save as PDF button appears in the top-right corner — click it
  3. In the print dialog:
    • Destination → "Save as PDF"
    • Paper size → A4
    • Margins → Default or Minimum
    • Background graphics → ✅ Enable this (to keep the coloured headers and table shading)
  4. Click Save

What's in the file (34 KB, fully self-contained):
  • Cover page with infographic + quick reference table
  • 10 colour-coded disease cards with ECG change tables + embedded ECG images (loaded from LITFL)
  • Full summary page at the end
  • Clean print CSS - page breaks at right places, no button in print output
This is a shared conversation. Sign in to Orris to start your own chat.