Tell me about physiological changes in pregnacy causes of these changes anaesthetic implications and also source

Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Searching Images

physiological changes in pregnancy cardiovascular respiratory

Summary : This figure presents the cardiovascular changes during pregnancy, including haemodynamic, ECG, and echocardiographic changes, with graphical and schematic representations of trends across trimesters, delivery, and postpartum.

line chart and schematic diagram:
# Haemodynamic Changes :
  • Line chart showing % change from pre-pregnancy for four parameters: cardiac output, plasma volume, heart rate, and peripheral vascular resistance/diastolic and systolic BP.
  • X-axis: Pregnancy timeline (1st trimester, 2nd trimester, 3rd trimester, Delivery, Post-partum).
  • Y-axis: % change from pre-pregnancy (range: -20% to +60%).
  • Cardiac output: Rises steeply to ~50% above baseline by 2nd trimester, peaks in 3rd trimester, drops sharply at delivery, returns to baseline by 6 weeks postpartum.
  • Plasma volume: Rises to ~40% above baseline, peaks in 3rd trimester, drops at delivery, returns to baseline postpartum.
  • Heart rate: Rises to ~20% above baseline, peaks in 3rd trimester, drops at delivery, returns to baseline postpartum.
  • Peripheral vascular resistance/diastolic and systolic BP: Drops to ~-20% below baseline, lowest in 2nd trimester, rises towards baseline at delivery and postpartum.

# ECG Changes :
  • Schematic comparison of normal ECG (black) and pregnancy ECG (purple).
  • PR interval shortened in pregnancy.
  • Prominent Q wave in pregnancy ECG.
  • Flattened/inverted T wave in pregnancy ECG.

# Echocardiographic Changes :
  • Schematic heart illustration with labelled changes.
  • Unchanged: Aortic root diameter, LVEF (left ventricular ejection fraction), RVEF (right ventricular ejection fraction), SPAP (systolic pulmonary artery pressure).
  • Small changes: Small pericardial effusion, increased RV (right ventricular) basal and mid diameters.
  • Increased LA (left atrial) size and volume, LVEDD (left ventricular end-diastolic diameter), LV (left ventricular) mass.

# Design Encodings :
  • Distinct coloured lines for each haemodynamic parameter.
  • Schematic ECG traces with colour-coded changes.
  • Heart diagram with labelled anatomical changes.

# Analysis :
  • Cardiac output, plasma volume, and heart rate all increase during pregnancy, peaking in the third trimester, and rapidly return to baseline postpartum.
  • Peripheral vascular resistance and blood pressure decrease during pregnancy, reaching their lowest in the second trimester, then return to baseline postpartum.
  • Pregnancy ECG shows shortened PR interval, prominent Q wave, and flattened/inverted T wave.
  • Echocardiographic changes include increased chamber sizes and mass, with most functional parameters unchanged except for small pericardial effusion and increased RV diameters.

Summary : This figure presents the cardiovascular changes during pregnancy, including haemodynamic, ECG, and echocardiographic changes, with graphical and schematic representations of trends across trimesters, delivery, and postpartum. line chart and schematic diagram: # Haemodynamic Changes : • Line chart showing % change from pre-pregnancy for four parameters: cardiac output, plasma volume, heart rate, and peripheral vascular resistance/diastolic and systolic BP. • X-axis: Pregnancy timeline (1st trimester, 2nd trimester, 3rd trimester, Delivery, Post-partum). • Y-axis: % change from pre-pregnancy (range: -20% to +60%). • Cardiac output: Rises steeply to ~50% above baseline by 2nd trimester, peaks in 3rd trimester, drops sharply at delivery, returns to baseline by 6 weeks postpartum. • Plasma volume: Rises to ~40% above baseline, peaks in 3rd trimester, drops at delivery, returns to baseline postpartum. • Heart rate: Rises to ~20% above baseline, peaks in 3rd trimester, drops at delivery, returns to baseline postpartum. • Peripheral vascular resistance/diastolic and systolic BP: Drops to ~-20% below baseline, lowest in 2nd trimester, rises towards baseline at delivery and postpartum. # ECG Changes : • Schematic comparison of normal ECG (black) and pregnancy ECG (purple). • PR interval shortened in pregnancy. • Prominent Q wave in pregnancy ECG. • Flattened/inverted T wave in pregnancy ECG. # Echocardiographic Changes : • Schematic heart illustration with labelled changes. • Unchanged: Aortic root diameter, LVEF (left ventricular ejection fraction), RVEF (right ventricular ejection fraction), SPAP (systolic pulmonary artery pressure). • Small changes: Small pericardial effusion, increased RV (right ventricular) basal and mid diameters. • Increased LA (left atrial) size and volume, LVEDD (left ventricular end-diastolic diameter), LV (left ventricular) mass. # Design Encodings : • Distinct coloured lines for each haemodynamic parameter. • Schematic ECG traces with colour-coded changes. • Heart diagram with labelled anatomical changes. # Analysis : • Cardiac output, plasma volume, and heart rate all increase during pregnancy, peaking in the third trimester, and rapidly return to baseline postpartum. • Peripheral vascular resistance and blood pressure decrease during pregnancy, reaching their lowest in the second trimester, then return to baseline postpartum. • Pregnancy ECG shows shortened PR interval, prominent Q wave, and flattened/inverted T wave. • Echocardiographic changes include increased chamber sizes and mass, with most functional parameters unchanged except for small pericardial effusion and increased RV diameters.

This cardiovascular magnetic resonance (CMR) comparison illustrates left ventricular (LV) remodeling and tissue characterization in a representative pregnant woman across three stages: 2nd trimester, 3rd trimester, and 1 month postpartum. The top rows feature structural cine images in short-axis (SAX) and four-chamber (4ch) views, demonstrating longitudinal changes in end-diastolic volume, ejection fraction, and LV mass. The bottom row presents native T1 mapping using the MOLLI (Modified Look-Locker Inversion recovery) sequence at 1.5 Tesla. These color-coded parametric maps represent myocardial T1 values, with a provided scale ranging from 0 to 2000 ms. Quantitatively, the native T1 values fluctuate from 1,206 ms in the 2nd trimester, decreasing to 1,025 ms in the 3rd trimester, and recovering to 1,128 ms postpartum. Visually, this is reflected in the shift from higher T1 areas (pink/yellow) to lower T1 regions (green/blue) and back. This visual comparison is educationally significant for understanding physiological cardiac adaptation during pregnancy and the role of non-contrast CMR in assessing myocardial tissue properties and peripartum cardiomyopathy (PPCM).

This cardiovascular magnetic resonance (CMR) comparison illustrates left ventricular (LV) remodeling and tissue characterization in a representative pregnant woman across three stages: 2nd trimester, 3rd trimester, and 1 month postpartum. The top rows feature structural cine images in short-axis (SAX) and four-chamber (4ch) views, demonstrating longitudinal changes in end-diastolic volume, ejection fraction, and LV mass. The bottom row presents native T1 mapping using the MOLLI (Modified Look-Locker Inversion recovery) sequence at 1.5 Tesla. These color-coded parametric maps represent myocardial T1 values, with a provided scale ranging from 0 to 2000 ms. Quantitatively, the native T1 values fluctuate from 1,206 ms in the 2nd trimester, decreasing to 1,025 ms in the 3rd trimester, and recovering to 1,128 ms postpartum. Visually, this is reflected in the shift from higher T1 areas (pink/yellow) to lower T1 regions (green/blue) and back. This visual comparison is educationally significant for understanding physiological cardiac adaptation during pregnancy and the role of non-contrast CMR in assessing myocardial tissue properties and peripartum cardiomyopathy (PPCM).

This physiological monitoring recording displays a four-channel data set captured via a transthoracic impedance system at a recording speed of 25 mm/s. The image illustrates a simultaneous recording of hemodynamics and respiratory patterns in a human subject. Channel R1 represents the base impedance measured in Ohms (Ω), oscillating between 30.9 and 31.2 Ω, reflecting transthoracic impedance changes related to cardiac cycle stroke volume. Synchronized with this is the ECG1 channel (millivolts, mV), showing standard QRS complexes and T waves used to correlate cardiac electrical activity with physical mechanical output. Channel R2 displays the impedance-derived breathing pattern, characterized by lower-frequency, smooth sinusoidal waves (48.0–51.0 Ω) that represent inhalation and exhalation cycles. ECG2 provides a secondary electrocardiographic lead for comprehensive rhythm analysis. This multi-modal visualization is characteristic of rheocardiographic examinations, used to calculate stroke volume and cardiac output by measuring the resistance of tissues to high-frequency alternating current. Such measurements are essential for evaluating cardiovascular and respiratory performance, particularly during or after physical activity.

This physiological monitoring recording displays a four-channel data set captured via a transthoracic impedance system at a recording speed of 25 mm/s. The image illustrates a simultaneous recording of hemodynamics and respiratory patterns in a human subject. Channel R1 represents the base impedance measured in Ohms (Ω), oscillating between 30.9 and 31.2 Ω, reflecting transthoracic impedance changes related to cardiac cycle stroke volume. Synchronized with this is the ECG1 channel (millivolts, mV), showing standard QRS complexes and T waves used to correlate cardiac electrical activity with physical mechanical output. Channel R2 displays the impedance-derived breathing pattern, characterized by lower-frequency, smooth sinusoidal waves (48.0–51.0 Ω) that represent inhalation and exhalation cycles. ECG2 provides a secondary electrocardiographic lead for comprehensive rhythm analysis. This multi-modal visualization is characteristic of rheocardiographic examinations, used to calculate stroke volume and cardiac output by measuring the resistance of tissues to high-frequency alternating current. Such measurements are essential for evaluating cardiovascular and respiratory performance, particularly during or after physical activity.

This physiological modeling data presents four time-series plots derived from a cardiovascular-respiratory interaction simulation, specifically the Jallon heart-lung model. Plot (a) displays respiratory muscle pressure (Pmus) in mmHg over 20 seconds, showing a sinusoidal oscillatory pattern with a visible non-stationary upward drift in both peak and trough values, highlighted by red trend lines. Plot (b) illustrates left ventricular volume (Vlv) in liters, demonstrating high-frequency cardiac oscillations superimposed on slower respiratory variations. Plot (c) shows alveolar volume (Valv) in liters over 50 seconds; red trend lines accentuate a pathological decrease in the overall range of ventilation over time. Plot (d) tracks thoracic volume (Vth) in liters, showing periodic fluctuations corresponding to the respiratory cycle. Collectively, these graphs illustrate model instability where non-stationary behavior leads to an unbounded increase in muscular pressure and a corresponding decline in pulmonary volumes, serving as an educational example of computational model drift in medical physiological systems.

This physiological modeling data presents four time-series plots derived from a cardiovascular-respiratory interaction simulation, specifically the Jallon heart-lung model. Plot (a) displays respiratory muscle pressure (Pmus) in mmHg over 20 seconds, showing a sinusoidal oscillatory pattern with a visible non-stationary upward drift in both peak and trough values, highlighted by red trend lines. Plot (b) illustrates left ventricular volume (Vlv) in liters, demonstrating high-frequency cardiac oscillations superimposed on slower respiratory variations. Plot (c) shows alveolar volume (Valv) in liters over 50 seconds; red trend lines accentuate a pathological decrease in the overall range of ventilation over time. Plot (d) tracks thoracic volume (Vth) in liters, showing periodic fluctuations corresponding to the respiratory cycle. Collectively, these graphs illustrate model instability where non-stationary behavior leads to an unbounded increase in muscular pressure and a corresponding decline in pulmonary volumes, serving as an educational example of computational model drift in medical physiological systems.

I now have everything I need to write a comprehensive answer. Let me compile it:

Physiological Changes in Pregnancy: Causes and Anaesthetic Implications

Sources: Barash, Cullen & Stoelting's Clinical Anesthesia, 9e (Ch. 41) | Morgan & Mikhail's Clinical Anesthesiology, 7e (Ch. Obstetric Anesthesia)

Overview

Pregnancy is characterised by significant anatomical and physiological changes across multiple organ systems. These changes are primarily driven by hormonal shifts (especially progesterone, relaxin, oestrogen, and placental hormones) and mechanical compression by the gravid uterus. They begin as early as the first trimester and return to pre-pregnancy baseline within weeks to months after delivery.
Cardiovascular changes in pregnancy across trimesters

Summary Table of Key Changes at Term

VariableChangeMagnitude
Plasma volume40-50%
Total blood volume40%
Haemoglobin11-12 g/dL
Fibrinogen~100%
Serum cholinesterase activity20-30%
Cardiac output30-50%
Systemic vascular resistance20-50%
Systemic blood pressureSlight
Functional residual capacity (FRC)20-30%
Minute ventilation50%
Alveolar ventilation70%
Oxygen consumption20%
Arterial CO2 tension (PaCO2)~10 mmHg (to ~30 mmHg)
Arterial O2 tension (PaO2)~10 mmHg (to ~106 mmHg)
Minimum alveolar concentration (MAC)32-40%

