Skip to content

Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.

fix: add pdfminer fallback for PDF page counts (#197)

Francis Reiner Maia Martinsbe452a940f6f
diff --git a/book_to_skill/parsers/pdf.py b/book_to_skill/parsers/pdf.py
index 242b4bc..4c1c5b7 100644
--- a/book_to_skill/parsers/pdf.py
+++ b/book_to_skill/parsers/pdf.py
@@ -169,22 +169,43 @@ def extract_with_docling(pdf_path: str) -> str | None:
def count_pages(pdf_path: str) -> int:
- # Try pdfinfo first
+ """Return the number of pages in a PDF using progressively safer fallbacks."""
+ # Try pdfinfo first.
if shutil.which("pdfinfo"):
try:
pdf_path = os.path.abspath(pdf_path)
result = subprocess.run(
- ["pdfinfo", pdf_path], capture_output=True, text=True, timeout=15
+ ["pdfinfo", pdf_path],
+ capture_output=True,
+ text=True,
+ timeout=15,
)
for line in result.stdout.splitlines():
if line.startswith("Pages:"):
return int(line.split(":")[1].strip())
except Exception:
pass
- # Fallback: count pages with pypdf
+
+ # Fallback: count pages with pypdf.
try:
import pypdf
+
with open(pdf_path, "rb") as f:
return len(pypdf.PdfReader(f).pages)
except Exception:
- return 0
+ pass
+
+ # Final fallback: pdfminer.extract_text() preserves page boundaries
+ # using form-feed characters, so the number of pages can be derived
+ # without requiring a separate PDF page-counting dependency.
+ try:
+ from pdfminer.high_level import extract_text
+
+ text = extract_text(pdf_path)
+ if text:
+ return text.count("\f") + (0 if text.endswith("\f") else 1)
+ except Exception:
+ # All page-counting methods are best-effort; preserve the historical 0 result.
+ pass
+
+ return 0
diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.py
index 35d3455..08fd28b 100644
--- a/tests/test_book_to_skill.py
+++ b/tests/test_book_to_skill.py
@@ -1817,6 +1817,30 @@ class TestPdftotextEncoding:
assert captured.get("errors") == "replace"
+class TestPdfPageCount:
+ """Tests for PDF page-count fallback behavior."""
+
+ def test_count_pages_uses_pdfminer_when_pdfinfo_and_pypdf_are_unavailable(
+ self, monkeypatch
+ ):
+ """Use pdfminer as the final fallback when other page counters are unavailable."""
+ fake_pdf = "fake.pdf"
+
+ monkeypatch.setattr(pdf_parser.shutil, "which", lambda _: None)
+
+ high_level = mock.MagicMock()
+ high_level.extract_text.return_value = (
+ "page one\fpage two\fpage three"
+ )
+
+ pdfminer = mock.MagicMock()
+ pdfminer.high_level = high_level
+
+ monkeypatch.setitem(sys.modules, "pdfminer", pdfminer)
+ monkeypatch.setitem(sys.modules, "pdfminer.high_level", high_level)
+
+ assert pdf_parser.count_pages(fake_pdf) == 3
+
class TestLooksImageOnly:
"""Scanned PDFs are caught by probing the first pages, before the chain runs."""