{"data":{"slug":"github-opensensenova-sensenova-skills-skills-sn-da-non-spreadsheet-analysis-capability-pdf-analysis-bcbecdee9c1c","title":"PDF Content Extraction and Analysis","summary":"Extract and analyze text, tables, and scanned content from PDFs with accurate parsing and OCR.","url":"https:\/\/skillshunter.net\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-non-spreadsheet-analysis-capability-pdf-analysis-bcbecdee9c1c","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-non-spreadsheet-analysis-capability-pdf-analysis-bcbecdee9c1c","markdown_url":"https:\/\/skillshunter.net\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-non-spreadsheet-analysis-capability-pdf-analysis-bcbecdee9c1c.md","download_url":"https:\/\/skillshunter.net\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-non-spreadsheet-analysis-capability-pdf-analysis-bcbecdee9c1c\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"The tool requires the PyMuPDF library for text extraction and pdfplumber for table extraction. For scanned PDFs, it uses an external image captioning script to perform OCR.","instructions":"---\nname: pdf-analysis\ndescription: \"PDF \u6587\u6863\u89e3\u6790\u3002\u81ea\u52a8\u533a\u5206\u6587\u5b57\u578b PDF \u4e0e\u626b\u63cf\u578b PDF\uff0c\u8986\u76d6\uff1a\u6587\u672c\/\u8868\u683c\u63d0\u53d6\u3001\u591a\u9875\u5168\u91cf\u626b\u63cf\u3001\u5d4c\u5165\u56fe\u8868 caption\u3001\u5355\u4f4d\u611f\u77e5\u6570\u503c\u8ba1\u7b97\u3002\"\n---\n\n# PDF Analysis\n\n## Step 0 \u2014 Detect PDF type (text vs scanned)\n\n**Critical first step**: determine whether the PDF has extractable text or is a scanned image.\nNever skip this \u2014 using the wrong parser wastes time and produces empty results.\n\n```python\nimport fitz  # PyMuPDF\n\ndef detect_pdf_type(pdf_path, sample_pages=3):\n    \"\"\"\n    Returns 'text' if PDF has extractable text, 'scanned' if image-based.\n    Checks first N pages (or all if fewer).\n    \"\"\"\n    doc = fitz.open(pdf_path)\n    total_chars = 0\n    pages_checked = min(sample_pages, len(doc))\n\n    for i in range(pages_checked):\n        page = doc[i]\n        text = page.get_text(\"text\")\n        total_chars += len(text.strip())\n\n    doc.close()\n    avg_chars = total_chars \/ max(pages_checked, 1)\n    pdf_type = 'text' if avg_chars > 50 else 'scanned'\n    print(f\"PDF type: {pdf_type} (avg {avg_chars:.0f} chars\/page, checked {pages_checked} pages)\")\n    return pdf_type\n```\n\n---\n\n## Core Method 1: Text PDF \u2014 Full Text Extraction (ALL pages)\n\n```python\nimport fitz\n\ndef extract_text_pdf(pdf_path):\n    \"\"\"Extract text from all pages of a text-based PDF.\"\"\"\n    doc = fitz.open(pdf_path)\n    total_pages = len(doc)\n    print(f\"Total pages: {total_pages}\")\n\n    all_text = []\n    for i, page in enumerate(doc):\n        text = page.get_text(\"text\").strip()\n        if text:\n            all_text.append(f\"=== Page {i+1} ===\\n{text}\")\n        else:\n            print(f\"  Page {i+1}: no text (may be image \u2014 will caption later)\")\n\n    doc.close()\n    return '\\n\\n'.join(all_text)\n\n# \u26a0\ufe0f MUST iterate ALL pages \u2014 never stop at page 1\nfull_text = extract_text_pdf(pdf_path)\nprint(f\"Total text length: {len(full_text)} chars\")\n```\n\n---\n\n## Core Method 2: Text PDF \u2014 Table Extraction\n\nFor PDFs with tables, `pdfplumber` gives better table structure than `fitz`:\n\n```python\nimport pdfplumber\nimport pandas as pd\n\ndef extract_tables_pdf(pdf_path):\n    \"\"\"Extract all tables from all pages as DataFrames.\"\"\"\n    all_tables = []\n    with pdfplumber.open(pdf_path) as pdf:\n        print(f\"Total pages: {len(pdf.pages)}\")\n        for i, page in enumerate(pdf.pages):\n            tables = page.extract_tables()\n            for j, tbl in enumerate(tables):\n                if not tbl:\n                    continue\n                # First row as header\n                df = pd.DataFrame(tbl[1:], columns=tbl[0])\n                # Clean: strip whitespace, replace None\n                df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)\n                df = df.dropna(how='all').reset_index(drop=True)\n                all_tables.append({'page': i+1, 'table_idx': j, 'df': df})\n                print(f\"  Page {i+1}, Table {j}: {df.shape[0]}r \u00d7 {df.shape[1]}c\")\n                print(df.head(3))\n    return all_tables\n\n# Verify table alignment after extraction:\n# Print column headers and first 3 rows to confirm row\/col mapping is correct\n```\n\n---\n\n## Core Method 3: Scanned PDF \u2014 OCR via Caption\n\nFor scanned PDFs (image-based pages), render each page as PNG and caption:\n\n```python\nimport fitz\nimport subprocess, json, os\n\nCAPTION = \"\/path\/to\/skills\/sn-da-image-caption\/scripts\/caption.py\"\n\ndef extract_scanned_pdf(pdf_path, prompt=None, dpi=150):\n    \"\"\"Render each page as image, then caption for text extraction.\"\"\"\n    doc = fitz.open(pdf_path)\n    total_pages = len(doc)\n    print(f\"Scanned PDF: {total_pages} pages, captioning each...\")\n\n    all_text = []\n    for i, page in enumerate(doc):\n        # Render page to PNG\n        mat = fitz.Matrix(dpi\/72, dpi\/72)\n        pix = page.get_pixmap(matrix=mat)\n        img_path = f\"\/tmp\/pdf_page_{i+1}.png\"\n        pix.save(img_path)\n\n        # Caption the page image\n        cmd = [\"python3\", CAPTION, img_path, \"--json\"]\n        if prompt:\n            cmd += [\"--prompt\", prompt]\n        else:\n            cmd += [\"--prompt\", \"\u63d0\u53d6\u9875\u9762\u4e2d\u6240\u6709\u6587\u5b57\u548c\u8868\u683c\u5185\u5bb9\uff0c\u4fdd\u6301\u539f\u59cb\u7ed3\u6784\uff0cMarkdown\u683c\u5f0f\u8f93\u51fa\u3002\"]\n\n        r = subprocess.run(cmd, capture_output=True, text=True, timeout=90)\n        if r.returncode == 0:\n            desc = json.loads(r.stdout).get(\"description\", \"\")\n            all_text.append(f\"=== Page {i+1} ===\\n{desc}\")\n            print(f\"  Page {i+1}: {len(desc)} chars extracted\")\n        else:\n            print(f\"  Page {i+1}: caption failed \u2014 {r.stderr[:100]}\")\n\n    doc.close()\n    return '\\n\\n'.join(all_text)\n\n# Usage for scanned invoice PDFs, bank statements, org charts, etc.\ntext = extract_scanned_pdf(pdf_path)\n```\n\n---\n\n## Core Method 4: Hybrid PDF (mixed text + image pages)\n\n```python\ndef extract_hybrid_pdf(pdf_path, text_prompt=None, image_prompt=None):\n    \"\"\"Handle PDFs where some pages have text, others are scanned.\"\"\"\n    doc_fitz = fitz.open(pdf_path)\n    all_text = []\n\n    for i, page in enumerate(doc_fitz):\n        raw_text = page.get_text(\"text\").strip()\n\n        if len(raw_text) > 50:\n            # Text page \u2014 use directly\n            all_text.append(f\"=== Page {i+1} (text) ===\\n{raw_text}\")\n        else:\n            # Image page \u2014 render and caption\n            mat = fitz.Matrix(150\/72, 150\/72)\n            pix = page.get_pixmap(matrix=mat)\n            img_path = f\"\/tmp\/hybrid_page_{i+1}.png\"\n            pix.save(img_path)\n\n            cmd = [\"python3\", CAPTION, img_path, \"--json\"]\n            prompt = image_prompt or \"\u63d0\u53d6\u9875\u9762\u4e2d\u6240\u6709\u6587\u5b57\u548c\u8868\u683c\u5185\u5bb9\uff0cMarkdown\u683c\u5f0f\u8f93\u51fa\u3002\"\n            cmd += [\"--prompt\", prompt]\n\n            r = subprocess.run(cmd, capture_output=True, text=True, timeout=90)\n            if r.returncode == 0:\n                desc = json.loads(r.stdout).get(\"description\", \"\")\n                all_text.append(f\"=== Page {i+1} (image\u2192caption) ===\\n{desc}\")\n            else:\n                all_text.append(f\"=== Page {i+1} (caption failed) ===\")\n\n    doc_fitz.close()\n    return '\\n\\n'.join(all_text)\n```\n\n---\n\n## Core Method 5: Extract Embedded Images \/ Charts from PDF\n\n```python\nimport fitz\n\ndef extract_pdf_images(pdf_path, min_width=100, min_height=100):\n    \"\"\"Extract all embedded images from a PDF (charts, diagrams, photos).\"\"\"\n    doc = fitz.open(pdf_path)\n    image_paths = []\n\n    for page_num, page in enumerate(doc):\n        for img_idx, img in enumerate(page.get_images(full=True)):\n            xref = img[0]\n            base = doc.extract_image(xref)\n            img_bytes = base[\"image\"]\n            ext = base[\"ext\"]\n\n            img_path = f\"\/tmp\/pdf_img_p{page_num+1}_{img_idx}.{ext}\"\n            with open(img_path, 'wb') as f:\n                f.write(img_bytes)\n\n            # Only keep images above size threshold (skip icons\/logos)\n            from PIL import Image\n            with Image.open(img_path) as im:\n                w, h = im.size\n            if w >= min_width and h >= min_height:\n                image_paths.append({'page': page_num+1, 'path': img_path, 'size': (w, h)})\n                print(f\"  Page {page_num+1}, img {img_idx}: {w}\u00d7{h} \u2192 {img_path}\")\n\n    doc.close()\n    return image_paths\n\n# After extracting, caption each image:\n# for img_info in image_paths:\n#     caption_image(img_info['path'], prompt=\"\u63d0\u53d6\u56fe\u8868\u6570\u636e\uff0cMarkdown \u8868\u683c\u8f93\u51fa\u3002\")\n```\n\n---\n\n## Common Patterns\n\n### Multi-invoice \/ multi-document PDF (\u53d1\u7968\u6c47\u603b)\n\n```python\n# When PDF contains multiple invoices (one per page):\ntables_by_page = extract_tables_pdf(pdf_path)\ninvoices = []\nfor item in tables_by_page:\n    df = item['df']\n    # Find key fields (flexible column name matching)\n    for col in df.columns:\n        if '\u91d1\u989d' in str(col) or 'amount' in str(col).lower():\n            invoices.append({'page': item['page'], 'amount_col': col, 'data': df})\n            break\nprint(f\"Found {len(invoices)} pages with amount data\")\n```\n\n### Numeric extraction with unit awareness\n\n```python\nimport re\n\ndef extract_number_with_unit(text_snippet):\n    \"\"\"\n    Extract value and unit from text like '1,760 \u5343\u6e2f\u5143' or '95,975,196,217.52\u5143'.\n    Returns (numeric_value, unit_string).\n    \"\"\"\n    # Remove thousands separator\n    text_snippet = text_snippet.replace(',', '')\n    match = re.search(r'([\\d\\.]+)\\s*(\u5343|\u4e07|\u4ebf|\u767e\u4e07)?\\s*(\u5143|\u6e2f\u5143|\u7f8e\u5143|\u4eba\u6c11\u5e01|%|percent)?', text_snippet)\n    if not match:\n        return None, None\n    value = float(match.group(1))\n    multiplier_map = {'\u5343': 1000, '\u4e07': 10000, '\u4ebf': 1e8, '\u767e\u4e07': 1e6}\n    mult = multiplier_map.get(match.group(2), 1)\n    unit = match.group(3) or ''\n    return value * mult, f\"{match.group(2) or ''}{unit}\"\n\n# Always verify unit matches what the question asks:\n# \"\u591a\u51e0\u591a\" in HKD \u2192 answer in \u5343\u6e2f\u5143 if source says \u5343\u6e2f\u5143\n```\n\n### Long document keyword search\n\n```python\ndef find_in_pdf(pdf_path, keyword, context_chars=200):\n    \"\"\"Search for keyword across all pages, return context snippets.\"\"\"\n    text = extract_text_pdf(pdf_path)\n    results = []\n    start = 0\n    while True:\n        idx = text.find(keyword, start)\n        if idx < 0:\n            break\n        snippet = text[max(0, idx-context_chars\/\/2): idx+context_chars]\n        results.append({'pos': idx, 'context': snippet})\n        start = idx + 1\n    print(f\"Found '{keyword}' {len(results)} times\")\n    return results\n```\n\n---\n\n## Pitfalls\n\n| Pitfall | Fix |\n|---------|-----|\n| Use `pdfplumber` on scanned PDF \u2192 empty result | Detect type first (Method 0); use OCR path for scanned |\n| Only read page 1, miss remaining invoices\/data | Always `for page in doc` \u2014 never index `[0]` only |\n| Table columns misaligned after extraction | Print headers + first 3 rows to verify before computing |\n| Report number as % when question asks absolute value | Read question carefully; `extract_number_with_unit()` preserves context |\n| Chart data embedded as image \u2192 pdfplumber returns nothing | Extract images (Method 5), then caption each |\n| Long doc loses cross-page context | Use `find_in_pdf()` for keyword search across full text |\n| `.pdf` contains multiple scanned docs (zip of PDFs) | Check if input is dir or archive; unzip first |\n","use_cases":["Extract text from text-based PDFs for data processing","Analyze scanned invoices and bank statements with OCR","Extract tables from structured PDF documents","Process hybrid PDFs with both text and scanned pages"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/OpenSenseNova\/SenseNova-Skills\/blob\/07e7ff8c4bdfd7b79e7402fe94af59d2a5a9749b\/skills\/sn-da-non-spreadsheet-analysis\/capability\/pdf-analysis\/SKILL.md","source_commit":"07e7ff8c4bdfd7b79e7402fe94af59d2a5a9749b","license":null,"version":null,"listing_approved_at":"2026-11-16","created_at":"2026-11-15T10:16:26.000000Z","updated_at":"2026-11-16T05:16:30.000000Z","seo_title":"PDF Content Extraction and Analysis Tool","seo_description":"Extract text, tables, and scanned content from PDFs with accurate parsing and OCR. Supports text and scanned PDFs.","seo_keywords":["PDF text extraction","scanned PDF analysis","OCR PDF processing","table extraction from PDF","hybrid PDF parsing"]}}