1. Airway and Respiratory Changes

Changes and Causes

Airway
  • Capillary engorgement of nasal, oropharyngeal, and laryngeal mucosa throughout pregnancy due to increased extracellular fluid and hormonal changes (oestrogen)
  • Airway oedema worsens in preeclampsia, after active pushing in the second stage of labour, and with tocolytic therapy
  • Mallampati score tends to increase throughout pregnancy and labour
  • Breast engorgement further impairs laryngoscopic access
Respiratory volumes
  • Progesterone acts on the respiratory centre to increase respiratory drive
  • Tidal volume (TV) increases by 45%; respiratory rate increases slightly - together these produce a 50% increase in minute ventilation at term
  • FRC decreases by up to 30% due to cephalad diaphragm displacement by the gravid uterus (residual volume falls 25%, expiratory reserve volume falls 20%)
  • Closing volume and closing capacity are unchanged, but FRC may fall below closing capacity in the supine or Trendelenburg position
  • FEV1, FVC, FEV1/FVC, and total lung capacity remain relatively unchanged
  • Alveolar ventilation increases by 70%, producing compensated respiratory alkalosis: pH 7.42-7.46, PaCO2 ~30 mmHg, PaO2 ~106 mmHg
  • Oxygen consumption increases by 20-21% at rest; rises to 45% above baseline in the first stage of labour and 75% in the second stage

Anaesthetic Implications

  1. Difficult airway: Nasal intubation is avoided (risk of haemorrhage). A short-handled laryngoscope is recommended. Failed intubation is more likely - anticipate and prepare for it.
  2. Rapid desaturation: The combination of reduced FRC + increased oxygen consumption means apnoeic episodes (e.g., during RSI) are very poorly tolerated. Preoxygenation with 100% O2 for ≥3 minutes (or 4 vital capacity breaths) is mandatory before induction of general anaesthesia.
  3. Faster inhalational induction/emergence: Increased alveolar ventilation + decreased FRC accelerates the uptake and elimination of volatile anaesthetic agents.
  4. Reduced MAC: MAC for volatile agents is reduced by 32-40% - attributed to progesterone's sedative effect and possibly endorphins. Lower doses of volatile agents are needed.
  5. Target PaCO2 ~30 mmHg during controlled ventilation to match the natural state of pregnancy; hyperventilation beyond this causes uterine artery vasoconstriction and fetal compromise.

2. Cardiovascular Changes

Changes and Causes

  • Cardiac output (CO) rises 30-50% starting in the first trimester, primarily due to progesterone and relaxin causing peripheral vasodilation
    • Stroke volume increases 20-50%
    • Heart rate increases ~15 bpm
  • Systemic vascular resistance (SVR) falls 20-50% - mediated by progesterone, relaxin, and nitric oxide
  • Blood pressure falls slightly despite increased CO, because of the fall in SVR (most pronounced in the second trimester)
  • CO peaks during the second stage of labour (catecholamine surge with pain) and immediately after delivery (uterine contraction causes autotransfusion)
  • Aortocaval compression: The gravid uterus compresses the inferior vena cava and aorta in the supine position from about 20 weeks gestation, reducing venous return and CO by up to 30% (supine hypotensive syndrome). The aorta is also compressed, reducing perfusion pressure to the uteroplacental bed.
  • ECG changes: shortened PR interval, axis deviation, prominent Q waves, flattened/inverted T waves in III and aVF

Anaesthetic Implications

  1. Left uterine displacement (LUD): Mandatory from 20 weeks - a wedge under the right hip (15° tilt) or manual displacement of the uterus relieves aortocaval compression and maintains venous return
  2. Hypotension after neuraxial block: Expected from sympathetic blockade in a patient with already-low SVR. Treat with IV phenylephrine (40-120 mcg bolus - preferred to maintain uterine blood flow), IV fluid preload or co-load, supplemental oxygen, and LUD
  3. Regional over general anaesthesia: Spinal or epidural anaesthesia is preferred for caesarean delivery - less haemodynamic fluctuation, avoids airway manipulation, reduces fetal drug exposure
  4. Increased CO alters drug distribution: Higher CO increases hepatic blood flow, accelerating clearance of some drugs

3. Haematological and Coagulation Changes

Changes and Causes

  • Plasma volume increases by 40-50% (driven by oestrogen, progesterone, aldosterone, and ADH)
  • Red cell mass increases by only 20-30%
  • This disproportionate expansion produces dilutional anaemia of pregnancy (physiological anaemia; Hb 11-12 g/dL)
  • Hypercoagulable state: Fibrinogen doubles (100% increase); factors VII, VIII, IX, X, and XII all increase; protein S falls; fibrinolytic activity is reduced - driven by placental hormones
  • Serum cholinesterase (pseudocholinesterase) activity falls 20-30% due to dilution and reduced synthesis
  • Platelet count falls slightly in many women (gestational thrombocytopenia)
  • White cell count rises (physiological leukocytosis)

Anaesthetic Implications

  1. Tolerance of blood loss: The increased blood volume provides a buffer - parturients can lose ~1000-1500 mL before significant haemodynamic compromise. However, rapid losses can still be fatal
  2. Succinylcholine: Cholinesterase activity is reduced, but the clinical effect is modest (slight prolongation of neuromuscular blockade). The drug remains safe and is still used for RSI
  3. DVT/PE risk: Hypercoagulability + venous stasis from uterine compression means thromboembolism is a leading cause of maternal death. Anticoagulants (e.g., LMWH) affect timing of regional techniques
  4. Neuraxial technique timing with anticoagulants: Regional anaesthesia is contraindicated in the presence of therapeutic anticoagulation; thrombocytopenia (platelets <70-80 × 10⁹/L) raises concern for epidural haematoma
  5. Point-of-care coagulation testing (TEG/ROTEM) is valuable in obstetric haemorrhage

4. Gastrointestinal Changes

Changes and Causes

  • Delayed gastric emptying and decreased lower oesophageal sphincter (LOS) tone due to progesterone's smooth muscle relaxant effect and mechanical displacement of the stomach by the gravid uterus
  • Gastric acid secretion increases (placental gastrin production)
  • Raised intra-abdominal pressure from the gravid uterus further reduces LOS competence
  • These factors increase the risk of regurgitation and pulmonary aspiration

Anaesthetic Implications

  1. All obstetric patients are considered to have a full stomach - regardless of the time since last oral intake (from ~16-20 weeks onwards)
  2. Aspiration prophylaxis: Antacids (sodium citrate), H2-antagonists (ranitidine) or proton pump inhibitors, and metoclopramide should be given before general anaesthesia
  3. Rapid sequence induction (RSI) with cricoid pressure: Mandatory for all pregnant patients receiving general anaesthesia after 20 weeks of gestation
  4. Regional anaesthesia is strongly preferred to avoid airway manipulation entirely

5. Renal Changes

Changes and Causes

  • Renal blood flow and GFR increase by 50% (driven by increased CO and reduced renal vascular resistance)
  • Serum creatinine and urea fall (normal creatinine in pregnancy is ~0.4-0.7 mg/dL)
  • Progesterone causes ureteral dilation and reduced ureteric tone (hydronephrosis of pregnancy)
  • Renal tubular reabsorption of glucose is overwhelmed - glycosuria may be present without diabetes
  • Sodium and water retention (via aldosterone and ADH) accounts for the 6-8 L increase in total body water

Anaesthetic Implications

  1. Drug dosing: Drugs excreted renally (e.g., antibiotics, magnesium) have altered clearance
  2. Glycosuria does not reliably diagnose gestational diabetes
  3. Magnesium toxicity: Mg²⁺ used to treat preeclampsia potentiates neuromuscular blockade and reduces MAC; monitor levels and titrate NMBDs carefully; calcium gluconate is the antidote

6. Hepatic System

Changes and Causes

  • Plasma albumin falls (dilutional), reducing protein binding of drugs
  • Serum alkaline phosphatase increases (placental origin - not hepatic)
  • Liver enzymes (AST, ALT) and bilirubin are essentially unchanged
  • Hepatic blood flow increases proportionally with CO

Anaesthetic Implications

  1. Increased free drug fraction: Lower albumin binding means more unbound (active) drug - especially relevant for highly protein-bound agents (e.g., bupivacaine, diazepam). This contributes to lower doses being needed
  2. Liver enzyme elevations in preeclampsia/HELLP are pathological and require dose adjustment

7. Neurological/CNS Changes

Changes and Causes

  • MAC is reduced by 32-40% - likely due to progesterone's sedating effect and elevated endorphin levels
  • Epidural and intrathecal local anaesthetic requirements are reduced by 25-40%: caused by (a) engorgement of epidural veins (from IVC compression), reducing the epidural space volume; (b) increased neural sensitivity possibly from hormonal effects; (c) reduced CSF volume

Anaesthetic Implications

  1. Reduce intrathecal/epidural doses: A spinal dose that would provide T4 anaesthesia in a non-pregnant patient will spread higher in a parturient
  2. Reduce induction agents and volatiles: Lower MAC means less propofol and volatile agent is needed; awareness at low doses is a risk if dosing is not adjusted
  3. Lumbar lordosis (and thoracic kyphosis) increases, affecting needle angulation for epidural and spinal placement

8. Endocrine/Metabolic Changes

Changes and Causes

  • Insulin resistance develops due to human placental lactogen (HPL), progesterone, and cortisol - causes gestational diabetes in susceptible women
  • Basal metabolic rate increases ~15-20% from mid-pregnancy
  • Thyroid: total T3/T4 increase (more binding globulin), but free T3/T4 are usually normal; gestational thyrotoxicosis can occur in the first trimester (hCG cross-reacts with TSH receptor)

Anaesthetic Implications

  1. Blood glucose monitoring: Stress hyperglycaemia and gestational diabetes require intraoperative glucose control
  2. Insulin adjustments are needed perioperatively

Key Anaesthetic Take-Home Points

ConcernClinical Action
Difficult/failed intubationPre-oxygenate well, short laryngoscope, video laryngoscopy, avoid nasal route
Rapid desaturationPreoxygenate 3-5 min before RSI; no apnoeic periods
Aspiration riskAntacid prophylaxis + RSI with cricoid pressure for GA
Aortocaval compressionLeft lateral tilt ≥15° from 20 weeks
Neuraxial hypotensionPhenylephrine infusion/boluses, IV fluid co-load
Reduced drug requirementsLower intrathecal/epidural doses, lower MAC
SuccinylcholineSafe for RSI despite reduced cholinesterase; prolongation is modest
Magnesium (preeclampsia)Potentiates NMBDs + reduces MAC - monitor and reduce doses
HypercoagulabilityCheck anticoagulation timing before regional technique

Sources:
  • Barash, Cullen & Stoelting's Clinical Anesthesia, 9e - Chapter 41: Obstetric Anesthesia (Ende, Peralta, Wong), pp. 3470-3510
  • Morgan & Mikhail's Clinical Anesthesiology, 7e - Obstetric Anesthesia chapter (Frölich), pp. 1601-1650

Create a summary PDF comparing physiological changes across trimesters

Reading File
Running Command

mkdir -p /tmp/workspace/pregnancy-physiology && ls /tmp/workspace/pregnancy-physiology/

Writing File

~/pregnancy-physiology/generate_pdf.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import mm, cm
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,
    HRFlowable, KeepTogether, PageBreak
)
from reportlab.graphics.shapes import Drawing, Rect, String, Line, Polygon
from reportlab.graphics import renderPDF
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.widgets.markers import makeMarker
from reportlab.lib.validators import Auto

OUTPUT = "/tmp/workspace/pregnancy-physiology/Physiological_Changes_in_Pregnancy.pdf"

# ─── Colour palette ───────────────────────────────────────────────────────────
T1_COL   = colors.HexColor("#4A90D9")   # 1st trimester – blue
T2_COL   = colors.HexColor("#27AE60")   # 2nd trimester – green
T3_COL   = colors.HexColor("#E67E22")   # 3rd trimester – orange
HDR_COL  = colors.HexColor("#1A3A5C")   # dark navy header
SUB_COL  = colors.HexColor("#2E86AB")   # section sub-header
LIGHT_BG = colors.HexColor("#EBF5FB")   # light blue row bg
ALT_BG   = colors.HexColor("#FDFEFE")   # near-white alternate row
WARN_COL = colors.HexColor("#E74C3C")   # red for warnings
GREEN_HL = colors.HexColor("#D5F5E3")   # green highlight cell
BLUE_HL  = colors.HexColor("#D6EAF8")   # blue highlight cell
ORG_HL   = colors.HexColor("#FDEBD0")   # orange highlight cell
WHITE    = colors.white
BLACK    = colors.black
GREY     = colors.HexColor("#7F8C8D")

