Make this pdf easy to understand
cd "/home/daytona/workspace/attachments/8b2d66a2-975d-49c0-8473-5f63a308fd39" && python3 -c " import pdfplumber with pdfplumber.open('Surgery One Page Notes.pdf') as pdf: print(f'Total pages: {len(pdf.pages)}') for i, page in enumerate(pdf.pages): print(f'\n=== PAGE {i+1} ===') text = page.extract_text() if text: print(text[:3000]) else: print('[No text extracted]') "
cd "/home/daytona/workspace/attachments/8b2d66a2-975d-49c0-8473-5f63a308fd39" && python3 -c " from pdf2image import convert_from_path import os pages = convert_from_path('Surgery One Page Notes.pdf', dpi=150) os.makedirs('/home/daytona/workspace/surgery-notes/pages', exist_ok=True) for i, page in enumerate(pages): page.save(f'/home/daytona/workspace/surgery-notes/pages/page_{i+1}.jpg', 'JPEG') print(f'Saved page {i+1}') "
~/surgery-notes/generate_pdf.py
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
HRFlowable, PageBreak, KeepTogether
)
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
from reportlab.platypus import ListFlowable, ListItem
# ── colour palette ──────────────────────────────────────────────────────────
C_TITLE = colors.HexColor("#1a3a5c") # dark navy
C_HEAD1 = colors.HexColor("#2563a8") # blue section heading bg
C_HEAD2 = colors.HexColor("#e8f0fb") # light blue sub-heading bg
C_ACCENT = colors.HexColor("#e05c1a") # orange accent (key points star)
C_TABLE_H = colors.HexColor("#2563a8")
C_TABLE_R = colors.HexColor("#f0f5ff")
C_RULE = colors.HexColor("#2563a8")
C_WARN = colors.HexColor("#fff3cd") # yellow highlight bg
C_WARNBDR = colors.HexColor("#e6a817")
C_GREEN = colors.HexColor("#d4edda")
C_GREENBDR= colors.HexColor("#28a745")
WHITE = colors.white
BLACK = colors.black
W, H = A4
def build_styles():
styles = getSampleStyleSheet()
def add(name, **kw):
styles.add(ParagraphStyle(name=name, **kw))
add("DocTitle",
fontName="Helvetica-Bold", fontSize=26, textColor=C_TITLE,
alignment=TA_CENTER, spaceAfter=4)
add("DocSubtitle",
fontName="Helvetica-Oblique", fontSize=11, textColor=colors.grey,
alignment=TA_CENTER, spaceAfter=14)
add("Sec1", # numbered section heading on coloured band
fontName="Helvetica-Bold", fontSize=12, textColor=WHITE,
leftIndent=6, spaceAfter=0, spaceBefore=0, leading=16)
add("Sec2", # sub-heading on light bg
fontName="Helvetica-Bold", fontSize=10.5, textColor=C_TITLE,
leftIndent=6, spaceAfter=2, spaceBefore=4, leading=14)
add("Body",
fontName="Helvetica", fontSize=9.5, textColor=BLACK,
leftIndent=12, spaceAfter=2, leading=13)
add("Bullet",
fontName="Helvetica", fontSize=9.5, textColor=BLACK,
leftIndent=20, spaceAfter=1, leading=13)
add("SubBullet",
fontName="Helvetica", fontSize=9, textColor=colors.HexColor("#333333"),
leftIndent=34, spaceAfter=1, leading=12)
add("KeyPoint",
fontName="Helvetica-BoldOblique", fontSize=9.5,
textColor=colors.HexColor("#7b1d00"),
leftIndent=12, spaceAfter=1, leading=13)
add("Summary",
fontName="Helvetica", fontSize=9.5, textColor=BLACK,
leftIndent=10, spaceAfter=2, leading=14, alignment=TA_JUSTIFY)
add("TableHeader",
fontName="Helvetica-Bold", fontSize=9, textColor=WHITE,
alignment=TA_CENTER)
add("TableCell",
fontName="Helvetica", fontSize=9, textColor=BLACK, leading=12)
add("CaptionStyle",
fontName="Helvetica-Oblique", fontSize=8.5,
textColor=colors.grey, alignment=TA_CENTER)
return styles
styles = build_styles()
# ── helper builders ──────────────────────────────────────────────────────────
def topic_title(title, subtitle="According to S. Das & Manipal Manual of Surgery"):
return [
Paragraph(title, styles["DocTitle"]),
Paragraph(f"({subtitle})", styles["DocSubtitle"]),
HRFlowable(width="100%", thickness=2, color=C_RULE, spaceAfter=10),
]
def sec1(num, text):
"""Blue band section heading."""
inner = Paragraph(f"{num}. {text.upper()}", styles["Sec1"])
t = Table([[inner]], colWidths=[W - 4*cm])
t.setStyle(TableStyle([
("BACKGROUND", (0,0), (-1,-1), C_HEAD1),
("TOPPADDING", (0,0), (-1,-1), 4),
("BOTTOMPADDING", (0,0), (-1,-1), 4),
("LEFTPADDING", (0,0), (-1,-1), 8),
("RIGHTPADDING", (0,0), (-1,-1), 4),
("ROUNDEDCORNERS", [4]),
]))
return [Spacer(1, 6), t, Spacer(1, 4)]
def sec2(text):
inner = Paragraph(text, styles["Sec2"])
t = Table([[inner]], colWidths=[W - 4*cm])
t.setStyle(TableStyle([
("BACKGROUND", (0,0), (-1,-1), C_HEAD2),
("TOPPADDING", (0,0), (-1,-1), 3),
("BOTTOMPADDING", (0,0), (-1,-1), 3),
("LEFTPADDING", (0,0), (-1,-1), 8),
("RIGHTPADDING", (0,0), (-1,-1), 4),
("LINEBELOW", (0,0), (-1,-1), 0.5, C_RULE),
]))
return [t, Spacer(1, 3)]
def bullet(text, sub=False):
s = styles["SubBullet"] if sub else styles["Bullet"]
prefix = " \u2013 " if sub else "\u2022 "
return Paragraph(f"{prefix}{text}", s)
def key_point(text):
return Paragraph(f"\u2605 {text}", styles["KeyPoint"])
def body(text):
return Paragraph(text, styles["Body"])
def spacer(n=6):
return Spacer(1, n)
def summary_box(lines):
content = [Paragraph(f"\u2022 {l}", styles["Summary"]) for l in lines]
t = Table([[content]], colWidths=[W - 4*cm])
t.setStyle(TableStyle([
("BACKGROUND", (0,0), (-1,-1), C_GREEN),
("LINEABOVE", (0,0), (-1, 0), 1.5, C_GREENBDR),
("LINEBELOW", (0,-1), (-1,-1), 1.5, C_GREENBDR),
("LINEBEFORE", (0,0), (0,-1), 1.5, C_GREENBDR),
("LINEAFTER", (-1,0), (-1,-1), 1.5, C_GREENBDR),
("TOPPADDING", (0,0), (-1,-1), 6),
("BOTTOMPADDING", (0,0), (-1,-1), 6),
("LEFTPADDING", (0,0), (-1,-1), 10),
]))
return [Spacer(1, 8), Paragraph("<b>SUMMARY</b>", styles["Sec2"]), t, Spacer(1, 6)]
def key_points_box(points):
content = [key_point(p) for p in points]
t = Table([[content]], colWidths=[W - 4*cm])
t.setStyle(TableStyle([
("BACKGROUND", (0,0), (-1,-1), C_WARN),
("LINEABOVE", (0,0), (-1, 0), 1.5, C_WARNBDR),
("LINEBELOW", (0,-1), (-1,-1), 1.5, C_WARNBDR),
("LINEBEFORE", (0,0), (0,-1), 1.5, C_WARNBDR),
("LINEAFTER", (-1,0), (-1,-1), 1.5, C_WARNBDR),
("TOPPADDING", (0,0), (-1,-1), 6),
("BOTTOMPADDING", (0,0), (-1,-1), 6),
("LEFTPADDING", (0,0), (-1,-1), 10),
]))
return [Spacer(1, 8), Paragraph("<b>IMPORTANT EXAM POINTS</b>", styles["Sec2"]), t, Spacer(1, 6)]
def simple_table(headers, rows, col_widths=None):
"""Generic comparison / data table."""
cw = col_widths or [((W - 4*cm) / len(headers))] * len(headers)
header_row = [Paragraph(h, styles["TableHeader"]) for h in headers]
data = [header_row]
for i, row in enumerate(rows):
data.append([Paragraph(str(c), styles["TableCell"]) for c in row])
ts = TableStyle([
("BACKGROUND", (0, 0), (-1, 0), C_TABLE_H),
("ROWBACKGROUNDS",(0, 1), (-1, -1), [WHITE, C_TABLE_R]),
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#aaaaaa")),
("TOPPADDING", (0, 0), (-1, -1), 4),
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
("LEFTPADDING", (0, 0), (-1, -1), 5),
("RIGHTPADDING", (0, 0), (-1, -1), 5),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
])
t = Table(data, colWidths=cw)
t.setStyle(ts)
return [t, Spacer(1, 6)]
# ════════════════════════════════════════════════════════════════════════════
# CONTENT
# ════════════════════════════════════════════════════════════════════════════
def page_crohn():
e = []
e += topic_title("CROHN DISEASE")
# 1
e += sec1(1, "Definition")
e.append(body("Crohn disease (regional enteritis) is a <b>chronic, transmural, granulomatous</b> inflammatory disease of any part of the GI tract from mouth to anus, most commonly affecting the <b>terminal ileum</b>."))
e.append(spacer())
# 2
e += sec1(2, "Etiology")
for t in ["Exact cause unknown (multifactorial)","Genetic predisposition",
"Abnormal immune response to intestinal flora",
"Environmental factors – smoking, diet","Infectious agents (not proven)"]:
e.append(bullet(t))
e.append(spacer())
# 3
e += sec1(3, "Pathology")
for t in ["Transmural inflammation – all layers involved",
"Skip lesions – normal segments between diseased areas",
"Non-caseating epithelioid cell granulomas","Cobblestone mucosa",
"Fissures, fistulae, strictures",
"Hypertrophy of mesenteric fat – \"creeping fat\""]:
e.append(bullet(t))
e.append(spacer())
# 4
e += sec1(4, "Common Sites (Frequency)")
for t in ["Terminal ileum (most common) – 60–70%","Ileocolic – 20–30%",
"Colon only – 10–15%","Upper GIT (rare)"]:
e.append(bullet(t))
e.append(spacer())
# 5
e += sec1(5, "Clinical Features")
e += sec2("A. Symptoms")
for t in ["Pain abdomen – colicky, RIF","Diarrhea (may be intermittent)",
"Low grade fever","Anorexia, nausea","Weight loss","Malaise, weakness",
"Per rectal symptoms – pain, discharge, bleeding (if perianal disease)"]:
e.append(bullet(t))
e += sec2("B. Signs")
for t in ["Pallor","Abdominal tenderness – RIF",
"Mass – RIF (inflammatory / phlegmonous mass)",
"Features of complications: Obstruction, Fistula, Perforation / Abscess"]:
e.append(bullet(t))
e.append(spacer())
# 6
e += sec1(6, "Diagnosis")
for t in ["History","Clinical features","Investigations","Endoscopy",
"Histopathology (Non-caseating granuloma supports diagnosis)"]:
e.append(bullet(t))
e.append(spacer())
# 7
e += sec1(7, "Investigations")
e += sec2("A. Laboratory")
for t in ["Hb – low (anaemia)","TLC – raised","ESR – raised",
"Serum albumin – low","Stool – R/E (to exclude infection)"]:
e.append(bullet(t))
e += sec2("B. Imaging")
for t in ["X-ray abdomen – features of obstruction, fistula",
"Barium follow through / Enteroclysis – skip lesions, strictures, fistulae",
"Ultrasound – bowel wall thickening, abscess, fistula",
"CT Enterography – best for extent and complications"]:
e.append(bullet(t))
e += sec2("C. Endoscopy")
e.append(bullet("Colonoscopy with biopsy – cobblestoning, ulcers, skip lesions"))
e.append(spacer())
# 8
e += sec1(8, "Complications")
for t in ["Stricture (fibrotic)","Obstruction",
"Fistula (Enteroenteric, Enterocutaneous, Enterovesical, Enterovaginal, Perianal)",
"Abscess (intra-abdominal / pelvic)","Perforation","Bleeding",
"Malabsorption","Increased risk of carcinoma (colon)"]:
e.append(bullet(t))
e.append(spacer())
# 9
e += sec1(9, "Differential Diagnosis")
for t in ["Intestinal tuberculosis","Ulcerative colitis","Amoebiasis",
"Carcinoma colon","Irritable bowel syndrome"]:
e.append(bullet(t))
e.append(spacer())
# 10
e += sec1(10, "Course")
for t in ["Chronic relapsing","Remissions and exacerbations",
"Fibrostenotic or fistulizing complications common"]:
e.append(bullet(t))
e.append(spacer())
# 11
e += sec1(11, "Management")
e += sec2("A. Medical Management (For Active Disease)")
for t in ["Rest, high calorie, high protein diet",
"Correction of anemia, dehydration, electrolyte imbalance",
"Anti-inflammatory drugs – Sulfasalazine, Mesalamine",
"Corticosteroids (Prednisolone)",
"Immunomodulators – Azathioprine / 6-MP",
"Biological agents – Infliximab, Adalimumab",
"Antibiotics (for abscess/fistula) – Metronidazole, Ciprofloxacin"]:
e.append(bullet(t))
e += sec2("B. Indications for Surgery")
for t in ["Obstruction not responding to medical treatment","Stricture (fibrotic)",
"Fistulae","Abscess not responding to medical treatment",
"Perforation","Massive bleeding","Suspicion of malignancy",
"Disease resistant to medical therapy"]:
e.append(bullet(t))
e += sec2("C. Surgical Management")
e.append(body("<b>Principles:</b> Remove diseased segment • Preserve normal bowel • Wide mesenteric excision • Avoid extensive resections"))
for t in ["Limited resection and primary anastomosis",
"Strictureplasty (where appropriate)",
"Drainage of abscess","Fistula surgery",
"Stoma (temporary / permanent) in selected cases"]:
e.append(bullet(t))
e.append(spacer())
# 12
e += sec1(12, "Surgical Complications")
for t in ["Anastomotic leak","Wound infection","Intra-abdominal abscess",
"Short bowel syndrome","Recurrent disease"]:
e.append(bullet(t))
e.append(spacer())
e += key_points_box([
"Transmural inflammation (all layers)",
"Skip lesions – hallmark",
"Non-caseating granuloma – diagnostic",
"Creeping fat – characteristic finding",
"Terminal ileum most commonly affected",
"Complications – obstruction, fistula, abscess",
])
e += summary_box([
"Crohn disease is a chronic, transmural granulomatous inflammation of GIT commonly affecting the terminal ileum.",
"It presents with abdominal pain, diarrhea, weight loss.",
"Complications include obstruction, fistula, and abscess.",
"Treatment is medical for active disease and surgery for complications.",
])
e.append(PageBreak())
return e
def page_intestinal_obstruction():
e = []
e += topic_title("INTESTINAL OBSTRUCTION")
# 1
e += sec1(1, "Definition")
e.append(body("Interference with the passage of intestinal contents due to <b>mechanical or functional causes</b>. May involve the small bowel or large bowel."))
e.append(spacer())
# 2
e += sec1(2, "Classification")
e += sec2("A. Mechanical Obstruction")
e.append(bullet("<b>Simple</b> – lumen blocked, blood supply intact"))
e.append(bullet("<b>Strangulated</b> – blood supply compromised → gangrene / perforation"))
e.append(bullet("<b>Closed loop obstruction</b> – obstructed at two points"))
e += sec2("B. Functional (Adynamic) Obstruction")
e.append(bullet("Paralytic ileus"))
e.append(bullet("Pseudo-obstruction"))
e.append(spacer())
# 3
e += sec1(3, "Common Causes")
e += sec2("A. Small Bowel Obstruction (SBO)")
for i, t in enumerate(["Adhesions (most common)","Hernia","Volvulus",
"Intussusception","Tumors","Crohn's disease"], 1):
e.append(bullet(f"{i}. {t}"))
e += sec2("B. Large Bowel Obstruction (LBO)")
for i, t in enumerate(["Carcinoma colon (most common)","Sigmoid volvulus",
"Diverticular stricture","Fecal impaction"], 1):
e.append(bullet(f"{i}. {t}"))
e.append(spacer())
# 4
e += sec1(4, "Cardinal Clinical Features")
e.append(body("<b>\"Pain + Vomiting + Distension + Constipation\"</b>"))
e += simple_table(
["Feature", "Small Bowel Obstruction", "Large Bowel Obstruction"],
[["Pain", "Colicky, central", "Lower abdomen"],
["Vomiting", "Early, profuse", "Late"],
["Distension", "Mild / moderate", "Marked"],
["Constipation", "Late", "Early (absolute)"]],
col_widths=[4*cm, 6*cm, 6*cm]
)
e += sec2("Examination Findings")
for t in ["Dehydration, tachycardia","Distended abdomen","Visible peristalsis",
"High-pitched bowel sounds (tinkling)",
"Guarding / rigidity → strangulation / peritonitis"]:
e.append(bullet(t))
e.append(spacer())
# 5
e += sec1(5, "Pathophysiology")
for t in ["Proximal bowel dilatation","Fluid & electrolyte loss",
"Bacterial overgrowth","Increased intraluminal pressure",
"Venous congestion → ischemia → gangrene → perforation"]:
e.append(bullet(t))
e.append(spacer())
# 6
e += sec1(6, "Investigations")
e += sec2("A. Blood Tests")
for t in ["CBC","Electrolytes (Na⁺, K⁺, Cl⁻)","Urea / Creatinine","Serum lactate"]:
e.append(bullet(t))
e += sec2("B. Imaging")
e.append(bullet("X-ray abdomen erect – multiple air-fluid levels, dilated bowel loops, step-ladder pattern (SBO)"))
e.append(bullet("<b>CT scan abdomen – best investigation</b> – identifies site, cause, strangulation, ischemia, perforation"))
e.append(spacer())
# 7
e += sec1(7, "Management")
e += sec2("A. Initial Management – \"DRIP & SUCK\"")
for t in ["Nil by mouth","IV fluids","Electrolyte correction",
"NG tube decompression","Foley's catheter",
"Broad spectrum antibiotics if strangulation suspected"]:
e.append(bullet(t))
e += sec2("B. Conservative Treatment – Indicated In")
for t in ["Partial SBO","Adhesive obstruction",
"No signs of strangulation or peritonitis"]:
e.append(bullet(t))
e += sec2("C. Indications for Surgery")
for t in ["Strangulation","Peritonitis","Complete obstruction",
"Failed conservative treatment","Perforation"]:
e.append(bullet(t))
e += sec2("D. Operations (As per cause)")
for t in ["Adhesiolysis","Hernia repair","Resection & anastomosis",
"Stoma formation","Volvulus correction"]:
e.append(bullet(t))
e.append(spacer())
# 8
e += sec1(8, "Complications")
for t in ["Gangrene","Perforation","Septic shock","Acute kidney injury",
"Electrolyte imbalance","Death"]:
e.append(bullet(t))
e.append(spacer())
e += key_points_box([
"Most common cause of SBO → Adhesions",
"Most common cause of LBO → Carcinoma colon",
"Absolute constipation is characteristic of complete obstruction",
"Pain becoming continuous suggests strangulation",
"CT abdomen = investigation of choice",
])
e += summary_box([
"Early diagnosis + resuscitation + timely surgery reduces morbidity and mortality.",
"Always look for signs of strangulation: fever, tachycardia, continuous pain, tenderness, guarding, leukocytosis, metabolic acidosis.",
])
e.append(PageBreak())
return e
def page_appendicitis():
e = []
e += topic_title("APPENDICITIS")
# 1
e += sec1(1, "Definition")
e.append(body("Appendicitis is <b>inflammation of the vermiform appendix</b>. It is the <b>commonest surgical emergency</b> of the abdomen."))
e.append(spacer())
# 2
e += sec1(2, "Anatomy – Key Points")
for t in ["Vermiform appendix – narrow, blind tube arising from posteromedial wall of caecum, 2–3 cm below ileocaecal junction",
"Length – 6 to 9 cm (variable)",
"Position variable: Retrocaecal 65% | Pelvic 31% | Subcaecal 2% | Pre-ileal 1% | Post-ileal 1%"]:
e.append(bullet(t))
e.append(spacer())
# 3
e += sec1(3, "Pathology")
e.append(bullet("Luminal obstruction (most common) → Bacterial overgrowth → Inflammation → Ischemia → Gangrene → Perforation"))
e += sec2("Causes of Obstruction")
for t in ["Lymphoid hyperplasia (most common)","Fecalith","Foreign body",
"Parasites","Tumor (rare)"]:
e.append(bullet(t, sub=True))
e += sec2("Progression")
e.append(bullet("Catarrhal → Suppurative → Gangrenous → Perforated"))
e.append(spacer())
# 4
e += sec1(4, "Etiology")
for t in ["Most common in 10–20 years age group","Male > Female",
"Low fiber diet, lymphoid hyperplasia, fecalith, worm infestation"]:
e.append(bullet(t))
e.append(spacer())
# 5
e += sec1(5, "Clinical Features")
e += sec2("A. Symptoms")
for t in ["Anorexia","Nausea, vomiting (after pain)",
"Pain – initially vague around umbilicus/epigastrium → later localizes to right iliac fossa (RIF)",
"Low grade fever","Constipation or diarrhea"]:
e.append(bullet(t))
e += sec2("B. Signs")
for t in ["Tenderness in RIF (McBurney's point)","Rebound tenderness",
"Guarding, rigidity (late)"]:
e.append(bullet(t))
e += sec2("Positive Signs")
for t in ["1. McBurney's point tenderness","2. Rovsing's sign",
"3. Psoas sign","4. Obturator sign"]:
e.append(bullet(t, sub=True))
e.append(spacer())
# 6
e += sec1(6, "Clinical Diagnosis")
for t in ["History","Clinical examination","Supportive investigations"]:
e.append(bullet(t))
e.append(spacer())
# 7
e += sec1(7, "Investigations")
e += sec2("A. Laboratory")
for t in ["TLC – Raised (12,000–18,000/mm³)","Neutrophilia",
"Urine – normal (to rule out UTI)","Pregnancy test – in females"]:
e.append(bullet(t))
e += sec2("B. Imaging")
e.append(bullet("Ultrasonography (first choice) – non-compressible, blind-ending tubular structure >6 mm diameter; appendicolith, periappendiceal fluid"))
e.append(bullet("CT Scan (if diagnosis doubtful) – most accurate"))
e.append(spacer())
# 8
e += sec1(8, "Differential Diagnosis")
for t in ["Mesenteric lymphadenitis","Gastroenteritis","Ureteric colic (right side)",
"Meckel's diverticulitis","Crohn's disease",
"Ovarian cyst/torsion (females)","Ectopic pregnancy (females)"]:
e.append(bullet(t))
e.append(spacer())
# 9
e += sec1(9, "Complications")
for t in ["Perforation (most common)","Localized or generalized peritonitis",
"Appendix mass (phlegmon)","Abscess (appendicular / pelvic)",
"Pylephlebitis","Fecal fistula","Adhesive intestinal obstruction"]:
e.append(bullet(t))
e.append(spacer())
# 10
e += sec1(10, "Management")
e += sec2("A. General (All Cases)")
for t in ["NPO (nil by mouth)","IV fluids","Analgesics",
"Antibiotics (e.g., Ceftriaxone + Metronidazole)",
"Nasogastric tube – if vomiting","Treat complications if present"]:
e.append(bullet(t))
e += sec2("B. Definitive – Appendectomy")
e.append(bullet("Open Appendectomy – Gridiron (McBurney) incision or Lanz incision"))
e.append(bullet("Laparoscopic Appendectomy – preferred in uncomplicated cases; better cosmesis, early recovery"))
e.append(spacer())
# 11
e += sec1(11, "Indications for Surgery")
for t in ["All diagnosed cases of acute appendicitis","Recurrent appendicitis",
"Appendix mass not responding to conservative treatment",
"Complicated appendicitis (abscess, perforation, peritonitis)"]:
e.append(key_point(t))
e.append(spacer())
# 12 & 13
e += sec1(12, "Postoperative Care")
for t in ["Continue IV fluids & antibiotics","Analgesics",
"Early oral intake as tolerated","Early ambulation",
"Wound care","Watch for complications"]:
e.append(bullet(t))
e.append(spacer())
e += sec1(13, "Complications of Surgery")
for t in ["Wound infection","Intra-abdominal abscess","Fecal fistula",
"Adhesive intestinal obstruction"]:
e.append(bullet(t))
e.append(spacer())
e += key_points_box([
"Most common surgical emergency – Appendicitis",
"Site of maximum tenderness – McBurney's point",
"Sequence of pain – Vague → RIF localization",
"Most common cause of obstruction – Lymphoid hyperplasia",
"Treatment – Appendectomy",
])
e += summary_box([
"Acute appendicitis should be suspected in any patient with anorexia, nausea, vomiting and pain starting around the umbilicus and localizing to the right iliac fossa with tenderness and guarding.",
"Early diagnosis and timely appendectomy prevent complications.",
])
e.append(PageBreak())
return e
def page_hematemesis():
e = []
e += topic_title("HEMATEMESIS")
# 1
e += sec1(1, "Definition")
e.append(body("Hematemesis is the <b>vomiting of blood originating proximal to the ligament of Treitz</b> (i.e., from oesophagus, stomach or duodenum)."))
e.append(spacer())
# 2
e += sec1(2, "Etiology – Common Causes")
for t in ["Peptic ulcer disease (DU > GU)","Portal hypertension (esophageal varices)",
"Erosive gastritis / oesophagitis","Mallory–Weiss tear",
"Carcinoma stomach / oesophagus","Vascular malformations",
"Dieulafoy's lesion","Aorto-enteric fistula (rare)",
"Ingestion of corrosives (late)","Coagulopathies, drugs (NSAIDs, steroids)"]:
e.append(bullet(t))
e.append(spacer())
# 3
e += sec1(3, "Pathophysiology")
for t in ["Blood in upper GI tract → vomiting (hematemesis) or passage of melaena",
"Severity depends on rate of bleeding, total blood loss and patient's reserve",
"Massive blood loss → hypovolaemic shock",
"Portal hypertension → variceal rupture (high pressure, low volume spurting bleed)",
"Peptic ulcer → arterial erosion (usually gastroduodenal or its branches)"]:
e.append(bullet(t))
e.append(spacer())
# 4
e += sec1(4, "Clinical Features")
e += sec2("A. Symptoms")
for t in ["Vomiting of blood – bright red / dark (coffee ground)","Nausea, retching",
"Giddiness, weakness","Palpitations, syncope (in severe bleeding)",
"Passage of melaena (black, tarry stools)"]:
e.append(bullet(t))
e += sec2("B. Signs")
for t in ["Pallor, cold clammy extremities","Tachycardia, hypotension",
"Signs of shock (in massive loss)",
"Abdominal findings – underlying cause"]:
e.append(bullet(t))
e.append(spacer())
# 5
e += sec1(5, "Quantify Blood Loss (Approximate)")
e += simple_table(
["Blood Loss (ml)", "Clinical Effect"],
[["< 500", "Usually no symptoms"],
["500 – 1000", "Mild tachycardia"],
["1000 – 1500", "Tachycardia, weakness, postural hypotension"],
["1500 – 2000", "Restlessness, confusion, marked tachycardia, hypotension"],
["> 2000", "Shock, collapse"]],
col_widths=[5*cm, 11*cm]
)
# 6 DD
e += sec1(6, "Differential Diagnosis")
for t in ["Epistaxis / bleeding from mouth (pseudo-hematemesis)",
"Hemoptysis","Bleeding from swallowed blood (after dental extraction)",
"Bleeding diathesis","Lower GI bleeding (if brisk)"]:
e.append(bullet(t))
e.append(spacer())
# 7
e += sec1(7, "Investigations")
e += sec2("A. Routine")
for t in ["CBC (Hb, PCV, TLC, Platelets)","Blood grouping & cross-match",
"Coagulation profile (PT/INR, aPTT)","Serum urea, creatinine, electrolytes",
"LFT (especially in chronic liver disease)"]:
e.append(bullet(t))
e += sec2("B. Specific")
e.append(bullet("Upper GI endoscopy – gold standard (within 12–24 hrs after resuscitation)"))
e.append(bullet("Nasogastric aspiration – in massive bleed (fresh blood / altered blood suggests upper GI source)"))
e.append(bullet("Imaging (if needed) – CT angiography / IR angiography"))
e.append(spacer())
# 8
e += sec1(8, "Risk Stratification")
e += sec2("High-Risk Features")
for t in ["Age > 60 years","Shock at presentation","Comorbid illness (liver disease, cardiac disease)",
"Hemoglobin < 8 g/dL","Ongoing bleeding (hematemesis, tachycardia, hypotension)"]:
e.append(bullet(t))
e += sec2("Low-Risk Features")
for t in ["Stable vitals, Hb > 10 g/dL","No comorbidity","No continuing bleed"]:
e.append(bullet(t))
e.append(spacer())
# 9
e += sec1(9, "Management")
e += sec2("A. Initial Resuscitation (ABC)")
for t in ["Secure IV access (2 large bore)","Resuscitate with IV fluids & blood products",
"Monitor pulse, BP, urine output","Oxygen as needed"]:
e.append(bullet(t))
e += sec2("B. General Measures")
for t in ["Nil by mouth","Insert NG tube (after initial resuscitation)",
"Foley's catheter – monitor urine output",
"Stop NSAIDs, anticoagulants","Maintain Hb > 7–8 g/dL"]:
e.append(bullet(t))
e.append(spacer())
# 10
e += sec1(10, "Definitive Management – According to Cause")
e += simple_table(
["Cause", "Medical / Endoscopic", "Surgical / Radiological"],
[["Peptic ulcer bleeding", "PPI (IV); Endoscopic therapy (adrenaline injection, thermal coagulation, hemoclips)", "Surgery if uncontrolled bleeding / rebeed; Oversew bleeding vessel / IR embolization"],
["Esophageal varices", "Terlipressin / Somatostatin; EVL; Antibiotics", "Balloon tamponade; TIPS / Shunt surgery; Devascularization"],
["Mallory–Weiss tear", "Usually stops spontaneously; Endoscopic therapy if needed", "Surgery rarely needed"],
["Erosive gastritis / oesophagitis", "PPI, sucralfate; Treat underlying cause; Avoid NSAIDs, alcohol", "Surgery rarely needed"],
["Carcinoma", "Palliative measures; Endoscopic stenting (selected)", "Palliative surgery (if resectable)"]],
col_widths=[3.5*cm, 7*cm, 5.5*cm]
)
# 11
e += sec1(11, "Endoscopic Therapeutic Options")
e.append(bullet("Injection therapy – Adrenaline (1:10,000), Sclerosants"))
e.append(bullet("Thermal therapy – Heater probe, Bipolar cautery, Argon plasma coagulation"))
e.append(bullet("Mechanical therapy – Hemoclips, Endoscopic band ligation (varices), Combination therapy"))
e.append(body("<i>Endoscopic therapy is first-line for most non-variceal upper GI bleeds.</i>"))
e.append(spacer())
# 12
e += sec1(12, "Indications for Surgery / IR")
for t in ["Failure of endoscopic therapy","Persistent / recurrent bleeding",
"Hemodynamic instability","Large or deep ulcer with visible vessel",
"Variceal bleed not controlled by medical and endoscopic measures",
"Complications: perforation, gastric outlet obstruction, suspicion of malignancy"]:
e.append(bullet(t))
e.append(spacer())
# difference table
e += sec1(16, "Difference Between Hematemesis and Melena")
e += simple_table(
["Feature", "Hematemesis", "Melena"],
[["Origin", "Upper GI bleeding (proximal to Treitz)", "Upper GI bleeding (usually slow, altered blood)"],
["Appearance", "Bright red / dark / coffee ground", "Black, tarry, foul smelling stool"],
["Onset", "Immediate", "6–8 hours after bleeding"],
["Indicates", "Active or recent bleeding", "Altered blood due to digestion"]],
col_widths=[3.5*cm, 6.5*cm, 6*cm]
)
e += key_points_box([
"Fresh, bright red blood → usually brisk bleeding",
"\"Coffee ground\" vomitus → slower bleeding (stomach)",
"Melena → altered blood (takes 6–8 hrs to appear in stool)",
"Always resuscitate first, then evaluate and treat",
"Early endoscopy (within 12–24 hrs) improves outcome",
])
e += summary_box([
"Hematemesis indicates upper GI bleeding.",
"Initial management is resuscitation (ABC), followed by diagnosis (endoscopy) and treatment.",
"Peptic ulcer and portal hypertension are the most common causes.",
"Early recognition and timely management reduce morbidity and mortality.",
])
e.append(PageBreak())
return e
def page_gastritis():
e = []
e += topic_title("GASTRITIS")
# 1
e += sec1(1, "Definition")
e.append(body("Gastritis is <b>inflammation of the gastric mucosa</b>. It may be acute or chronic and may be superficial or involve the deeper layers."))
e.append(spacer())
# 2
e += sec1(2, "Etiology")
e += sec2("A. Exogenous (Most Common)")
for t in ["Helicobacter pylori infection","NSAIDs / Aspirin","Alcohol","Smoking",
"Bile reflux","Stress (burns, trauma, sepsis)",
"Drugs – Steroids, Potassium chloride, Iron, OCP, etc.",
"Dietary factors – spicy food, very hot food, irregular meals"]:
e.append(bullet(t))
e += sec2("B. Endogenous")
for t in ["Autoimmune","Ischaemia","Chemical irritation (excess acid)",
"Allergic / Hypersensitivity"]:
e.append(bullet(t))
e.append(spacer())
# 3
e += sec1(3, "Pathophysiology")
for t in ["Aggressive factors (acid, pepsin, H. pylori, drugs, bile) overcome mucosal defence",
"Mucosal injury → inflammation → impaired barrier → further injury",
"Acute inflammation: neutrophils predominate",
"Chronic inflammation: lymphocytes, plasma cells predominate → atrophy, intestinal metaplasia, dysplasia (premalignant)"]:
e.append(bullet(t))
e += sec2("Aggressive vs Defensive Factors")
e += simple_table(
["Aggressive Factors", "Defensive Factors"],
[["Acid, Pepsin, H. pylori, NSAIDs, Alcohol, Bile, Smoking, Stress",
"Mucus-bicarbonate, Epithelial barrier, Prostaglandins, Adequate blood supply, Cell renewal, IgA"]],
col_widths=[8*cm, 8*cm]
)
e.append(body("<b>Imbalance → Gastritis</b>"))
e.append(spacer())
# 4
e += sec1(4, "Classification")
e += sec2("A. Acute Gastritis (Reversible)")
for t in ["Sudden onset, short duration","Mucosal oedema, congestion, haemorrhage",
"Causes: excess alcohol, drugs, corrosives, stress, severe infection"]:
e.append(bullet(t))
e += sec2("B. Chronic Gastritis (Persistent)")
for t in ["Long standing; may be superficial or atrophic",
"Predisposes to peptic ulcer and carcinoma"]:
e.append(bullet(t))
e += simple_table(
["Type", "Features", "Associations"],
[["Non-atrophic (Antral)", "Inflammation in antrum ± corpus", "H. pylori infection, peptic ulcer"],
["Atrophic (Corpus)", "Loss of glands, atrophy, intestinal metaplasia", "Autoimmune gastritis, pernicious anaemia, carcinoma"],
["Special forms", "Granulomatous, eosinophilic, lymphocytic, chemical (reactive)", "Crohn's TB, allergy, bile reflux, chemical irritants"]],
col_widths=[4*cm, 6.5*cm, 5.5*cm]
)
e.append(spacer())
# 5
e += sec1(5, "Clinical Features")
for t in ["Epigastric pain / discomfort – dull, burning","Fullness, early satiety",
"Nausea, occasional vomiting","Belching, bloating, flatulence",
"Anorexia, weight loss (chronic)",
"Haematemesis / melaena (if erosions/ulcers)",
"Often asymptomatic (chronic superficial gastritis)"]:
e.append(bullet(t))
e.append(spacer())
# 7
e += sec1(7, "Investigations")
e += sec2("A. Routine")
for t in ["CBC","ESR","Serum electrolytes","LFT","Stool routine & occult blood","Urea / Creatinine"]:
e.append(bullet(t))
e += sec2("B. Specific")
e.append(bullet("H. pylori detection – Urea breath test, Stool antigen test, Serology (IgG), Biopsy (rapid urease test, histology)"))
e.append(bullet("Endoscopy with biopsy – gold standard"))
e.append(bullet("Gastric juice analysis (rarely required)"))
e.append(spacer())
# 8
e += sec1(8, "Histopathology")
e += sec2("A. Acute Gastritis")
for t in ["Oedema","Congestion","Neutrophilic infiltration","Erosions / haemorrhage"]:
e.append(bullet(t))
e += sec2("B. Chronic Gastritis")
for t in ["Mononuclear cell infiltrate (lymphocytes, plasma cells)","Glandular atrophy",
"Intestinal metaplasia","Dysplasia (in advanced cases)"]:
e.append(bullet(t))
e.append(spacer())
# 9
e += sec1(9, "Management")
e += sec2("A. General Measures")
for t in ["Avoid smoking, alcohol","Small, frequent meals",
"Avoid spicy, irritant food","Stress relief"]:
e.append(bullet(t))
e += sec2("B. Medical Management")
e.append(bullet("1. H. pylori eradication (if present) – Triple therapy (14 days): PPI + Clarithromycin + Amoxicillin (or Metronidazole)"))
e.append(bullet("2. Acid suppression – PPIs (Omeprazole, Pantoprazole, Esomeprazole), H2 receptor blockers (Ranitidine, Famotidine), Antacids, Prostaglandin analogues (Misoprostol)"))
e.append(bullet("3. Remove offending agent – Stop NSAIDs, alcohol, smoking, irritant drugs"))
e.append(bullet("4. Treat associated conditions (bile reflux, stress, systemic diseases)"))
e.append(bullet("5. Nutritional support"))
e.append(spacer())
# 10
e += sec1(10, "Indications for Surgery")
for t in ["Perforation","Uncontrolled haemorrhage",
"Gastric outlet obstruction due to chronic scarring",
"Suspicion / presence of malignancy",
"Failure of medical therapy in complicated disease"]:
e.append(bullet(t))
e.append(spacer())
# 11
e += sec1(11, "Complications")
for t in ["Peptic ulcer","Gastrointestinal bleeding","Perforation",
"Gastric outlet obstruction","Atrophic gastritis → pernicious anaemia",
"Intestinal metaplasia → dysplasia → carcinoma stomach"]:
e.append(bullet(t))
e.append(spacer())
# 13
e += sec1(13, "Gastritis and Carcinoma Sequence")
e.append(body("Chronic inflammation (e.g., H. pylori) → Atrophic gastritis → Intestinal metaplasia → Dysplasia → <b>Carcinoma</b>"))
e.append(body("<i>Risk increases with duration and severity of chronic gastritis.</i>"))
e.append(spacer())
e += key_points_box([
"Most common cause: H. pylori infection",
"Treat the cause + suppress acid",
"Atrophic gastritis is a premalignant condition",
"Endoscopy with biopsy is gold standard for diagnosis",
"Early diagnosis and correct management prevent complications",
])
e += summary_box([
"Gastritis is inflammation of gastric mucosa due to imbalance between aggressive and defensive factors.",
"It may be acute or chronic; causes include H. pylori, NSAIDs, alcohol, stress, bile reflux.",
"Diagnosis is by endoscopy with biopsy.",
"Management involves eradication of cause, acid suppression, and supportive care.",
"Chronic atrophic gastritis has malignant potential.",
])
e.append(PageBreak())
return e
def page_ulcerative_colitis():
e = []
e += topic_title("ULCERATIVE COLITIS")
# 1
e += sec1(1, "Definition")
e.append(body("Ulcerative colitis (UC) is a <b>chronic inflammatory disease of colon and rectum</b> of unknown etiology, limited to mucosa and submucosa, starting from rectum and extending proximally in a <b>continuous</b> manner."))
e.append(spacer())
# 2
e += sec1(2, "Etiology")
for t in ["Exact cause unknown","Genetic predisposition","Immune dysregulation",
"Environmental factors","Altered gut flora"]:
e.append(bullet(t))
e.append(spacer())
# 3
e += sec1(3, "Pathophysiology")
for t in ["Immune-mediated inflammation of mucosa",
"Starts in rectum → continuous spread proximally",
"Ulceration confined to mucosa & submucosa",
"Loss of absorptive surface → diarrhea, blood & mucus",
"Chronic inflammation → fibrosis, strictures, dysplasia, carcinoma"]:
e.append(bullet(t))
e.append(spacer())
# 4
e += sec1(4, "Clinical Features")
e += sec2("A. Symptoms")
for t in ["Bloody diarrhea (most common)","Mucus in stools","Tenesmus",
"Lower abdominal pain","Bloating, Urgency",
"Fever (in severe attack)","Weight loss, anorexia, fatigue"]:
e.append(bullet(t))
e += sec2("B. Signs")
for t in ["Pallor","Dehydration","Abdominal tenderness (left iliac fossa)",
"Distended abdomen (toxic megacolon)","Perianal disease (skin tags, fissure, fistula)",
"Extraintestinal manifestations may be present"]:
e.append(bullet(t))
e.append(spacer())
# 5
e += sec1(5, "Extent – Montreal Classification")
e += simple_table(
["Class", "Name", "Extent"],
[["E1", "Proctitis", "Limited to rectum"],
["E2", "Left-sided colitis", "Up to splenic flexure"],
["E3", "Extensive colitis", "Beyond splenic flexure"],
["E4", "Pancolitis", "Entire colon"]],
col_widths=[2*cm, 5*cm, 9*cm]
)
e.append(body("<b>Rectum is always involved.</b>"))
e.append(spacer())
# 6
e += sec1(6, "Investigations")
e += sec2("A. Routine")
for t in ["CBC – anaemia","ESR, CRP – raised in activity","Serum electrolytes",
"LFT","Stool routine & microscopy","Stool culture (to rule out infection)"]:
e.append(bullet(t))
e += sec2("B. Specific")
for t in ["Colonoscopy with biopsy – gold standard: continuous mucosal inflammation, loss of vascular pattern, ulcers, friability, contact bleeding",
"Histopathology – crypt abscesses, crypt distortion, mucosal ulceration"]:
e.append(bullet(t))
e.append(spacer())
# 8
e += sec1(8, "Complications")
for t in ["Toxic megacolon","Massive hemorrhage","Perforation","Strictures",
"Colorectal carcinoma (risk increases with duration & extent)",
"Extraintestinal: arthritis, uveitis, erythema nodosum, PSC, thrombophlebitis"]:
e.append(bullet(t))
e.append(spacer())
# 9
e += sec1(9, "Management")
e += sec2("A. Medical Management")
e.append(bullet("1. Mild to Moderate Disease – 5-ASA (Mesalamine): oral + topical (enema/suppository); Topical steroids (budesonide enema)"))
e.append(bullet("2. Moderate to Severe Disease – Systemic corticosteroids (Prednisolone); Immunomodulators: Azathioprine / 6-MP; Biologics: Anti-TNF (Infliximab, Adalimumab), Vedolizumab, Ustekinumab"))
e.append(bullet("3. Acute Severe Colitis – IV steroids (Hydrocortisone); Close monitoring; Rescue therapy: Cyclosporine / Infliximab"))
e.append(bullet("4. Supportive Care – Fluid & electrolyte correction; Nutritional support; Treat anaemia"))
e += sec2("B. Indications for Surgery")
for t in ["Failure of medical therapy","Toxic megacolon",
"Massive uncontrolled hemorrhage","Perforation",
"Dysplasia / carcinoma","Stricture causing obstruction",
"Recurrent severe attacks affecting quality of life"]:
e.append(bullet(t))
e += sec2("C. Surgical Options")
e.append(bullet("Emergency – Subtotal colectomy with end ileostomy and mucous fistula"))
e.append(bullet("Elective (Definitive) – Total proctocolectomy with ileal pouch-anal anastomosis (IPAA – J pouch); Total colectomy with ileorectal anastomosis (in selected cases); Restorative proctocolectomy (3-stage IPAA)"))
e.append(spacer())
# 10
e += sec1(10, "Extraintestinal Manifestations")
for t in ["Musculoskeletal: Peripheral arthritis, ankylosing spondylitis",
"Ocular: Uveitis, episcleritis",
"Skin: Erythema nodosum, pyoderma gangrenosum",
"Hepatobiliary: Primary sclerosing cholangitis",
"Hematological: Iron deficiency anaemia",
"Others: Aphthous ulcers, venous thromboembolism"]:
e.append(bullet(t))
e.append(spacer())
# 12 UC vs CD
e += sec1(12, "Ulcerative Colitis vs Crohn's Disease")
e += simple_table(
["Feature", "Ulcerative Colitis", "Crohn's Disease"],
[["Site", "Rectum always involved, continuous", "Any part, skip lesions"],
["Distribution", "Continuous", "Discontinuous"],
["Depth", "Mucosa & submucosa only", "Transmural"],
["Skip areas", "Absent", "Present"],
["Fissures / Fistula", "Absent", "Common"],
["Strictures", "Rare", "Common"],
["Granulomas", "Absent", "May be present"],
["Perianal disease", "Rare", "Common"],
["Cancer risk", "Increased (with duration & extent)", "Less (except colonic involvement)"]],
col_widths=[4.5*cm, 6*cm, 5.5*cm]
)
e += key_points_box([
"UC always involves rectum",
"Continuous spread proximally",
"Bloody diarrhea + mucus + tenesmus are hallmark",
"Diagnosis – Colonoscopy with biopsy",
"Treat early and adequately; watch for complications",
"Long-standing extensive disease → carcinoma risk",
])
e += summary_box([
"Ulcerative colitis is a chronic inflammatory disease of colon & rectum, starting from rectum and extending in a continuous manner.",
"Presents with bloody diarrhea, mucus, tenesmus and lower abdominal pain.",
"Diagnosis is by colonoscopy with biopsy.",
"Medical treatment is mainstay; surgery is indicated for complications or failure.",
"Long-standing disease increases risk of colorectal carcinoma.",
])
e.append(PageBreak())
return e
def page_gastric_carcinoma():
e = []
e += topic_title("GASTRIC CARCINOMA")
e += sec1(1, "Definition")
e.append(body("Malignant epithelial neoplasm arising from the lining epithelium of stomach. <b>Most common malignancy of stomach and 3rd leading cause of cancer death worldwide.</b>"))
e.append(spacer())
# 2
e += sec1(2, "Etiology & Risk Factors")
for t in ["Helicobacter pylori infection (chronic atrophic gastritis)",
"Diet: high salt, smoked, pickled food; low fruits & vegetables (↓ Vit C)",
"Smoking, alcohol","Pernicious anemia","Adenomatous polyps",
"Menetrier disease","Familial (CDH1 gene mutation – gareditic cancer)",
"Previous partial gastrectomy","Blood group A"]:
e.append(bullet(t))
e.append(spacer())
# 3
e += sec1(3, "Pathogenesis – Correa's Cascade")
e.append(body("Chronic non-atrophic gastritis → Chronic atrophic gastritis → Intestinal metaplasia → Dysplasia → <b>Adenocarcinoma</b>"))
e.append(body("<i>Sequence takes years to decades. H. pylori is the key initiator.</i>"))
e.append(spacer())
# 4
e += sec1(4, "Classification (WHO)")
e += simple_table(
["Type", "Examples"],
[["Adenocarcinoma", "Tubular, Papillary, Mucinous, Signet ring cell (diffuse), Mixed"],
["Other epithelial tumours", "Squamous cell carcinoma, Adenosquamous carcinoma"],
["Neuroendocrine tumours", "Carcinoid tumour, Neuroendocrine carcinoma"],
["Others", "Lymphoma, GIST, Metastatic tumours"]],
col_widths=[5*cm, 11*cm]
)
e.append(spacer())
# 5
e += sec1(5, "Pathophysiology")
for t in ["Proximal bowel dilatation (due to obstruction)","Fluid & electrolyte loss",
"Bacterial overgrowth","Increased intraluminal pressure",
"Venous congestion → ischemia → gangrene → perforation"]:
e.append(bullet(t))
e.append(spacer())
# 6
e += sec1(6, "Clinical Features")
e.append(bullet("<b>Early</b> – usually asymptomatic or dyspepsia, epigastric discomfort"))
e.append(bullet("<b>Advanced</b> – anorexia, weight loss, vomiting, haematemesis, melena, anaemia, palpable mass"))
e.append(bullet("<b>Linitis plastica</b> – rigid, thickened stomach; leather bottle appearance"))
e.append(spacer())
# 7
e += sec1(7, "Spread")
for t in ["Direct invasion – into deeper layers, serosa, adjacent organs (pancreas, spleen, transverse colon, liver)",
"Lymphatic spread – to perigastric nodes → celiac, superior mesenteric nodes",
"Hematogenous spread – liver (most common), lungs, bone, brain, peritoneum",
"Transcoelomic spread – peritoneal carcinomatosis"]:
e.append(bullet(t))
e.append(spacer())
# 8
e += sec1(8, "Investigations")
e += sec2("A. Blood Tests")
for t in ["CBC","Electrolytes (Na⁺, K⁺, Cl⁻)","Urea / Creatinine","Serum lactate"]:
e.append(bullet(t))
e += sec2("B. Imaging")
e.append(bullet("X-ray abdomen erect – multiple air-fluid levels, dilated bowel loops, step ladder pattern"))
e.append(bullet("<b>CT scan abdomen – best investigation</b> for site, cause, staging"))
e.append(spacer())
# 9
e += sec1(9, "Diagnosis")
for t in ["Upper GI endoscopy with biopsy – gold standard",
"Radiology (UGI series, CECT) – for extent and metastasis",
"Endoscopic ultrasound – depth of invasion",
"Tumour markers: CEA, CA 19-9 (not specific)"]:
e.append(bullet(t))
e.append(spacer())
# 10
e += sec1(10, "Prognosis")
for t in ["Depends on stage at diagnosis, histologic type and depth of invasion",
"Intestinal type – better prognosis","Diffuse type – poor prognosis",
"5-year survival: Early (confined to mucosa/submucosa) 70–90%; Advanced (serosa/lymph node/metastasis) < 20%"]:
e.append(bullet(t))
e.append(spacer())
# 11
e += sec1(11, "Management")
e += sec2("A. Initial Management – \"DRIP & SUCK\"")
for t in ["Nil by mouth","IV fluids","Electrolyte correction",
"NG tube decompression","Foley's catheter",
"Broad spectrum antibiotics if strangulation suspected"]:
e.append(bullet(t))
e += sec2("B. Conservative Treatment – Indicated In")
for t in ["Partial obstruction","Adhesive obstruction","No signs of strangulation or peritonitis"]:
e.append(bullet(t))
e += sec2("C. Indications for Surgery")
for t in ["Strangulation","Peritonitis","Complete obstruction",
"Failed conservative treatment","Perforation"]:
e.append(bullet(t))
e += sec2("D. Operations (As per cause)")
for t in ["Adhesiolysis","Hernia repair","Resection & anastomosis",
"Stoma formation","Volvulus correction"]:
e.append(bullet(t))
e.append(spacer())
# 12
e += sec1(12, "Gross & Microscopic Features")
e += sec2("A. Gross")
for t in ["Polypoid / Ulcerative / Infiltrative (linitis plastica) growth patterns",
"Common sites: pyloric antrum > lesser curvature > cardia > body"]:
e.append(bullet(t))
e += sec2("B. Microscopic")
e.append(bullet("Intestinal type – well formed glands with desmoplastic stroma"))
e.append(bullet("Diffuse type (Signet ring cells) – discohesive signet ring cells infiltrating the stroma"))
e.append(spacer())
e += key_points_box([
"Most gastric carcinomas are adenocarcinomas",
"Correa's cascade explains multistep carcinogenesis",
"Intestinal type – gland forming, better prognosis",
"Diffuse type – signet ring cells, linitis plastica, poor prognosis",
"Early detection improves outcome",
])
e += summary_box([
"Early diagnosis + resuscitation + timely surgery reduces morbidity and mortality.",
"Always look for signs of strangulation: fever, tachycardia, continuous pain, tenderness, guarding, leukocytosis, metabolic acidosis.",
])
e.append(PageBreak())
return e
def page_peptic_ulcer():
e = []
e += topic_title("PEPTIC ULCER")
# 1
e += sec1(1, "Definition")
e.append(body("Peptic ulcer is a <b>break in the continuity of the mucosa</b> of the stomach or duodenum (proximal to the ligament of Treitz) produced by acid pepsin digestion."))
e.append(spacer())
# 2
e += sec1(2, "Etiology")
for t in ["Helicobacter pylori infection (most common)","NSAIDs / Aspirin",
"Smoking","Alcohol","Stress (burns, head injury, sepsis)",
"Hyperacidity states – Zollinger Ellison syndrome",
"Genetic factors (blood group O)","Dietary factors – spicy food, irregular meals"]:
e.append(bullet(t))
e.append(spacer())
# 3
e += sec1(3, "Pathogenesis")
e.append(body("<b>Aggressive factors</b>: Acid, Pepsin, H. pylori, NSAIDs, Smoking, Alcohol, Bile salts"))
e.append(body("<b>Defensive factors</b>: Mucus-bicarbonate barrier, Prostaglandins, Good blood supply, Epithelial restitution"))
e.append(body("<b>Imbalance → Mucosal injury → Ulcer</b>"))
e.append(spacer())
# 4
e += sec1(4, "Classification")
e += sec2("A. Anatomical")
e += simple_table(
["Gastric Ulcer", "Duodenal Ulcer"],
[["Occurs on lesser curvature (80–90%); Also on greater curvature, anterior/posterior wall (30%); Usually solitary",
"Usually in first part (90–95%); Anterior wall (60%) > posterior wall (30%); Usually solitary"]],
col_widths=[8*cm, 8*cm]
)
e += sec2("B. Clinical")
for t in ["Acute ulcer","Chronic ulcer","Recurrent ulcer","Complicated ulcer"]:
e.append(bullet(t))
e.append(spacer())
# 5
e += sec1(5, "Clinical Features")
e += sec2("A. Duodenal Ulcer")
for t in ["Pain in epigastrium","Periodicity – related to meals (hunger pain, relieved by food or antacids)",
"Pain at night","Relieved by vomiting / food",
"No loss of weight","Appetite normal / increased"]:
e.append(bullet(t))
e += sec2("B. Gastric Ulcer")
for t in ["Pain in epigastrium soon after food","Aggravated by food",
"Not relieved by vomiting","Loss of appetite",
"Loss of weight","Nausea, early satiety"]:
e.append(bullet(t))
e.append(body("<b>Common symptoms:</b> Heartburn, belching, bloating"))
e.append(spacer())
# 6
e += sec1(6, "Complications")
for t in ["Hemorrhage – Melaena / haematemesis",
"Perforation – Sudden severe pain, rigid abdomen",
"Penetration – Into pancreas (common)",
"Obstruction – Pyloric/duodenal obstruction",
"Malignant change – Gastric ulcer (rare)",
"Others: Fistula, Adhesions, Recurrent ulcer"]:
e.append(bullet(t))
e.append(spacer())
# 7
e += sec1(7, "Investigations")
e += sec2("A. Routine")
for t in ["Hb%, TLC","Stool occult blood","Urea, Creatinine","Blood group"]:
e.append(bullet(t))
e += sec2("B. Specific")
e.append(bullet("Upper GI endoscopy – gold standard (Diagnosis, defines site/number/size, biopsy gastric ulcer to rule out malignancy)"))
e.append(bullet("Rapid urease test / H. pylori testing"))
e.append(bullet("Barium contrast study – if endoscopy not available or in obstruction"))
e += sec2("C. Others (If Indicated)")
for t in ["Gastric acid analysis","Serum gastrin (Zollinger Ellison syndrome)"]:
e.append(bullet(t))
e.append(spacer())
# 8
e += sec1(8, "Differential Diagnosis")
for t in ["Gastritis","Carcinoma stomach","Pancreatitis","Biliary colic",
"Cardiac ischemia","Functional dyspepsia"]:
e.append(bullet(t))
e.append(spacer())
# 9
e += sec1(9, "Management")
e += sec2("A. General Measures")
for t in ["Regular small meals","Stop smoking","Avoid alcohol",
"Avoid NSAIDs (if possible)","Adequate rest"]:
e.append(bullet(t))
e += sec2("B. Medical Management")
e.append(bullet("I. H. pylori eradication (if present) – Triple therapy (14 days): PPI + Clarithromycin + Amoxicillin (or Metronidazole)"))
e.append(bullet("II. Acid suppression – Proton pump inhibitors (e.g., Omeprazole, Pantoprazole); H₂ receptor blockers – Ranitidine, Famotidine"))
e.append(bullet("III. Mucosal protective agents – Sucralfate, Bismuth compounds"))
e.append(bullet("IV. Antacids (for symptomatic relief) – Aluminium hydroxide, Magnesium hydroxide, Combination preparations"))
e += sec2("C. Indications for Surgery")
for t in ["Perforation","Uncontrolled hemorrhage","Gastric outlet obstruction",
"Penetration","Suspicion of malignancy","Refractory / recurrent ulcer"]:
e.append(bullet(t))
e += sec2("D. Surgical Options")
for t in ["Highly selective vagotomy (HSV) + Drainage",
"Proximal gastric vagotomy (PGV) + Drainage",
"Truncal vagotomy + Drainage",
"Antrectomy + Reconstruction (for gastric ulcer)",
"Simple closure with omental patch (for perforation)",
"Definitive surgery in emergency (rare)"]:
e.append(bullet(t))
e.append(spacer())
# 10 GU vs DU
e += sec1(10, "Gastric vs Duodenal Ulcer – Comparison")
e += simple_table(
["Feature", "Gastric Ulcer", "Duodenal Ulcer"],
[["Age", "> 40 years", "20–50 years"],
["Sex", "M = F", "M : F = 4 : 1"],
["Site", "Lesser curvature (common)", "First part of duodenum (common)"],
["Relation to meals", "Pain after meals", "Pain when hungry; relieved by food"],
["Pain at night", "Less common", "Common"],
["Vomiting", "Relieves pain", "Relieves pain"],
["Appetite", "Decreased", "Normal / Increased"],
["Weight", "Loss", "Normal / Gain"],
["Malignancy risk", "Present (5–10%)", "Nil"],
["Complications", "Bleed, perforate, obstruct, malignant change", "Bleed, perforate, penetrate, obstruct"]],
col_widths=[4*cm, 6*cm, 6*cm]
)
e.append(spacer())
# 12
e += sec1(12, "Perforated Peptic Ulcer – Overview")
e += sec2("Features")
for t in ["Sudden severe epigastric pain","Board-like rigidity",
"Absent liver dullness","X-ray erect abdomen – free gas under diaphragm"]:
e.append(bullet(t))
e += sec2("Management")
for t in ["Resuscitation – IV fluids, NG tube, catheter, correction of electrolytes",
"Broad spectrum antibiotics",
"Emergency surgery – simple closure with omental (Graham) patch"]:
e.append(bullet(t))
e.append(spacer())
e += key_points_box([
"Duodenal ulcer – pain related to meals, no loss of weight",
"Gastric ulcer – pain after meals, loss of weight, malignancy risk present",
"H. pylori – most common cause",
"Endoscopy – gold standard for diagnosis",
"Perforation – medical emergency",
])
e += summary_box([
"Peptic ulcer disease is a common disorder due to imbalance between aggressive and defensive factors.",
"H. pylori and NSAIDs are the most important causes.",
"Clinical pattern helps in differentiation of gastric and duodenal ulcers.",
"Complications can be serious; early diagnosis and appropriate management prevent morbidity and mortality.",
])
e.append(PageBreak())
return e
def page_goo():
e = []
e += topic_title("GASTRIC OUTLET OBSTRUCTION (GOO)")
# 1
e += sec1(1, "Definition")
e.append(body("GOO is a condition in which there is <b>partial or complete obstruction to the emptying of gastric contents into the duodenum</b>."))
e.append(spacer())
# 2
e += sec1(2, "Etiology")
e += sec2("A. Benign (Most Common)")
for t in ["Peptic ulcer disease (chronic duodenal ulcer) – most common",
"Pyloric stenosis (infant, hypertrophic)","Caustic strictures",
"Crohn's disease","Tuberculosis","Chronic pancreatitis",
"Post-surgical (anastomotic stricture)","Bezoar, gall stone (Bouveret syndrome)"]:
e.append(bullet(t))
e += sec2("B. Malignant")
for t in ["Carcinoma stomach (pyloric part)","Carcinoma pancreas (head)",
"Carcinoma duodenum","Lymphoma"]:
e.append(bullet(t))
e.append(spacer())
# 3
e += sec1(3, "Pathophysiology")
for t in ["Obstruction at gastric outlet → retention of food, fluid and secretions in stomach",
"Increased intragastric pressure → dilatation of stomach",
"Loss of HCl, K⁺ and water in vomitus → dehydration, metabolic alkalosis, hypokalaemia, hypochloraemia",
"Weight loss, malnutrition",
"Hyperperistalsis initially → visible peristalsis",
"Later → atonic dilatation"]:
e.append(bullet(t))
e.append(spacer())
# 4
e += sec1(4, "Clinical Features")
for t in ["Upper abdominal fullness","Postprandial fullness and discomfort",
"Early satiety",
"Nausea and non-bilious vomiting (of food taken hours or previous day) – relieves symptoms temporarily",
"Visible peristalsis (left hypochondrium)",
"Succussion splash (3–4 hrs after meal)","Dehydration, lethargy","Weight loss"]:
e.append(bullet(t))
e.append(spacer())
# 5
e += sec1(5, "Classification")
e.append(bullet("Based on degree: Partial (some passage) / Complete (no passage)"))
e.append(bullet("Based on duration: Acute (< 1 week) / Chronic (> 1 week)"))
e.append(bullet("Based on cause: Benign / Malignant"))
e.append(spacer())
# 6
e += sec1(6, "Investigations")
e += sec2("A. Routine")
for t in ["Hb%, TLC","Serum electrolytes (↓ K⁺, ↓ Cl⁻)","Urea, Creatinine",
"Blood group","ECG (if elderly)"]:
e.append(bullet(t))
e += sec2("B. Imaging")
e.append(bullet("X-ray abdomen (erect) – dilated stomach with multiple air-fluid levels; scanty/absent gas in distal bowel"))
e.append(bullet("Upper GI endoscopy – to detect site and cause of obstruction & biopsy if needed"))
e.append(bullet("CECT / USG abdomen – to assess cause, extent and resectability (in malignant cases)"))
e.append(spacer())
# 7
e += sec1(7, "Differential Diagnosis")
for t in ["Gastroparesis","Functional dyspepsia","Chronic pancreatitis",
"Superior mesenteric artery syndrome","Carcinoma stomach / pancreas",
"Pseudocyst of pancreas","Chronic intestinal obstruction"]:
e.append(bullet(t))
e.append(spacer())
# 8
e += sec1(8, "Clinical Signs")
e += simple_table(
["Sign", "Finding"],
[["Visible peristalsis", "Waves seen in left hypochondrium"],
["Succussion splash", "Splashing sound heard 3–4 hrs after a meal"],
["Dehydration", "Dry tongue, poor skin turgor, hypotension"],
["Nutritional deficiency", "Weight loss, anaemia, weakness"],
["Metabolic alkalosis", "Due to loss of HCl in vomitus"]],
col_widths=[5*cm, 11*cm]
)
e.append(spacer())
# 9
e += sec1(9, "Management")
e += sec2("A. Initial / Conservative Management (Stabilization)")
for t in ["Nil by mouth","NG tube aspiration","IV fluids (RL / NS)",
"Correct electrolyte imbalance (↓ K⁺, ↓ Cl⁻)","PPI (Omeprazole)",
"Antiemetics (if needed)"]:
e.append(bullet(t))
e += sec2("B. Definitive Management – Depends on Cause")
e += sec2("Benign causes")
for t in ["Treat underlying cause",
"PUD: PPI + H. pylori eradication",
"Caustic stricture: dilation",
"Pyloric stenosis: surgery (Heineke-Mikulicz pyloroplasty)",
"Bezoar / gall stone: endoscopic / surgical removal",
"Tuberculosis: ATT"]:
e.append(bullet(t, sub=True))
e += sec2("Malignant causes")
for t in ["Resectable – curative surgery (distal gastrectomy / pancreatoduodenectomy)",
"Unresectable – palliative bypass surgery (gastrojejunostomy) / stenting"]:
e.append(bullet(t, sub=True))
e += sec2("C. Surgical Options")
for t in ["Gastrojejunostomy (most common palliative procedure)",
"Vagotomy with drainage (rarely needed now)",
"Pyloroplasty (for benign obstruction, good gastric motility)",
"Resection (for resectable malignancy)",
"Endoscopic stenting (selected malignant cases)"]:
e.append(bullet(t))
e.append(spacer())
# 10
e += sec1(10, "Complications")
for t in ["Severe dehydration","Hypokalaemic, hypochloraemic metabolic alkalosis",
"Aspiration pneumonia","Mallory–Weiss tear",
"Perforation (in peptic ulcer)","Malnutrition",
"Carcinoma (in chronic PUD)"]:
e.append(bullet(t))
e.append(spacer())
# 12 benign vs malignant
e += sec1(12, "Benign vs Malignant GOO")
e += simple_table(
["Feature", "Benign GOO", "Malignant GOO"],
[["Onset", "Insidious, long duration", "Relatively rapid"],
["Pain", "Common (e.g., PUD)", "Less common"],
["Vomiting", "Relieves symptoms", "Relieves partially"],
["Weight loss", "Mild / due to vomiting", "Marked"],
["Age", "Young / middle aged", "Older (> 40 years)"],
["Endoscopy", "Inflammatory / scar", "Growth / ulceroproliferative lesion"],
["Prognosis", "Good (treatable)", "Depends on stage"]],
col_widths=[4*cm, 6*cm, 6*cm]
)
e.append(spacer())
e += key_points_box([
"Most common cause of GOO is chronic duodenal ulcer",
"Non-bilious vomiting + succussion splash are classic features",
"Loss of HCl → metabolic alkalosis, hypokalaemia",
"Gastrojejunostomy is the most common palliative surgery",
"Always search for underlying malignancy in elderly",
])
e += summary_box([
"GOO is obstruction to gastric emptying at the level of pylorus/duodenum.",
"Causes are broadly benign (more common) and malignant.",
"Management includes stabilization, treating the cause and surgery when indicated.",
])
e.append(PageBreak())
return e
# ════════════════════════════════════════════════════════════════════════════
# BUILD PDF
# ════════════════════════════════════════════════════════════════════════════
def build_pdf(output_path):
doc = SimpleDocTemplate(
output_path,
pagesize=A4,
topMargin=1.8*cm, bottomMargin=1.8*cm,
leftMargin=2*cm, rightMargin=2*cm,
title="Surgery One Page Notes – Simplified",
author="Orris AI",
)
story = []
# Cover page
story.append(Spacer(1, 3*cm))
story.append(Paragraph("SURGERY NOTES", styles["DocTitle"]))
story.append(Paragraph("Simplified & Structured Edition", styles["DocSubtitle"]))
story.append(Spacer(1, 0.5*cm))
story.append(HRFlowable(width="100%", thickness=3, color=C_RULE))
story.append(Spacer(1, 0.4*cm))
topics = [
"1. Crohn Disease",
"2. Intestinal Obstruction",
"3. Appendicitis",
"4. Hematemesis",
"5. Gastritis",
"6. Ulcerative Colitis",
"7. Gastric Carcinoma",
"8. Peptic Ulcer",
"9. Gastric Outlet Obstruction (GOO)",
]
story.append(Paragraph("<b>Contents</b>", styles["Sec2"]))
for t in topics:
story.append(Paragraph(t, styles["Bullet"]))
story.append(Spacer(1, 0.5*cm))
story.append(Paragraph("<i>Based on: S. Das & Manipal Manual of Surgery</i>", styles["CaptionStyle"]))
story.append(PageBreak())
# Pages
story += page_crohn()
story += page_intestinal_obstruction()
story += page_appendicitis()
story += page_hematemesis()
story += page_gastritis()
story += page_ulcerative_colitis()
story += page_gastric_carcinoma()
story += page_peptic_ulcer()
story += page_goo()
doc.build(story)
print(f"PDF saved to: {output_path}")
build_pdf("/home/daytona/workspace/surgery-notes/Surgery_Notes_Simplified.pdf")