# ─── Styles ───────────────────────────────────────────────────────────────────
styles = getSampleStyleSheet()

title_style = ParagraphStyle(
    "TitleStyle", parent=styles["Title"],
    fontSize=22, leading=26, textColor=WHITE,
    spaceAfter=4, alignment=TA_CENTER, fontName="Helvetica-Bold"
)
subtitle_style = ParagraphStyle(
    "SubtitleStyle", parent=styles["Normal"],
    fontSize=11, leading=14, textColor=colors.HexColor("#BDC3C7"),
    alignment=TA_CENTER, fontName="Helvetica"
)
section_style = ParagraphStyle(
    "SectionStyle", parent=styles["Heading1"],
    fontSize=13, leading=16, textColor=WHITE,
    spaceAfter=2, spaceBefore=10, fontName="Helvetica-Bold",
    leftIndent=0, borderPad=4
)
sub_style = ParagraphStyle(
    "SubStyle", parent=styles["Heading2"],
    fontSize=10, leading=13, textColor=HDR_COL,
    spaceAfter=3, spaceBefore=6, fontName="Helvetica-Bold"
)
body_style = ParagraphStyle(
    "BodyStyle", parent=styles["Normal"],
    fontSize=8.5, leading=11.5, textColor=colors.HexColor("#2C3E50"),
    spaceAfter=3, fontName="Helvetica", alignment=TA_JUSTIFY
)
cell_style = ParagraphStyle(
    "CellStyle", parent=styles["Normal"],
    fontSize=8, leading=10, textColor=BLACK,
    fontName="Helvetica", alignment=TA_LEFT
)
cell_bold = ParagraphStyle(
    "CellBold", parent=cell_style,
    fontName="Helvetica-Bold", textColor=HDR_COL
)
footnote_style = ParagraphStyle(
    "Footnote", parent=styles["Normal"],
    fontSize=7, leading=9, textColor=GREY,
    fontName="Helvetica-Oblique", alignment=TA_LEFT
)
warn_style = ParagraphStyle(
    "WarnStyle", parent=styles["Normal"],
    fontSize=8, leading=10.5, textColor=WARN_COL,
    fontName="Helvetica-Bold"
)
header_cell = ParagraphStyle(
    "HeaderCell", parent=styles["Normal"],
    fontSize=9, leading=11, textColor=WHITE,
    fontName="Helvetica-Bold", alignment=TA_CENTER
)

# ─── Helpers ──────────────────────────────────────────────────────────────────
W, H = A4
PAGE_W = W - 2*cm  # usable width

def hr():
    return HRFlowable(width="100%", thickness=0.5,
                      color=colors.HexColor("#AED6F1"), spaceAfter=4, spaceBefore=4)

def section_header(text, colour=HDR_COL):
    """A full-width coloured band as section title."""
    tbl = Table([[Paragraph(text, section_style)]], colWidths=[PAGE_W])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), colour),
        ("LEFTPADDING", (0,0), (-1,-1), 8),
        ("RIGHTPADDING", (0,0), (-1,-1), 4),
        ("TOPPADDING", (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("ROWBACKGROUNDS", (0,0), (-1,-1), [colour]),
    ]))
    return tbl

def trimester_badge(text, colour):
    tbl = Table([[Paragraph(f"<b>{text}</b>", ParagraphStyle("b",
                parent=styles["Normal"], fontSize=8, textColor=WHITE,
                fontName="Helvetica-Bold", alignment=TA_CENTER))]],
                colWidths=[38*mm])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), colour),
        ("ALIGN", (0,0), (-1,-1), "CENTER"),
        ("TOPPADDING", (0,0), (-1,-1), 3),
        ("BOTTOMPADDING", (0,0), (-1,-1), 3),
        ("ROUNDEDCORNERS", [4, 4, 4, 4]),
    ]))
    return tbl

def make_main_table(headers, rows, col_widths, row_colors=None):
    """Build a styled comparison table."""
    header_row = [Paragraph(h, header_cell) for h in headers]
    data = [header_row]
    for i, row in enumerate(rows):
        data.append([Paragraph(str(c), cell_style) for c in row])

    tbl = Table(data, colWidths=col_widths, repeatRows=1)

    style = [
        # Header
        ("BACKGROUND", (0,0), (-1,0), HDR_COL),
        ("TEXTCOLOR", (0,0), (-1,0), WHITE),
        ("ALIGN", (0,0), (-1,-1), "CENTER"),
        ("ALIGN", (0,0), (0,-1), "LEFT"),
        ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
        ("FONTNAME", (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE", (0,0), (-1,-1), 8),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_BG, ALT_BG]),
        ("GRID", (0,0), (-1,-1), 0.4, colors.HexColor("#AED6F1")),
        ("LINEBELOW", (0,0), (-1,0), 1.5, HDR_COL),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 5),
        ("RIGHTPADDING", (0,0), (-1,-1), 5),
    ]
    if row_colors:
        for (r, c1, c2), col in row_colors.items():
            style.append(("BACKGROUND", (c1, r), (c2, r), col))

    tbl.setStyle(TableStyle(style))
    return tbl

# ─── Title page banner ────────────────────────────────────────────────────────
def title_block():
    items = []
    # Navy banner table
    banner_data = [[
        Paragraph("Physiological Changes in Pregnancy", title_style),
        Paragraph("Trimester-by-Trimester Comparison with Anaesthetic Implications", subtitle_style),
        Paragraph("Sources: Barash Clinical Anesthesia 9e · Morgan &amp; Mikhail 7e", subtitle_style),
    ]]
    # Stack vertically
    banner = Table([
        [Paragraph("Physiological Changes in Pregnancy", title_style)],
        [Paragraph("Trimester-by-Trimester Comparison with Anaesthetic Implications", subtitle_style)],
        [Paragraph("Sources: Barash, Cullen &amp; Stoelting's Clinical Anesthesia 9e  |  Morgan &amp; Mikhail's Clinical Anesthesiology 7e", subtitle_style)],
    ], colWidths=[PAGE_W])
    banner.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), HDR_COL),
        ("TOPPADDING", (0,0), (-1,0), 16),
        ("TOPPADDING", (0,1), (-1,1), 4),
        ("TOPPADDING", (0,2), (-1,2), 4),
        ("BOTTOMPADDING", (0,2), (-1,2), 16),
        ("LEFTPADDING", (0,0), (-1,-1), 12),
        ("RIGHTPADDING", (0,0), (-1,-1), 12),
    ]))
    items.append(banner)
    items.append(Spacer(1, 8*mm))

    # Trimester legend row
    legend = Table([[
        trimester_badge("1st Trimester  (Weeks 1-12)", T1_COL),
        trimester_badge("2nd Trimester  (Weeks 13-26)", T2_COL),
        trimester_badge("3rd Trimester  (Weeks 27-40)", T3_COL),
    ]], colWidths=[PAGE_W/3]*3)
    legend.setStyle(TableStyle([
        ("ALIGN", (0,0), (-1,-1), "CENTER"),
        ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ]))
    items.append(legend)
    items.append(Spacer(1, 6*mm))
    return items

# ─── Overview summary table ───────────────────────────────────────────────────
def overview_table():
    items = [section_header("OVERVIEW: QUANTITATIVE CHANGES AT EACH TRIMESTER", HDR_COL), Spacer(1,3*mm)]
    headers = ["Parameter", "Pre-pregnancy\nBaseline", "1st Trimester\n(Wks 1-12)", "2nd Trimester\n(Wks 13-26)", "3rd Trimester\n(Wks 27-40)", "Trend"]
    rows = [
        ["Cardiac Output", "4-5 L/min", "+10-15%", "+30-40%", "+30-50%", "↑ Peaks 3rd Tri"],
        ["Heart Rate", "70-80 bpm", "+5-10 bpm", "+10-15 bpm", "+15 bpm", "↑ Gradual"],
        ["Stroke Volume", "60-70 mL", "+10%", "+25-30%", "+20-50%", "↑ Peaks mid-Tri"],
        ["Systemic Vascular Resistance", "Normal", "-10%", "-20-35%", "-20-50%", "↓ Progressive"],
        ["Blood Pressure (systolic)", "110-120 mmHg", "Slight ↓", "Lowest", "Returns near baseline", "↓ then ↑"],
        ["Plasma Volume", "Normal", "+10%", "+30-40%", "+40-50%", "↑ Disproportionate"],
        ["Red Cell Mass", "Normal", "+5%", "+15%", "+20-30%", "↑ Less than plasma"],
        ["Haemoglobin", "12-16 g/dL", "Slight ↓", "11-12 g/dL", "11-12 g/dL", "↓ Dilutional"],
        ["Tidal Volume", "500 mL", "+10%", "+30%", "+45%", "↑ Progesterone"],
        ["Minute Ventilation", "Normal", "+15%", "+30%", "+50%", "↑ Progressive"],
        ["FRC", "Normal", "-5%", "-15%", "-20-30%", "↓ Uterine elevation"],
        ["Oxygen Consumption", "Normal", "+5%", "+15%", "+20-21%", "↑ Metabolic demand"],
        ["PaCO2", "38-42 mmHg", "~36 mmHg", "~32 mmHg", "~30 mmHg", "↓ Resp. alkalosis"],
        ["PaO2", "~93 mmHg", "~95 mmHg", "~100 mmHg", "~106 mmHg", "↑ Hyperventilation"],
        ["GFR / Renal Blood Flow", "Normal", "+30-40%", "+40-50%", "+50%", "↑ Peaks 2nd Tri"],
        ["Serum Creatinine", "0.7-1.0 mg/dL", "~0.6 mg/dL", "~0.5 mg/dL", "~0.4-0.7 mg/dL", "↓ Dilution"],
        ["Serum Albumin", "3.5-5.0 g/dL", "Slight ↓", "~3.0 g/dL", "~2.8-3.2 g/dL", "↓ Dilution"],
        ["Fibrinogen", "200-400 mg/dL", "+15%", "+50%", "+100%", "↑ Hypercoag."],
        ["Serum Cholinesterase", "Normal", "Slight ↓", "-15-20%", "-20-30%", "↓ Dilutional"],
        ["MAC (volatile agents)", "Normal", "Slight ↓", "-20%", "-32-40%", "↓ Progesterone"],
    ]
    # Colour highlight T3 column (col 4) for each row
    row_colors = {}
    for i in range(1, len(rows)+1):
        row_colors[(i, 4, 4)] = ORG_HL
        row_colors[(i, 2, 2)] = BLUE_HL
        row_colors[(i, 3, 3)] = GREEN_HL

    cws = [PAGE_W*0.27, PAGE_W*0.13, PAGE_W*0.15, PAGE_W*0.15, PAGE_W*0.16, PAGE_W*0.14]
    items.append(make_main_table(headers, rows, cws, row_colors))
    items.append(Spacer(1,2*mm))
    items.append(Paragraph(
        "Abbreviations: FRC = Functional Residual Capacity; PaCO2 = Arterial CO2 tension; PaO2 = Arterial O2 tension; "
        "GFR = Glomerular Filtration Rate; MAC = Minimum Alveolar Concentration. "
        "Values are approximate and represent population averages.",
        footnote_style))
    return items

# ─── System-by-system sections ────────────────────────────────────────────────
def respiratory_section():
    items = [Spacer(1,4*mm), section_header("1. RESPIRATORY SYSTEM", colors.HexColor("#1F618D")), Spacer(1,2*mm)]

    items.append(Paragraph(
        "Progesterone acts on central respiratory centres to increase respiratory drive, producing the hallmark "
        "respiratory alkalosis of pregnancy. Mechanical elevation of the diaphragm by the gravid uterus reduces "
        "lung volumes from the second trimester onwards.",
        body_style))
    items.append(Spacer(1,2*mm))

    headers = ["Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause", "Anaesthetic Implication"]
    rows = [
        ["Tidal Volume", "+10%", "+30%", "+45%", "Progesterone↑ resp. drive", "Faster inhalation induction"],
        ["Respiratory Rate", "Minimal ↑", "+5%", "Slight ↑", "Progesterone", "PaCO2 target 30 mmHg on vent"],
        ["Minute Ventilation", "+15%", "+30%", "+50%", "TV + RR increase", "Volatile uptake/elimination faster"],
        ["FRC", "-5%", "-15%", "-20-30%", "Diaphragm elevation", "EARLY desaturation on apnoea"],
        ["FEV1 / FVC", "Unchanged", "Unchanged", "Unchanged", "Airway calibre preserved", "Asthma management unchanged"],
        ["PaCO2", "~36 mmHg", "~32 mmHg", "~30 mmHg", "Hyperventilation", "Maintain 30 mmHg with IPPV"],
        ["PaO2", "~95 mmHg", "~100 mmHg", "~106 mmHg", "Alveolar hyperventilation", "Preoxygenate well before RSI"],
        ["O2 Consumption", "+5%", "+15%", "+20% (rest)", "Fetal + maternal metabolism", "3 min preoxygenation mandatory"],
        ["Airway Mucosa", "Early oedema", "Moderate oedema", "Prominent oedema", "Oestrogen / fluid retention", "Avoid nasal intubation"],
        ["Mallampati Score", "May increase", "Increases", "Further increase", "Airway oedema", "Anticipate difficult airway"],
        ["MAC", "Slight ↓", "-20%", "-32-40%", "Progesterone / endorphins", "Reduce volatile agent dose"],
    ]
    cws = [PAGE_W*0.14, PAGE_W*0.10, PAGE_W*0.11, PAGE_W*0.11, PAGE_W*0.24, PAGE_W*0.30]
    items.append(make_main_table(headers, rows, cws))

    items.append(Spacer(1,3*mm))
    items.append(Paragraph(
        "<b>Key Anaesthetic Points:</b>  (1) Preoxygenate with 100% O2 for ≥3 min before RSI.  "
        "(2) Reduced FRC + increased O2 consumption = rapid SpO2 drop during apnoea.  "
        "(3) Short-handled laryngoscope; video laryngoscopy should be immediately available.  "
        "(4) Avoid nasal routes (oedematous mucosa - high bleeding risk).  "
        "(5) Target PaCO2 ~30 mmHg during IPPV to avoid uteroplacental vasoconstriction.",
        body_style))
    return items

def cardiovascular_section():
    items = [Spacer(1,4*mm), section_header("2. CARDIOVASCULAR SYSTEM", colors.HexColor("#1A5276")), Spacer(1,2*mm)]

    items.append(Paragraph(
        "Progesterone and relaxin drive peripheral vasodilation from as early as 8 weeks. The compensatory "
        "increase in cardiac output (30-50%) is driven by both increased stroke volume and heart rate. "
        "Aortocaval compression by the gravid uterus becomes haemodynamically significant from ~20 weeks.",
        body_style))
    items.append(Spacer(1,2*mm))

    headers = ["Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause", "Anaesthetic Implication"]
    rows = [
        ["Cardiac Output", "+10-15%", "+30-40%", "+30-50%", "↑ SV + ↑ HR", "Dilutes IV drugs faster"],
        ["Heart Rate", "+5-10 bpm", "+10-15 bpm", "+15 bpm", "Progesterone / sympathetic", "Tachycardia is normal baseline"],
        ["Stroke Volume", "+10%", "+25-30%", "+20-50%", "↑ Preload + ↓ afterload", "Raised CO peaks at delivery"],
        ["SVR", "-10%", "-20-35%", "-20-50%", "Progesterone, relaxin, NO", "Exaggerated hypotension post-spinal"],
        ["Blood Pressure", "Slight ↓", "Lowest (↓10-15 mmHg)", "Returns near baseline", "↓ SVR > ↑ CO", "Do not use non-pregnant norms"],
        ["Aortocaval Compression", "None", "Begins ~16-20 wks", "Significant from 20 wks", "Gravid uterus on IVC + aorta", "LEFT UTERINE DISPLACEMENT"],
        ["Colloid Oncotic Pressure", "Slight ↓", "Further ↓", "Lowest", "↓ Albumin", "Oedema risk ↑ with crystalloids"],
        ["ECG: Heart Position", "Normal", "Left axis shift starts", "Left axis shift", "Diaphragm elevation", "Axis deviation is normal"],
        ["ECG: Rate", "Slight ↑", "↑", "↑ 10-20 bpm above baseline", "Sympathetic tone", "ST depression may be normal"],
    ]
    cws = [PAGE_W*0.16, PAGE_W*0.10, PAGE_W*0.12, PAGE_W*0.12, PAGE_W*0.22, PAGE_W*0.28]
    items.append(make_main_table(headers, rows, cws))

    items.append(Spacer(1,3*mm))
    items.append(Paragraph(
        "<b>Key Anaesthetic Points:</b>  (1) LEFT UTERINE DISPLACEMENT (15-20° right hip wedge) is mandatory "
        "from 20 weeks - prevents IVC compression and maintains venous return.  "
        "(2) Phenylephrine (40-120 mcg IV bolus or infusion) is preferred over ephedrine for treating "
        "spinal hypotension - better fetal acid-base status.  "
        "(3) Regional anaesthesia preferred over GA for caesarean delivery.  "
        "(4) Interpret ECG and BP values against pregnancy norms, not standard adult ranges.",
        body_style))
    return items

def haematology_section():
    items = [Spacer(1,4*mm), section_header("3. HAEMATOLOGY AND COAGULATION", colors.HexColor("#76448A")), Spacer(1,2*mm)]

    items.append(Paragraph(
        "Plasma volume expansion exceeds red cell mass expansion throughout pregnancy, producing "
        "physiological (dilutional) anaemia. Placental hormones simultaneously drive a progressive "
        "hypercoagulable state.",
        body_style))
    items.append(Spacer(1,2*mm))

    headers = ["Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause", "Anaesthetic Implication"]
    rows = [
        ["Plasma Volume", "+10%", "+30-40%", "+40-50%", "Oestrogen, aldosterone, ADH", "Dilutes all drugs - affects Vd"],
        ["Red Cell Mass", "+5%", "+15%", "+20-30%", "Erythropoietin ↑", "Lags behind plasma expansion"],
        ["Haemoglobin", "Slight ↓", "11-12 g/dL", "11-12 g/dL", "Dilutional anaemia", "Transfusion trigger adjusted"],
        ["Fibrinogen", "+15%", "+50%", "+100% (to ~600 mg/dL)", "Placental hormones", "DVT/PE risk markedly ↑"],
        ["Factors VII, VIII, X, XII", "Slight ↑", "Moderate ↑", "Markedly ↑", "Placental hormones", "Epidural haematoma risk lower"],
        ["Protein S", "Slight ↓", "↓↓", "↓↓↓", "Increased clearance", "VTE prophylaxis essential"],
        ["Platelet Count", "Normal/slight ↓", "May fall slightly", "Gestational thrombocytopenia", "Dilution + consumption", "Check before neuraxial block"],
        ["Serum Cholinesterase", "Slight ↓", "-15-20%", "-20-30%", "Dilution + ↓ synthesis", "Minimal prolongation of Sux"],
        ["WBC Count", "↑ (leukocytosis)", "↑↑", "↑↑↑ (up to 15,000)", "Cortisol, demargination", "Do not interpret as infection alone"],
        ["Serum Albumin", "Slight ↓", "~3.0 g/dL", "~2.8-3.2 g/dL", "Dilution", "↑ Free drug fraction"],
    ]
    cws = [PAGE_W*0.16, PAGE_W*0.10, PAGE_W*0.12, PAGE_W*0.13, PAGE_W*0.21, PAGE_W*0.28]
    items.append(make_main_table(headers, rows, cws))

    items.append(Spacer(1,3*mm))
    items.append(Paragraph(
        "<b>Key Anaesthetic Points:</b>  (1) Succinylcholine is still safe for RSI despite ↓ cholinesterase "
        "- prolongation is modest (~2-5 min).  "
        "(2) Hypercoagulability means anticoagulant timing critically affects epidural/spinal safety "
        "(ASRA guidelines for timing of neuraxial techniques with LMWH/warfarin/NOACs).  "
        "(3) Platelets should ideally be >70-80 × 10⁹/L before neuraxial block.  "
        "(4) Lower albumin increases free fraction of bupivacaine - increased toxicity risk.",
        body_style))
    return items

def gi_renal_section():
    items = [Spacer(1,4*mm), section_header("4. GASTROINTESTINAL AND RENAL SYSTEMS", colors.HexColor("#117A65")), Spacer(1,2*mm)]

    gi_headers = ["GI Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause", "Anaesthetic Implication"]
    gi_rows = [
        ["Gastric Emptying", "Normal / slight delay", "Delayed", "Delayed (worse in labour)", "Progesterone relaxes smooth muscle", "ALL obstetric pts = full stomach"],
        ["Lower Oesophageal Sphincter", "Slight ↓ tone", "Reduced tone", "Significantly reduced tone", "Progesterone + mechanical", "Aspiration risk throughout"],
        ["Gastric Acid", "↑ (early)", "↑↑", "↑↑↑", "Placental gastrin production", "Antacid prophylaxis essential"],
        ["Intra-abdominal Pressure", "Normal", "Moderately ↑", "Markedly ↑", "Gravid uterus", "Compounds reflux risk"],
        ["Nausea/Vomiting", "Common (hCG peak)", "Reduces", "Less common", "hCG + progesterone", "Aspiration prophylaxis from T1"],
    ]
    cws_gi = [PAGE_W*0.15, PAGE_W*0.10, PAGE_W*0.11, PAGE_W*0.11, PAGE_W*0.24, PAGE_W*0.29]
    items.append(Paragraph("Gastrointestinal System", sub_style))
    items.append(make_main_table(gi_headers, gi_rows, cws_gi))

    items.append(Spacer(1,3*mm))
    renal_headers = ["Renal Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause", "Anaesthetic Implication"]
    renal_rows = [
        ["GFR", "+30-40%", "+40-50%", "+50%", "↑ CO + ↓ renal vasc. resistance", "Drug dosing adjustment needed"],
        ["Renal Blood Flow", "+30%", "+40-50%", "+50%", "Relaxin, progesterone", "Faster clearance of renally excreted drugs"],
        ["Serum Creatinine", "~0.6 mg/dL", "~0.5 mg/dL", "~0.4-0.7 mg/dL", "↑ GFR + dilution", "Normal creatinine ≠ normal renal function"],
        ["Serum Urea/BUN", "Falls", "Further fall", "Lowest", "↑ GFR", "Standard upper limits not applicable"],
        ["Glycosuria", "Possible", "Common", "Common", "Tubular reabsorption overwhelmed", "NOT diagnostic of diabetes alone"],
        ["Ureteric Dilation", "Begins", "Progressive", "Marked (hydronephrosis)", "Progesterone + uterine compression", "UTI risk; magnesium accumulates"],
        ["Magnesium Clearance", "Normal", "↑ with GFR", "↑", "↑ GFR", "Monitor Mg levels in pre-eclampsia treatment"],
    ]
    cws_r = [PAGE_W*0.15, PAGE_W*0.10, PAGE_W*0.11, PAGE_W*0.11, PAGE_W*0.24, PAGE_W*0.29]
    items.append(Paragraph("Renal System", sub_style))
    items.append(make_main_table(renal_headers, renal_rows, cws_r))

    items.append(Spacer(1,3*mm))
    items.append(Paragraph(
        "<b>Key Anaesthetic Points:</b>  (1) RSI with cricoid pressure + antacid prophylaxis (sodium citrate ± "
        "ranitidine ± metoclopramide) for all GA after 16-20 weeks.  "
        "(2) Magnesium sulphate (used in preeclampsia) potentiates NMBDs and reduces MAC - monitor levels, "
        "use neuromuscular monitoring, calcium gluconate as antidote.  "
        "(3) Serum creatinine 0.8 mg/dL in a pregnant woman may represent significant renal impairment.",
        body_style))
    return items

def neuro_hepatic_endocrine():
    items = [Spacer(1,4*mm), section_header("5. NEUROLOGICAL, HEPATIC, AND ENDOCRINE SYSTEMS", colors.HexColor("#7D6608")), Spacer(1,2*mm)]

    headers = ["System / Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause", "Anaesthetic Implication"]
    rows = [
        # Neurological
        ["MAC (Volatile Agents)", "Slight ↓", "-20%", "-32-40%", "Progesterone / β-endorphins", "Reduce volatile agent dose - awareness risk"],
        ["Epidural Space Volume", "Normal", "Starts to decrease", "Reduced (engorged veins)", "IVC compression → epidural venous engorgement", "Epidural doses must be REDUCED"],
        ["Intrathecal LA Spread", "Normal", "Slightly enhanced", "Enhanced spread", "↓ CSF volume, altered CSF protein/density", "Lower spinal doses for same block level"],
        ["Lumbar Lordosis", "Increasing", "Moderate", "Marked", "Weight + lax ligaments", "Alters needle angle for epidural/spinal"],
        ["Neural Sensitivity to LA", "May be ↑", "↑", "↑↑", "Progesterone alters nerve membrane", "Block established faster + denser"],
        # Hepatic
        ["Serum Albumin", "Slight ↓", "~3.0 g/dL", "~2.8-3.2 g/dL", "Dilution + altered synthesis", "↑ Free bupivacaine → toxicity risk"],
        ["Alkaline Phosphatase", "↑↑ (placental)", "↑↑", "3-4× normal", "Placental isoform (NOT hepatic)", "Do not interpret as liver pathology"],
        ["ALT/AST/Bilirubin", "Normal", "Normal", "Normal (mild ↑ biliary stasis)", "—", "Abnormal values suggest pathology (HELLP, ICP)"],
        ["Hepatic Blood Flow", "↑ with CO", "↑↑", "↑↑", "↑ CO", "Faster clearance of some drugs"],
        # Endocrine
        ["Insulin Resistance", "Mild", "Moderate", "Marked", "HPL, progesterone, cortisol", "Gestational diabetes monitoring"],
        ["Cortisol (total)", "↑", "↑↑", "↑↑↑", "↑ Corticosteroid-binding globulin", "Altered stress response"],
        ["Total T3/T4", "↑ (early hCG)", "↑", "↑", "↑ Thyroid-binding globulin", "Free thyroid levels usually normal"],
    ]
    cws = [PAGE_W*0.18, PAGE_W*0.09, PAGE_W*0.10, PAGE_W*0.10, PAGE_W*0.25, PAGE_W*0.28]
    items.append(make_main_table(headers, rows, cws))

    items.append(Spacer(1,3*mm))
    items.append(Paragraph(
        "<b>Key Anaesthetic Points:</b>  (1) Reduce intrathecal bupivacaine dose for caesarean "
        "(typically 10-12 mg vs 15 mg in non-pregnant patients).  "
        "(2) Lower induction doses of propofol/thiopentone.  "
        "(3) Alkaline phosphatase elevation is normal - do not misinterpret.  "
        "(4) Monitor blood glucose perioperatively.",
        body_style))
    return items

def anaesthetic_summary():
    items = [Spacer(1,4*mm), section_header("6. ANAESTHETIC IMPLICATIONS SUMMARY TABLE", WARN_COL), Spacer(1,2*mm)]

    headers = ["Concern", "Physiological Basis", "Action Required"]
    rows = [
        ["Difficult / Failed Intubation", "Airway oedema, ↑ Mallampati, breast engorgement", "Preoxygenate, short handle laryngoscope, VL immediately available, RSI"],
        ["Rapid Desaturation on Apnoea", "↓ FRC + ↑ O2 consumption", "Pre-oxygenate ≥3 min (FiO2 1.0); 4 vital capacity breaths minimum"],
        ["Aspiration Risk", "↓ LOS tone, delayed gastric emptying, ↑ gastric acid", "Antacid + H2-blocker + metoclopramide; RSI + cricoid pressure for GA"],
        ["Aortocaval Compression", "Gravid uterus compresses IVC + aorta (from 20 wks)", "Left lateral tilt ≥15° (wedge under right hip) at ALL TIMES"],
        ["Hypotension (post-spinal)", "Sympathectomy in already-low SVR state", "Phenylephrine infusion/boluses, IV fluid co-load, LUD, supplemental O2"],
        ["Reduced Drug Requirements (Neuraxial)", "Engorged epidural veins, ↑ neural sensitivity, ↓ CSF volume", "Reduce intrathecal + epidural doses by 25-40%"],
        ["Reduced MAC (Volatile)", "Progesterone, β-endorphins", "Reduce volatile agent dose; monitor for awareness"],
        ["Succinylcholine (RSI)", "↓ Cholinesterase (-20-30%)", "Safe to use; modest prolongation (~2-5 min) only; no dose change"],
        ["Magnesium Toxicity (Preeclampsia Rx)", "↑ Mg potentiates NMBDs, ↓ MAC", "Reduce NMBD dose, use NM monitoring, Ca gluconate as antidote"],
        ["Neuraxial + Anticoagulation", "Hypercoagulable state → LMWH/heparin common", "Follow ASRA guidelines; minimum 12 h (prophylactic) / 24 h (therapeutic) LMWH gap"],
        ["Haemorrhage Tolerance", "↑ Blood volume (+40%) buffers early loss", "Blood loss of 1000-1500 mL before haemodynamic compromise; have FFP/PLT ready"],
        ["Eclampsia / HELLP", "End-organ disease of preeclampsia", "Neuraxial preferred; avoid ergometrine; MgSO4 for seizure prophylaxis"],
        ["Fetal Drug Exposure", "Lipophilic, low-MW, un-ionised drugs cross placenta", "Prefer regional; use lowest effective doses; time delivery after GA"],
    ]
    cws = [PAGE_W*0.22, PAGE_W*0.35, PAGE_W*0.43]
    tbl = Table(
        [[Paragraph(h, header_cell) for h in headers]] +
        [[Paragraph(str(c), cell_style) for c in row] for row in rows],
        colWidths=cws, repeatRows=1
    )
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,0), WARN_COL),
        ("TEXTCOLOR", (0,0), (-1,0), WHITE),
        ("ALIGN", (0,0), (-1,0), "CENTER"),
        ("ALIGN", (0,0), (0,-1), "LEFT"),
        ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
        ("FONTNAME", (0,0), (-1,0), "Helvetica-Bold"),
        ("FONTSIZE", (0,0), (-1,-1), 8),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [colors.HexColor("#FDEDEC"), ALT_BG]),
        ("GRID", (0,0), (-1,-1), 0.4, colors.HexColor("#F1948A")),
        ("LINEBELOW", (0,0), (-1,0), 1.5, WARN_COL),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 5),
        ("RIGHTPADDING", (0,0), (-1,-1), 5),
    ]))
    items.append(tbl)
    return items

def references_block():
    items = [Spacer(1,6*mm), hr()]
    items.append(Paragraph(
        "<b>References:</b>  "
        "1. Ende HB, Peralta FM, Wong CA. Obstetric Anesthesia. In: Barash PG, Cullen BF, Stoelting RK, et al., eds. "
        "<i>Clinical Anesthesia</i>, 9th ed. Wolters Kluwer; 2023: Chapter 41, pp. 3470-3510.  |  "
        "2. Frölich MA. Obstetric Anesthesia. In: Butterworth JF, Mackey DC, Wasnick JD, eds. "
        "<i>Morgan &amp; Mikhail's Clinical Anesthesiology</i>, 7th ed. McGraw-Hill; 2022: pp. 1601-1650.",
        footnote_style))
    items.append(Spacer(1,2*mm))
    items.append(Paragraph(
        "This document is for educational reference only. Clinical decisions should be based on current guidelines and individual patient assessment.",
        footnote_style))
    return items

# ─── Build document ───────────────────────────────────────────────────────────
def build_pdf():
    doc = SimpleDocTemplate(
        OUTPUT,
        pagesize=A4,
        leftMargin=1*cm, rightMargin=1*cm,
        topMargin=1.2*cm, bottomMargin=1.5*cm,
        title="Physiological Changes in Pregnancy - Trimester Comparison",
        author="Orris Medical Reference",
        subject="Obstetric Anaesthesia - Physiological Changes by Trimester"
    )

    story = []

    # Title block
    story.extend(title_block())

    # Overview
    story.extend(overview_table())
    story.append(PageBreak())

    # Respiratory
    story.extend(respiratory_section())
    story.append(PageBreak())

    # Cardiovascular
    story.extend(cardiovascular_section())
    story.append(Spacer(1,4*mm))

    # Haematology
    story.extend(haematology_section())
    story.append(PageBreak())

    # GI + Renal
    story.extend(gi_renal_section())
    story.append(PageBreak())

    # Neuro + Hepatic + Endocrine
    story.extend(neuro_hepatic_endocrine())
    story.append(Spacer(1,4*mm))

    # Anaesthetic Summary
    story.extend(anaesthetic_summary())

    # References
    story.extend(references_block())

    doc.build(story)
    print(f"PDF created: {OUTPUT}")

build_pdf()
Running Command

cd /tmp/workspace/pregnancy-physiology && python generate_pdf.py 2>&1

Running Command

ls -lh /tmp/workspace/pregnancy-physiology/Physiological_Changes_in_Pregnancy.pdf

Your PDF is ready:

Physiological Changes in Pregnancy

PDF Document · PDF


What's inside (6 pages, fully colour-coded):
SectionContent
Title Banner + LegendColour-coded trimester badges (Blue = T1, Green = T2, Orange = T3)
Overview Table20 parameters with values at each trimester + trend arrows
Respiratory System11 parameters - FRC, minute ventilation, PaCO2, MAC, airway, O2 consumption
Cardiovascular System9 parameters - CO, HR, SVR, BP, aortocaval compression
Haematology & Coagulation10 parameters - plasma volume, Hb, fibrinogen, cholinesterase, platelet
GI & Renal SystemsGastric emptying, LOS tone, GFR, creatinine, glycosuria, Mg clearance
Neurological / Hepatic / EndocrineMAC reduction, neuraxial dose reduction, albumin, ALP, insulin resistance
Anaesthetic Implications Summary13 clinical concerns with action required - colour-highlighted in red
ReferencesBarash 9e + Morgan & Mikhail 7e cited
Every table column has: Parameter | 1st Trimester | 2nd Trimester | 3rd Trimester | Cause | Anaesthetic Implication.

Not like this how you wrote na that i want

Writing File

~/pregnancy-physiology/generate_pdf_v2.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import mm, cm
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,
    HRFlowable, PageBreak, ListFlowable, ListItem
)

OUTPUT = "/tmp/workspace/pregnancy-physiology/Physiological_Changes_in_Pregnancy_v2.pdf"

W, H = A4
PAGE_W = W - 2.4*cm

# ── Colours ──────────────────────────────────────────────────────────────────
NAVY      = colors.HexColor("#1A3A5C")
BLUE      = colors.HexColor("#2E86AB")
MID_BLUE  = colors.HexColor("#1F618D")
TEAL      = colors.HexColor("#117A65")
PURPLE    = colors.HexColor("#6C3483")
DARK_ORG  = colors.HexColor("#7D6608")
RED       = colors.HexColor("#C0392B")
LIGHT_HDR = colors.HexColor("#D6EAF8")
LIGHT_GRN = colors.HexColor("#D5F5E3")
LIGHT_RED = colors.HexColor("#FADBD8")
ALT1      = colors.HexColor("#EBF5FB")
ALT2      = colors.HexColor("#FDFEFE")
WHITE     = colors.white
GREY      = colors.HexColor("#7F8C8D")
LIGHT_GREY= colors.HexColor("#F2F3F4")

# ── Styles ───────────────────────────────────────────────────────────────────
styles = getSampleStyleSheet()

DOC_TITLE = ParagraphStyle("DocTitle",
    fontSize=20, leading=26, textColor=WHITE,
    fontName="Helvetica-Bold", alignment=TA_CENTER, spaceAfter=4)

DOC_SUBTITLE = ParagraphStyle("DocSubtitle",
    fontSize=10, leading=13, textColor=colors.HexColor("#BDC3C7"),
    fontName="Helvetica", alignment=TA_CENTER, spaceAfter=2)

SEC_TITLE = ParagraphStyle("SecTitle",
    fontSize=13, leading=16, textColor=WHITE,
    fontName="Helvetica-Bold", spaceBefore=8, spaceAfter=2)

SUBSEC_TITLE = ParagraphStyle("SubsecTitle",
    fontSize=10.5, leading=13, textColor=NAVY,
    fontName="Helvetica-Bold", spaceBefore=6, spaceAfter=2,
    leftIndent=0)

BODY = ParagraphStyle("Body",
    fontSize=9, leading=13, textColor=colors.HexColor("#1C2833"),
    fontName="Helvetica", spaceAfter=4, alignment=TA_JUSTIFY)

BULLET = ParagraphStyle("Bullet",
    fontSize=8.8, leading=12.5, textColor=colors.HexColor("#1C2833"),
    fontName="Helvetica", spaceAfter=2, leftIndent=12, bulletIndent=2)

KEY_POINT = ParagraphStyle("KeyPoint",
    fontSize=8.8, leading=12.5, textColor=colors.HexColor("#1A5276"),
    fontName="Helvetica", spaceAfter=2, leftIndent=12, bulletIndent=2)

BOLD_LABEL = ParagraphStyle("BoldLabel",
    fontSize=9, leading=12, textColor=NAVY,
    fontName="Helvetica-Bold", spaceAfter=1)

TABLE_HDR = ParagraphStyle("TableHdr",
    fontSize=8.5, leading=11, textColor=WHITE,
    fontName="Helvetica-Bold", alignment=TA_CENTER)

TABLE_CELL = ParagraphStyle("TableCell",
    fontSize=8, leading=10.5, textColor=colors.HexColor("#1C2833"),
    fontName="Helvetica", alignment=TA_LEFT)

TABLE_CELL_CTR = ParagraphStyle("TableCellCtr",
    fontSize=8, leading=10.5, textColor=colors.HexColor("#1C2833"),
    fontName="Helvetica", alignment=TA_CENTER)

FOOTNOTE = ParagraphStyle("Footnote",
    fontSize=7, leading=9, textColor=GREY,
    fontName="Helvetica-Oblique", spaceAfter=2)

# ── Reusable helpers ─────────────────────────────────────────────────────────

def hr(colour=colors.HexColor("#AED6F1"), thick=0.6):
    return HRFlowable(width="100%", thickness=thick, color=colour,
                      spaceBefore=3, spaceAfter=3)

def section_banner(text, bg=NAVY):
    tbl = Table([[Paragraph(text, SEC_TITLE)]], colWidths=[PAGE_W])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), bg),
        ("LEFTPADDING",  (0,0), (-1,-1), 10),
        ("RIGHTPADDING", (0,0), (-1,-1), 6),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
    ]))
    return tbl

def subsec_banner(text, bg=LIGHT_HDR):
    tbl = Table([[Paragraph(text, SUBSEC_TITLE)]], colWidths=[PAGE_W])
    tbl.setStyle(TableStyle([
        ("BACKGROUND",   (0,0), (-1,-1), bg),
        ("LEFTPADDING",  (0,0), (-1,-1), 8),
        ("RIGHTPADDING", (0,0), (-1,-1), 6),
        ("TOPPADDING",   (0,0), (-1,-1), 4),
        ("BOTTOMPADDING",(0,0), (-1,-1), 4),
    ]))
    return tbl

def bullet_item(text):
    return Paragraph(f"<bullet>&bull;</bullet> {text}", BULLET)

def key_point(text):
    return Paragraph(f"<bullet>&#9658;</bullet> {text}", KEY_POINT)

def sp(h=3):
    return Spacer(1, h*mm)

def make_table(headers, rows, col_widths, hdr_bg=NAVY, alt1=ALT1, alt2=ALT2):
    data = [[Paragraph(h, TABLE_HDR) for h in headers]]
    for row in rows:
        data.append([Paragraph(str(c), TABLE_CELL) for c in row])
    tbl = Table(data, colWidths=col_widths, repeatRows=1)
    tbl.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0), hdr_bg),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [alt1, alt2]),
        ("GRID",          (0,0), (-1,-1), 0.4, colors.HexColor("#AED6F1")),
        ("LINEBELOW",     (0,0), (-1,0), 1.5, hdr_bg),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("ALIGN",         (0,0), (-1,0), "CENTER"),
        ("TOPPADDING",    (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING",   (0,0), (-1,-1), 5),
        ("RIGHTPADDING",  (0,0), (-1,-1), 5),
    ]))
    return tbl

# ═════════════════════════════════════════════════════════════════════════════
# CONTENT
# ═════════════════════════════════════════════════════════════════════════════

def title_block():
    banner = Table([
        [Paragraph("Physiological Changes in Pregnancy", DOC_TITLE)],
        [Paragraph("Causes · Trimester-by-Trimester Comparison · Anaesthetic Implications", DOC_SUBTITLE)],
        [Paragraph("Sources: Barash, Cullen &amp; Stoelting's Clinical Anesthesia, 9e  |  Morgan &amp; Mikhail's Clinical Anesthesiology, 7e", DOC_SUBTITLE)],
    ], colWidths=[PAGE_W])
    banner.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), NAVY),
        ("TOPPADDING",    (0,0), (-1,0),  14),
        ("TOPPADDING",    (0,1), (-1,1),  4),
        ("TOPPADDING",    (0,2), (-1,2),  3),
        ("BOTTOMPADDING", (0,2), (-1,2),  14),
        ("LEFTPADDING",   (0,0), (-1,-1), 14),
        ("RIGHTPADDING",  (0,0), (-1,-1), 14),
    ]))
    return [banner, sp(5)]


def overview_section():
    s = [section_banner("OVERVIEW", NAVY), sp(2)]
    s.append(Paragraph(
        "Pregnancy is characterised by significant anatomical and physiological changes across multiple "
        "organ systems. These changes are primarily driven by <b>hormonal shifts</b> (especially "
        "progesterone, relaxin, oestrogen, and placental hormones) and <b>mechanical compression</b> "
        "by the gravid uterus. They begin as early as the first trimester and return to pre-pregnancy "
        "baseline within weeks to months after delivery.", BODY))
    s.append(sp(3))

    s.append(subsec_banner("Summary of Key Quantitative Changes at Term", LIGHT_HDR))
    s.append(sp(2))

    headers = ["Parameter", "Change", "Magnitude", "Primary Cause"]
    rows = [
        ["Plasma volume",                    "↑",  "40-50%",            "Oestrogen, aldosterone, ADH"],
        ["Total blood volume",               "↑",  "40%",               "Plasma + RBC expansion"],
        ["Haemoglobin",                      "↓",  "11-12 g/dL",        "Dilutional anaemia"],
        ["Fibrinogen",                       "↑",  "~100%",             "Placental hormones"],
        ["Serum cholinesterase activity",    "↓",  "20-30%",            "Dilution + ↓ synthesis"],
        ["Systemic vascular resistance",     "↓",  "20-50%",            "Progesterone, relaxin, NO"],
        ["Cardiac output",                   "↑",  "30-50%",            "↑ SV + ↑ HR"],
        ["Systemic blood pressure",          "↓",  "Slight",            "↓ SVR > ↑ CO"],
        ["Functional residual capacity (FRC)","↓", "20-30%",            "Diaphragm elevation by uterus"],
        ["Minute ventilation",               "↑",  "50%",               "Progesterone ↑ respiratory drive"],
        ["Alveolar ventilation",             "↑",  "70%",               "Progesterone"],
        ["Oxygen consumption",               "↑",  "20% (rest); 75% in 2nd stage labour", "Fetal + maternal metabolism"],
        ["PaCO₂",                            "↓",  "~30 mmHg at term",  "Hyperventilation"],
        ["PaO₂",                             "↑",  "~106 mmHg at term", "Alveolar hyperventilation"],
        ["Minimum alveolar concentration (MAC)","↓","32-40%",           "Progesterone / β-endorphins"],
    ]
    cws = [PAGE_W*0.30, PAGE_W*0.07, PAGE_W*0.25, PAGE_W*0.38]
    s.append(make_table(headers, rows, cws))
    s.append(sp(2))
    s.append(Paragraph(
        "↑ = increase  |  ↓ = decrease  |  PaCO₂ = arterial carbon dioxide tension  |  "
        "PaO₂ = arterial oxygen tension  |  MAC = minimum alveolar concentration  |  SV = stroke volume  |  "
        "HR = heart rate  |  SVR = systemic vascular resistance  |  CO = cardiac output",
        FOOTNOTE))
    return s


def respiratory_section():
    s = [sp(4), section_banner("1.  RESPIRATORY SYSTEM", MID_BLUE), sp(2)]

    # -- Changes & Causes --
    s.append(subsec_banner("Changes and Causes", bg=colors.HexColor("#D6EAF8")))
    s.append(sp(2))

    s.append(Paragraph("<b>Airway</b>", BOLD_LABEL))
    for t in [
        "Capillary engorgement of nasal, oropharyngeal, and laryngeal mucosa occurs throughout pregnancy due to increased extracellular fluid and oestrogen-driven vasodilation.",
        "Airway oedema worsens in preeclampsia, after active pushing in the second stage of labour, and with tocolytic therapy.",
        "Mallampati score tends to increase throughout pregnancy and labour.",
        "Breast engorgement in late pregnancy further impairs laryngoscopic access.",
    ]:
        s.append(bullet_item(t))
    s.append(sp(2))

    s.append(Paragraph("<b>Respiratory Volumes and Gas Exchange</b>", BOLD_LABEL))
    for t in [
        "Progesterone acts on central respiratory centres to increase respiratory drive.",
        "Tidal volume (TV) increases by <b>45%</b>; respiratory rate increases slightly - producing a <b>50% increase in minute ventilation</b> at term.",
        "<b>FRC decreases by up to 30%</b> due to cephalad diaphragm displacement by the gravid uterus (residual volume falls 25%, expiratory reserve volume falls 20%).",
        "Closing volume and closing capacity are unchanged, but FRC may fall below closing capacity in the supine position, causing airway closure during normal tidal breathing.",
        "FEV₁, FVC, FEV₁/FVC ratio, and total lung capacity remain relatively unchanged.",
        "<b>Alveolar ventilation increases by 70%</b>, producing <b>compensated respiratory alkalosis</b>: pH 7.42-7.46, PaCO₂ ~30 mmHg, PaO₂ ~106 mmHg.",
        "Oxygen consumption increases by <b>20-21% at rest</b>; rises to <b>45% above baseline in the first stage</b> and <b>75% in the second stage</b> of labour.",
        "Apnoea is poorly tolerated due to the combination of increased O₂ consumption and reduced FRC, resulting in early desaturation.",
    ]:
        s.append(bullet_item(t))
    s.append(sp(3))

    # -- Trimester comparison table --
    s.append(subsec_banner("Trimester-by-Trimester Comparison", bg=colors.HexColor("#D6EAF8")))
    s.append(sp(2))
    headers = ["Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause"]
    rows = [
        ["Tidal Volume",         "+10%",             "+30%",              "+45%",             "Progesterone ↑ resp. drive"],
        ["Respiratory Rate",     "Minimal ↑",        "+5%",               "Slight ↑",         "Progesterone"],
        ["Minute Ventilation",   "+15%",             "+30%",              "+50%",             "TV + RR increase"],
        ["FRC",                  "-5%",              "-15%",              "-20 to -30%",      "Diaphragm elevation"],
        ["FEV₁ / FVC",           "Unchanged",        "Unchanged",         "Unchanged",        "Airway calibre preserved"],
        ["PaCO₂",                "~36 mmHg",         "~32 mmHg",          "~30 mmHg",         "Hyperventilation"],
        ["PaO₂",                 "~95 mmHg",         "~100 mmHg",         "~106 mmHg",        "Alveolar hyperventilation"],
        ["O₂ Consumption",       "+5%",              "+15%",              "+20% (rest)",      "Fetal + maternal metabolism"],
        ["Airway Oedema",        "Early",            "Moderate",          "Prominent",        "Oestrogen / fluid retention"],
        ["Mallampati Score",     "May increase",     "Increases",         "Further increase", "Airway oedema"],
        ["MAC",                  "Slight ↓",         "-20%",              "-32 to -40%",      "Progesterone / endorphins"],
    ]
    cws = [PAGE_W*0.15, PAGE_W*0.12, PAGE_W*0.13, PAGE_W*0.13, PAGE_W*0.47]
    s.append(make_table(headers, rows, cws, hdr_bg=MID_BLUE))
    s.append(sp(3))

    # -- Anaesthetic implications --
    s.append(subsec_banner("Anaesthetic Implications", bg=colors.HexColor("#D6EAF8")))
    s.append(sp(2))
    for t in [
        "<b>Preoxygenate with 100% O₂ for ≥3 minutes</b> (or 4 vital capacity breaths) before RSI - reduced FRC + increased O₂ consumption means SpO₂ drops dangerously fast during apnoea.",
        "<b>Anticipate a difficult airway</b>: nasal intubation is avoided (high mucosal bleeding risk). Use a short-handled laryngoscope; have video laryngoscopy immediately available.",
        "<b>Faster inhalational induction and emergence</b>: increased alveolar ventilation plus decreased FRC accelerates uptake and elimination of volatile agents.",
        "<b>Reduced MAC by 32-40%</b>: lower doses of volatile agents are required. Progesterone's sedative effect is the primary mechanism.",
        "<b>Target PaCO₂ ~30 mmHg</b> during controlled ventilation - hyperventilation below 25 mmHg causes uterine artery vasoconstriction and fetal compromise.",
        "Avoid hyperoxia-induced hyperventilation during spontaneous breathing - can shift maternal O₂-Hb dissociation curve leftward, reducing O₂ delivery to the fetus.",
    ]:
        s.append(key_point(t))
    return s


def cardiovascular_section():
    s = [sp(4), section_banner("2.  CARDIOVASCULAR SYSTEM", colors.HexColor("#1A5276")), sp(2)]

    s.append(subsec_banner("Changes and Causes", bg=colors.HexColor("#D6EAF8")))
    s.append(sp(2))
    for t in [
        "<b>Cardiac output rises 30-50%</b> starting in the first trimester, driven by progesterone and relaxin causing peripheral vasodilation. Stroke volume increases 20-50%; heart rate increases ~15 bpm.",
        "<b>Systemic vascular resistance falls 20-50%</b> - mediated by progesterone, relaxin, and nitric oxide.",
        "<b>Blood pressure falls slightly</b> despite increased CO, because the fall in SVR is greater than the rise in CO. Most pronounced in the second trimester.",
        "CO peaks during the second stage of labour (catecholamine surge with pain) and immediately after delivery (uterine contraction causes autotransfusion of ~500 mL).",
        "<b>Aortocaval compression</b>: the gravid uterus compresses the inferior vena cava and aorta in the supine position from ~20 weeks gestation, reducing venous return and CO by up to 30% (supine hypotensive syndrome).",
        "ECG changes: shortened PR interval, left axis deviation, prominent Q waves in III and aVF, flattened or inverted T waves in III and aVF - all <i>normal</i> in pregnancy.",
        "Colloid oncotic pressure falls (due to dilutional fall in albumin), increasing the risk of pulmonary oedema, especially if large volumes of crystalloid are given.",
    ]:
        s.append(bullet_item(t))
    s.append(sp(3))

    s.append(subsec_banner("Trimester-by-Trimester Comparison", bg=colors.HexColor("#D6EAF8")))
    s.append(sp(2))
    headers = ["Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause"]
    rows = [
        ["Cardiac Output",            "+10-15%",              "+30-40%",            "+30-50%",              "↑ SV + ↑ HR"],
        ["Heart Rate",                "+5-10 bpm",            "+10-15 bpm",         "+15 bpm",              "Progesterone / sympathetic"],
        ["Stroke Volume",             "+10%",                 "+25-30%",            "+20-50%",              "↑ Preload + ↓ afterload"],
        ["Systemic Vascular Resist.", "-10%",                 "-20 to -35%",        "-20 to -50%",          "Progesterone, relaxin, NO"],
        ["Blood Pressure",            "Slight ↓",             "Lowest (-10-15 mmHg)","Returns near baseline","↓ SVR > ↑ CO"],
        ["Aortocaval Compression",    "None",                 "Begins ~16-20 wks",  "Significant from 20 wks","Gravid uterus on IVC+aorta"],
        ["Colloid Oncotic Pressure",  "Slight ↓",             "Further ↓",          "Lowest",               "↓ Albumin"],
    ]
    cws = [PAGE_W*0.19, PAGE_W*0.13, PAGE_W*0.15, PAGE_W*0.14, PAGE_W*0.39]
    s.append(make_table(headers, rows, cws, hdr_bg=colors.HexColor("#1A5276")))
    s.append(sp(3))

    s.append(subsec_banner("Anaesthetic Implications", bg=colors.HexColor("#D6EAF8")))
    s.append(sp(2))
    for t in [
        "<b>Left uterine displacement (LUD) is mandatory from 20 weeks</b> - place a wedge under the right hip (15-20° tilt) or manually displace the uterus. Prevents IVC compression and maintains venous return.",
        "<b>Phenylephrine (40-120 mcg IV bolus or infusion)</b> is the preferred vasopressor for spinal hypotension during caesarean delivery - preserves uteroplacental blood flow better than ephedrine.",
        "<b>Regional anaesthesia is preferred over general anaesthesia</b> for caesarean delivery - less haemodynamic fluctuation, avoids airway manipulation, reduces fetal drug exposure.",
        "Interpret ECG and blood pressure values against <i>pregnancy norms</i>, not standard adult ranges - axis deviation and mild tachycardia are normal.",
        "Increased CO increases hepatic and renal blood flow, accelerating clearance of some drugs.",
    ]:
        s.append(key_point(t))
    return s


def haematology_section():
    s = [sp(4), section_banner("3.  HAEMATOLOGY AND COAGULATION", PURPLE), sp(2)]

    s.append(subsec_banner("Changes and Causes", bg=colors.HexColor("#E8DAEF")))
    s.append(sp(2))
    for t in [
        "<b>Plasma volume expands 40-50%</b> (driven by oestrogen, progesterone, aldosterone, and ADH), while red cell mass increases only 20-30% - producing <b>dilutional (physiological) anaemia</b> with Hb 11-12 g/dL.",
        "<b>Hypercoagulable state</b>: fibrinogen doubles (100% increase); factors VII, VIII, IX, X, and XII all increase; protein S falls; fibrinolytic activity is reduced. Driven by placental hormones.",
        "<b>Serum cholinesterase (pseudocholinesterase) activity falls 20-30%</b> due to dilution and reduced synthesis.",
        "Platelet count falls slightly in many women (gestational thrombocytopenia - platelets 70-150 × 10⁹/L).",
        "White cell count rises to up to 15,000/mm³ (physiological leukocytosis - do not interpret as infection alone).",
        "Serum albumin falls to ~2.8-3.2 g/dL at term due to dilution - increases the free (active) fraction of highly protein-bound drugs.",
    ]:
        s.append(bullet_item(t))
    s.append(sp(3))

    s.append(subsec_banner("Trimester-by-Trimester Comparison", bg=colors.HexColor("#E8DAEF")))
    s.append(sp(2))
    headers = ["Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause"]
    rows = [
        ["Plasma Volume",             "+10%",         "+30-40%",          "+40-50%",           "Oestrogen, aldosterone, ADH"],
        ["Red Cell Mass",             "+5%",          "+15%",             "+20-30%",           "Erythropoietin ↑"],
        ["Haemoglobin",               "Slight ↓",     "11-12 g/dL",       "11-12 g/dL",        "Dilutional anaemia"],
        ["Fibrinogen",                "+15%",         "+50%",             "+100% (~600 mg/dL)","Placental hormones"],
        ["Factors VII, VIII, X, XII", "Slight ↑",     "Moderate ↑",       "Markedly ↑",        "Placental hormones"],
        ["Protein S",                 "Slight ↓",     "↓↓",               "↓↓↓",               "Increased clearance"],
        ["Platelet Count",            "Normal/slight ↓","May fall slightly","Gestational thrombocytopenia","Dilution + consumption"],
        ["Serum Cholinesterase",       "Slight ↓",     "-15-20%",          "-20-30%",           "Dilution + ↓ synthesis"],
        ["WBC Count",                 "↑",            "↑↑",               "↑↑↑ (up to 15,000)","Cortisol, demargination"],
        ["Serum Albumin",             "Slight ↓",     "~3.0 g/dL",        "~2.8-3.2 g/dL",     "Dilution"],
    ]
    cws = [PAGE_W*0.19, PAGE_W*0.12, PAGE_W*0.13, PAGE_W*0.17, PAGE_W*0.39]
    s.append(make_table(headers, rows, cws, hdr_bg=PURPLE))
    s.append(sp(3))

    s.append(subsec_banner("Anaesthetic Implications", bg=colors.HexColor("#E8DAEF")))
    s.append(sp(2))
    for t in [
        "<b>Succinylcholine is still safe and is the drug of choice for RSI</b> despite reduced cholinesterase - prolongation is modest (~2-5 minutes only); no dose change required.",
        "<b>Hypercoagulability means anticoagulant timing critically affects neuraxial safety</b>. Follow ASRA guidelines: minimum 12 h (prophylactic LMWH) or 24 h (therapeutic LMWH) gap before epidural/spinal.",
        "Platelets should ideally be <b>&gt;70-80 × 10⁹/L</b> before neuraxial block; &lt;50 × 10⁹/L is a contraindication.",
        "Lower albumin increases the free fraction of bupivacaine - increased local anaesthetic systemic toxicity (LAST) risk. Use intralipid protocol.",
        "The expanded blood volume (~1000-1500 mL buffer) means parturients can mask significant haemorrhage before haemodynamic compromise - maintain vigilance.",
    ]:
        s.append(key_point(t))
    return s


def gi_renal_section():
    s = [sp(4), section_banner("4.  GASTROINTESTINAL AND RENAL SYSTEMS", TEAL), sp(2)]

    # GI
    s.append(Paragraph("<b>Gastrointestinal System</b>", SUBSEC_TITLE))
    s.append(hr(colors.HexColor("#A9DFBF")))
    s.append(sp(1))
    s.append(subsec_banner("Changes and Causes", bg=colors.HexColor("#D5F5E3")))
    s.append(sp(2))
    for t in [
        "<b>Delayed gastric emptying</b> and decreased lower oesophageal sphincter (LOS) tone due to progesterone's smooth muscle relaxant effect and mechanical displacement of the stomach by the gravid uterus.",
        "Gastric acid secretion increases (placental gastrin production).",
        "Raised intra-abdominal pressure from the gravid uterus further reduces LOS competence.",
        "These factors together increase the risk of <b>regurgitation and pulmonary aspiration</b>.",
    ]:
        s.append(bullet_item(t))
    s.append(sp(2))

    headers = ["GI Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause"]
    rows = [
        ["Gastric Emptying",         "Normal / slight delay", "Delayed",         "Delayed (worse in labour)", "Progesterone relaxes smooth muscle"],
        ["Lower Oesophageal Sphincter","Slight ↓ tone",       "Reduced tone",    "Significantly reduced",    "Progesterone + mechanical elevation"],
        ["Gastric Acid Secretion",   "↑ (early)",             "↑↑",              "↑↑↑",                      "Placental gastrin production"],
        ["Intra-abdominal Pressure", "Normal",                "Moderately ↑",    "Markedly ↑",               "Gravid uterus"],
        ["Nausea/Vomiting",          "Common (hCG peak)",     "Reduces",         "Less common",              "hCG + progesterone"],
    ]
    cws = [PAGE_W*0.19, PAGE_W*0.12, PAGE_W*0.12, PAGE_W*0.14, PAGE_W*0.43]
    s.append(make_table(headers, rows, cws, hdr_bg=TEAL))
    s.append(sp(2))

    s.append(subsec_banner("Anaesthetic Implications (GI)", bg=colors.HexColor("#D5F5E3")))
    s.append(sp(2))
    for t in [
        "<b>All obstetric patients are considered to have a full stomach from ~16-20 weeks onwards</b>, regardless of fasting time.",
        "<b>Aspiration prophylaxis</b>: sodium citrate 30 mL PO (non-particulate antacid), ranitidine 150 mg PO / 50 mg IV, and metoclopramide 10 mg IV should be given before general anaesthesia.",
        "<b>Rapid sequence induction (RSI) with cricoid pressure</b> is mandatory for all pregnant patients receiving general anaesthesia after 20 weeks.",
        "Regional anaesthesia is strongly preferred to eliminate airway manipulation entirely.",
    ]:
        s.append(key_point(t))
    s.append(sp(4))

    # Renal
    s.append(Paragraph("<b>Renal System</b>", SUBSEC_TITLE))
    s.append(hr(colors.HexColor("#A9DFBF")))
    s.append(sp(1))
    s.append(subsec_banner("Changes and Causes", bg=colors.HexColor("#D5F5E3")))
    s.append(sp(2))
    for t in [
        "Renal blood flow and GFR increase by <b>50%</b> (driven by increased CO and reduced renal vascular resistance via relaxin).",
        "Serum creatinine and urea fall - normal creatinine in pregnancy is ~0.4-0.7 mg/dL.",
        "Progesterone causes ureteral dilation and reduced ureteric tone (physiological hydronephrosis).",
        "Glycosuria may be present without diabetes - tubular reabsorption capacity is overwhelmed.",
        "Sodium and water retention (aldosterone and ADH) accounts for the 6-8 L increase in total body water.",
    ]:
        s.append(bullet_item(t))
    s.append(sp(2))

    headers = ["Renal Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause"]
    rows = [
        ["GFR",                   "+30-40%",      "+40-50%",     "+50%",              "↑ CO + ↓ renal vasc. resistance"],
        ["Renal Blood Flow",      "+30%",         "+40-50%",     "+50%",              "Relaxin, progesterone"],
        ["Serum Creatinine",      "~0.6 mg/dL",   "~0.5 mg/dL",  "~0.4-0.7 mg/dL",  "↑ GFR + dilution"],
        ["Serum Urea/BUN",        "Falls",        "Further fall", "Lowest",           "↑ GFR"],
        ["Glycosuria",            "Possible",     "Common",       "Common",           "Tubular reabsorption overwhelmed"],
        ["Ureteric Dilation",     "Begins",       "Progressive",  "Marked",           "Progesterone + uterine compression"],
    ]
    cws = [PAGE_W*0.19, PAGE_W*0.12, PAGE_W*0.12, PAGE_W*0.14, PAGE_W*0.43]
    s.append(make_table(headers, rows, cws, hdr_bg=TEAL))
    s.append(sp(2))

    s.append(subsec_banner("Anaesthetic Implications (Renal)", bg=colors.HexColor("#D5F5E3")))
    s.append(sp(2))
    for t in [
        "Standard adult reference ranges for creatinine and urea do <i>not</i> apply in pregnancy - a creatinine of 0.8 mg/dL may represent significant renal impairment.",
        "<b>Magnesium sulphate</b> (used for seizure prophylaxis in preeclampsia): Mg²⁺ is renally cleared and accumulates if GFR falls; it potentiates NMBDs and reduces MAC. Monitor levels; calcium gluconate is the antidote (10 mL of 10% IV).",
        "Glycosuria alone does not diagnose gestational diabetes - a glucose tolerance test is required.",
    ]:
        s.append(key_point(t))
    return s


def neuro_hepatic_section():
    s = [sp(4), section_banner("5.  NEUROLOGICAL, HEPATIC, AND ENDOCRINE SYSTEMS", DARK_ORG), sp(2)]

    s.append(subsec_banner("Changes and Causes", bg=colors.HexColor("#FCF3CF")))
    s.append(sp(2))

    s.append(Paragraph("<b>Neurological / CNS</b>", BOLD_LABEL))
    for t in [
        "<b>MAC is reduced by 32-40%</b> - progesterone's sedating effect (progesterone is a potent CNS depressant) and elevated endorphin levels are the primary mechanisms.",
        "<b>Epidural and intrathecal local anaesthetic requirements are reduced by 25-40%</b>: (a) engorgement of epidural veins (from IVC compression) reduces epidural space volume; (b) increased neural sensitivity from hormonal effects; (c) reduced CSF volume.",
        "Lumbar lordosis increases with advancing gestation, altering the angle needed for epidural/spinal placement.",
    ]:
        s.append(bullet_item(t))
    s.append(sp(2))

    s.append(Paragraph("<b>Hepatic System</b>", BOLD_LABEL))
    for t in [
        "Serum albumin falls to ~2.8-3.2 g/dL (dilution + altered synthesis), increasing the free fraction of protein-bound drugs.",
        "Serum alkaline phosphatase increases 3-4× - this is <b>placental in origin</b> (not hepatic) and is normal.",
        "ALT, AST, and bilirubin are essentially unchanged. Any elevation is pathological (e.g. HELLP syndrome, intrahepatic cholestasis of pregnancy).",
        "Hepatic blood flow increases proportionally with cardiac output.",
    ]:
        s.append(bullet_item(t))
    s.append(sp(2))

    s.append(Paragraph("<b>Endocrine / Metabolic</b>", BOLD_LABEL))
    for t in [
        "Insulin resistance develops due to human placental lactogen (HPL), progesterone, and cortisol - causes gestational diabetes in susceptible women.",
        "Basal metabolic rate increases ~15-20% from mid-pregnancy.",
        "Total T3/T4 increase (more thyroid-binding globulin) but free T3/T4 are usually normal; first-trimester gestational thyrotoxicosis can occur (hCG cross-reacts with TSH receptor).",
    ]:
        s.append(bullet_item(t))
    s.append(sp(3))

    s.append(subsec_banner("Trimester-by-Trimester Comparison", bg=colors.HexColor("#FCF3CF")))
    s.append(sp(2))
    headers = ["System / Parameter", "1st Trimester", "2nd Trimester", "3rd Trimester", "Cause"]
    rows = [
        ["MAC (Volatile Agents)",          "Slight ↓",          "-20%",               "-32 to -40%",         "Progesterone / β-endorphins"],
        ["Epidural space volume",          "Normal",            "Starts to decrease",  "Reduced",             "IVC compression → engorged epidural veins"],
        ["Intrathecal LA spread",          "Normal",            "Slightly enhanced",   "Enhanced",            "↓ CSF volume, altered CSF density"],
        ["Lumbar lordosis",                "Increasing",        "Moderate",            "Marked",              "Weight + lax ligaments"],
        ["Neural sensitivity to LA",       "May be ↑",          "↑",                   "↑↑",                  "Progesterone alters nerve membranes"],
        ["Serum Albumin",                  "Slight ↓",          "~3.0 g/dL",           "~2.8-3.2 g/dL",       "Dilution + altered synthesis"],
        ["Alkaline Phosphatase",           "↑↑ (placental)",    "↑↑",                  "3-4× normal",         "Placental isoform - NOT hepatic"],
        ["ALT/AST/Bilirubin",              "Normal",            "Normal",              "Normal (mild biliary stasis)", "Any elevation = pathology"],
        ["Insulin Resistance",             "Mild",              "Moderate",            "Marked",              "HPL, progesterone, cortisol"],
        ["Total T3/T4",                    "↑ (early hCG peak)","↑",                   "↑",                   "↑ Thyroid-binding globulin"],
    ]
    cws = [PAGE_W*0.21, PAGE_W*0.12, PAGE_W*0.13, PAGE_W*0.14, PAGE_W*0.40]
    s.append(make_table(headers, rows, cws, hdr_bg=DARK_ORG))
    s.append(sp(3))

    s.append(subsec_banner("Anaesthetic Implications", bg=colors.HexColor("#FCF3CF")))
    s.append(sp(2))
    for t in [
        "<b>Reduce intrathecal bupivacaine dose</b> for caesarean (typically 10-12 mg vs 15 mg in non-pregnant patients) - enhanced spread increases risk of total spinal.",
        "<b>Reduce induction agent doses</b> (propofol, thiopentone) due to lower albumin and CNS sensitivity.",
        "<b>Alkaline phosphatase elevation is normal</b> in pregnancy - do not misinterpret as hepatic pathology.",
        "Monitor blood glucose perioperatively; insulin requirements change significantly in the peripartum period.",
    ]:
        s.append(key_point(t))
    return s


def anaesthetic_summary():
    s = [sp(4), section_banner("6.  ANAESTHETIC IMPLICATIONS - KEY SUMMARY TABLE", RED), sp(2)]

    headers = ["Clinical Concern", "Physiological Basis", "Action Required"]
    rows = [
        ["Difficult / Failed\nIntubation",
         "Airway oedema, ↑ Mallampati,\nbreast engorgement",
         "Preoxygenate, short-handle laryngoscope, video laryngoscopy immediately available, RSI, avoid nasal route"],

        ["Rapid Desaturation\non Apnoea",
         "↓ FRC + ↑ O₂ consumption",
         "Preoxygenate ≥3 min (FiO₂ 1.0); 4 vital capacity breaths minimum before RSI"],

        ["Aspiration Risk",
         "↓ LOS tone, delayed gastric emptying,\n↑ gastric acid",
         "Sodium citrate + H2-blocker + metoclopramide; RSI + cricoid pressure for GA; prefer regional"],

        ["Aortocaval\nCompression",
         "Gravid uterus compresses IVC + aorta\n(from 20 weeks)",
         "Left lateral tilt ≥15° (wedge under right hip) at ALL TIMES from 20 weeks"],

        ["Hypotension\n(post-spinal/epidural)",
         "Sympathectomy in already-low SVR state",
         "Phenylephrine infusion/boluses (preferred), IV fluid co-load, LUD, supplemental O₂"],

        ["Reduced Neuraxial\nDrug Requirements",
         "Engorged epidural veins, ↑ neural\nsensitivity, ↓ CSF volume",
         "Reduce intrathecal + epidural doses by 25-40% vs non-pregnant adult doses"],

        ["Reduced MAC\n(Volatile Agents)",
         "Progesterone, β-endorphins",
         "Reduce volatile agent dose by 32-40%; monitor for awareness"],

        ["Succinylcholine for RSI",
         "↓ Cholinesterase (-20-30%)",
         "Safe to use; modest prolongation (~2-5 min) only; no dose change needed"],

        ["Magnesium Toxicity\n(Preeclampsia Rx)",
         "Mg²⁺ potentiates NMBDs, ↓ MAC,\naccumulates if GFR ↓",
         "Reduce NMBD dose, use NM monitoring, Ca gluconate as antidote"],

        ["Neuraxial Timing\nwith Anticoagulants",
         "Hypercoagulable state → LMWH /\nheparin commonly used",
         "Min 12 h (prophylactic LMWH) / 24 h (therapeutic LMWH) before neuraxial block (ASRA guidelines)"],

        ["Haemorrhage",
         "Hypercoagulability + ↑ blood volume\nbuffers early loss",
         "Anticipate rapid decompensation; crossmatch, activate MTP early, have FFP/PLT/cryoprecipitate available"],

        ["Fetal Drug Exposure",
         "Lipophilic, low-MW, un-ionised drugs\ncross placenta freely",
         "Prefer regional anaesthesia; use lowest effective doses; time delivery if GA given"],
    ]
    cws = [PAGE_W*0.17, PAGE_W*0.30, PAGE_W*0.53]
    tbl = Table(
        [[Paragraph(h, TABLE_HDR) for h in headers]] +
        [[Paragraph(str(c), TABLE_CELL) for c in row] for row in rows],
        colWidths=cws, repeatRows=1
    )
    tbl.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,0),  RED),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [colors.HexColor("#FDEDEC"), colors.HexColor("#FEF9F9")]),
        ("GRID",          (0,0), (-1,-1), 0.4, colors.HexColor("#F1948A")),
        ("LINEBELOW",     (0,0), (-1,0),  1.5, RED),
        ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ("ALIGN",         (0,0), (-1,0),  "CENTER"),
        ("TOPPADDING",    (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING",   (0,0), (-1,-1), 5),
        ("RIGHTPADDING",  (0,0), (-1,-1), 5),
        ("FONTSIZE",      (0,0), (-1,-1), 8),
    ]))
    s.append(tbl)
    return s


def references():
    s = [sp(6), hr()]
    s.append(Paragraph(
        "<b>References:</b> "
        "1. Ende HB, Peralta FM, Wong CA. Obstetric Anesthesia. In: Barash PG, Cullen BF, Stoelting RK, et al., eds. "
        "<i>Clinical Anesthesia</i>, 9th ed. Wolters Kluwer; 2023: Chapter 41, pp. 3470-3510. | "
        "2. Frölich MA. Obstetric Anesthesia. In: Butterworth JF, Mackey DC, Wasnick JD, eds. "
        "<i>Morgan &amp; Mikhail's Clinical Anesthesiology</i>, 7th ed. McGraw-Hill; 2022: pp. 1601-1650.",
        FOOTNOTE))
    s.append(Paragraph(
        "This document is for educational reference only. Clinical decisions should be based on current "
        "guidelines and individual patient assessment.",
        FOOTNOTE))
    return s


# ─── Page number footer ────────────────────────────────────────────────────────
def add_page_number(canvas, doc):
    canvas.saveState()
    canvas.setFont("Helvetica", 7)
    canvas.setFillColor(GREY)
    page_num = canvas.getPageNumber()
    text = f"Physiological Changes in Pregnancy  |  Page {page_num}"
    canvas.drawCentredString(W / 2.0, 10*mm, text)
    canvas.restoreState()


# ─── Build ─────────────────────────────────────────────────────────────────────
def build():
    doc = SimpleDocTemplate(
        OUTPUT,
        pagesize=A4,
        leftMargin=1.2*cm, rightMargin=1.2*cm,
        topMargin=1.2*cm, bottomMargin=1.8*cm,
        title="Physiological Changes in Pregnancy - Anaesthetic Implications",
        author="Orris Medical Reference",
        subject="Obstetric Anaesthesia"
    )

    story = []
    story.extend(title_block())
    story.extend(overview_section())
    story.append(PageBreak())
    story.extend(respiratory_section())
    story.append(PageBreak())
    story.extend(cardiovascular_section())
    story.append(PageBreak())
    story.extend(haematology_section())
    story.append(PageBreak())
    story.extend(gi_renal_section())
    story.append(PageBreak())
    story.extend(neuro_hepatic_section())
    story.append(PageBreak())
    story.extend(anaesthetic_summary())
    story.extend(references())

    doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
    print(f"Done: {OUTPUT}")

build()
Running Command

cd /tmp/workspace/pregnancy-physiology && python generate_pdf_v2.py 2>&1

Running Command

ls -lh /tmp/workspace/pregnancy-physiology/Physiological_Changes_in_Pregnancy_v2.pdf

Here it is:

Physiological Changes in Pregnancy v2

PDF Document · PDF

This version mirrors exactly how I wrote the answer - structured with:
  • Colour-coded section banners for each system (respiratory, cardiovascular, haematology, GI/renal, neuro/hepatic/endocrine)
  • "Changes and Causes" subsection with narrative bullet points explaining the physiology
  • Trimester comparison table (1st / 2nd / 3rd trimester + Cause column) for each system
  • "Anaesthetic Implications" subsection with numbered action points per system
  • Final summary table covering all 12 key clinical concerns with physiological basis + action required
  • Page numbers in the footer + references at the end

Why

Asking for Preferences
Your credits are exhausted. You can purchase a top-up or subscribe to a plan to continue using Orris. If you're already subscribed, your daily credits will reset tomorrow.

I had hundred credits

Your credits are exhausted. You can purchase a top-up or subscribe to a plan to continue using Orris. If you're already subscribed, your daily credits will reset tomorrow.
This is a shared conversation. Sign in to Orris to start your own chat.