Communitygithub.com

bg-szy/TOP-SKILLS

當使用者需要處理任何 PDF 檔案時使用此技能,包含讀取、提取文字/表格、合併、分割、旋轉頁面、加入浮水印、建立新 PDF、填寫 PDF 表單、加密/解密、提取圖片以及對掃描 PDF 進行 OCR 以提高搜尋性。

TOP-SKILLS 是什麼?

這個技能(bg-szy/TOP-SKILLS)為 AI 代理提供了一套完整的 PDF 處理指南,涵蓋 Python 函式庫(如 pypdf、pdfplumber、reportlab)與命令列工具(如 pdftotext、qpdf、pdftk)。無論是基本操作(合併、分割、旋轉、加密)、進階擷取(表格、圖片、OCR),還是建立結構化 PDF 文件,都能夠透過清晰的程式碼範例與指令快速實現。此技能特別支援 pypdf 處理常見的 PDF 操作,pdfplumber 進行精準的文字與表格萃取,reportlab 從無到有建立 PDF,以及 qpdf 和 pdftk 提供輕量級的指令列方案。對於掃描文件,整合了 pytesseract 與 pdf2image 進行 OCR。此外,它還明確指示在需要填寫 PDF 表單時應參閱 FORMS.md,並連結至更深入的 REFERENCE.md。整體而言,此技能讓 AI 代理能夠有效率地應對使用者的多種 PDF 需求,並提供跨平台的相容性與實作上的最佳實踐。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/bg-szy/TOP-SKILLS/tree/HEAD/skills/skills/pdf

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

PDF 處理指南

概述

本指南涵蓋了使用 Python 函式庫和命令列工具進行基本 PDF 處理作業。如需進階功能、JavaScript 函式庫和詳細範例,請參閱 REFERENCE.md。如果您需要填寫 PDF 表單,請閱讀 FORMS.md 並遵循其說明。

快速入門

from pypdf import PdfReader, PdfWriter

# 讀取 PDF
reader = PdfReader("document.pdf")
print(f"頁數: {len(reader.pages)}")

# 提取文字
text = ""
for page in reader.pages:
    text += page.extract_text()

Python 函式庫

pypdf - 基本操作

合併 PDF

from pypdf import PdfWriter, PdfReader

writer = PdfWriter()
for pdf_file in ["doc1.pdf", "doc2.pdf", "doc3.pdf"]:
    reader = PdfReader(pdf_file)
    for page in reader.pages:
        writer.add_page(page)

with open("merged.pdf", "wb") as output:
    writer.write(output)

分割 PDF

reader = PdfReader("input.pdf")
for i, page in enumerate(reader.pages):
    writer = PdfWriter()
    writer.add_page(page)
    with open(f"page_{i+1}.pdf", "wb") as output:
        writer.write(output)

提取元資料

reader = PdfReader("document.pdf")
meta = reader.metadata
print(f"標題: {meta.title}")
print(f"作者: {meta.author}")
print(f"主旨: {meta.subject}")
print(f"建立者: {meta.creator}")

旋轉頁面

reader = PdfReader("input.pdf")
writer = PdfWriter()

page = reader.pages[0]
page.rotate(90)  # 順時針旋轉 90 度
writer.add_page(page)

with open("rotated.pdf", "wb") as output:
    writer.write(output)

pdfplumber - 文字與表格提取

提取文字(保留版面)

import pdfplumber

with pdfplumber.open("document.pdf") as pdf:
    for page in pdf.pages:
        text = page.extract_text()
        print(text)

提取表格

with pdfplumber.open("document.pdf") as pdf:
    for i, page in enumerate(pdf.pages):
        tables = page.extract_tables()
        for j, table in enumerate(tables):
            print(f"第 {i+1} 頁的表格 {j+1}:")
            for row in table:
                print(row)

進階表格提取

import pandas as pd

with pdfplumber.open("document.pdf") as pdf:
    all_tables = []
    for page in pdf.pages:
        tables = page.extract_tables()
        for table in tables:
            if table:  # 檢查表格是否非空
                df = pd.DataFrame(table[1:], columns=table[0])
                all_tables.append(df)

# 合併所有表格
if all_tables:
    combined_df = pd.concat(all_tables, ignore_index=True)
    combined_df.to_excel("extracted_tables.xlsx", index=False)

reportlab - 建立 PDF

基本 PDF 建立

from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas

c = canvas.Canvas("hello.pdf", pagesize=letter)
width, height = letter

# 新增文字
c.drawString(100, height - 100, "Hello World!")
c.drawString(100, height - 120, "這是一個用 reportlab 建立的 PDF")

# 新增線條
c.line(100, height - 140, 400, height - 140)

# 儲存
c.save()

建立多頁 PDF

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet

doc = SimpleDocTemplate("report.pdf", pagesize=letter)
styles = getSampleStyleSheet()
story = []

# 新增內容
title = Paragraph("報告標題", styles['Title'])
story.append(title)
story.append(Spacer(1, 12))

body = Paragraph("這是報告的主體內容。" * 20, styles['Normal'])
story.append(body)
story.append(PageBreak())

# 第 2 頁
story.append(Paragraph("第 2 頁", styles['Heading1']))
story.append(Paragraph("第 2 頁的內容", styles['Normal']))

# 建立 PDF
doc.build(story)

下標與上標

重要:永遠不要在 ReportLab PDF 中使用 Unicode 下標/上標字元(₀₁₂₃₄₅₆₇₈₉、⁰¹²³⁴⁵⁶⁷⁸⁹)。內建字型不包含這些字形,會導致它們顯示為黑色實心方塊。

請改用 ReportLab 在 Paragraph 物件中的 XML 標記:

from reportlab.platypus import Paragraph
from reportlab.lib.styles import getSampleStyleSheet

styles = getSampleStyleSheet()

# 下標:使用 <sub> 標籤
chemical = Paragraph("H<sub>2</sub>O", styles['Normal'])

# 上標:使用 <super> 標籤
squared = Paragraph("x<super>2</super> + y<super>2</super>", styles['Normal'])

對於以 canvas 繪製的文字(非 Paragraph 物件),請手動調整字型大小和位置,而不要使用 Unicode 下標/上標。

命令列工具

pdftotext (poppler-utils)

# 提取文字
pdftotext input.pdf output.txt

# 保留版面的文字提取
pdftotext -layout input.pdf output.txt

# 提取指定頁面
pdftotext -f 1 -l 5 input.pdf output.txt  # 第 1 至 5 頁

qpdf

# 合併 PDF
qpdf --empty --pages file1.pdf file2.pdf -- merged.pdf

# 分割頁面
qpdf input.pdf --pages . 1-5 -- pages1-5.pdf
qpdf input.pdf --pages . 6-10 -- pages6-10.pdf

# 旋轉頁面
qpdf input.pdf output.pdf --rotate=+90:1  # 將第 1 頁旋轉 90 度

# 移除密碼
qpdf --password=mypassword --decrypt encrypted.pdf decrypted.pdf

pdftk(如可用)

# 合併
pdftk file1.pdf file2.pdf cat output merged.pdf

# 分割
pdftk input.pdf burst

# 旋轉
pdftk input.pdf rotate 1east output rotated.pdf

常見任務

從掃描 PDF 提取文字

# 需要安裝:pip install pytesseract pdf2image
import pytesseract
from pdf2image import convert_from_path

# 將 PDF 轉換為圖片
images = convert_from_path('scanned.pdf')

# 對每一頁進行 OCR
text = ""
for i, image in enumerate(images):
    text += f"第 {i+1} 頁:\n"
    text += pytesseract.image_to_string(image)
    text += "\n\n"

print(text)

新增浮水印

from pypdf import PdfReader, PdfWriter

# 建立浮水印(或載入現有浮水印)
watermark = PdfReader("watermark.pdf").pages[0]

# 套用到所有頁面
reader = PdfReader("document.pdf")
writer = PdfWriter()

for page in reader.pages:
    page.merge_page(watermark)
    writer.add_page(page)

with open("watermarked.pdf", "wb") as output:
    writer.write(output)

提取圖片

# 使用 pdfimages (poppler-utils)
pdfimages -j input.pdf output_prefix

# 這會將所有圖片提取為 output_prefix-000.jpg、output_prefix-001.jpg 等

密碼保護

from pypdf import PdfReader, PdfWriter

reader = PdfReader("input.pdf")
writer = PdfWriter()

for page in reader.pages:
    writer.add_page(page)

# 新增密碼
writer.encrypt("userpassword", "ownerpassword")

with open("encrypted.pdf", "wb") as output:
    writer.write(output)

快速參考

任務最佳工具命令/程式碼
合併 PDFpypdfwriter.add_page(page)
分割 PDFpypdf每個頁面一個檔案
提取文字pdfplumberpage.extract_text()
提取表格pdfplumberpage.extract_tables()
建立 PDFreportlabCanvas 或 Platypus
命令列合併qpdfqpdf --empty --pages ...
掃描 PDF OCRpytesseract先轉換為圖片
填寫 PDF 表單pdf-lib 或 pypdf(見 FORMS.md)見 FORMS.md

後續步驟

  • 如需進階 pypdfium2 用法,請參閱 REFERENCE.md
  • 如需 JavaScript 函式庫(pdf-lib),請參閱 REFERENCE.md
  • 如果您需要填寫 PDF 表單,請遵循 FORMS.md 中的說明
  • 如需疑難排解指南,請參閱 REFERENCE.md

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

bg-szy/TOP-SKILLS

Brand-first landing page designer — runs a brand-identity interview (colors, typography, shape language), then generates and iterates on a polished landing page via Stitch with deployment-ready HTML. Use when the user asks to create, design, or build a landing page, homepage, or marketing page and has no established visual direction. Skip when they have a design mockup, need a dashboard or app UI, are working at component level, building a multi-page app, or restyling with known design tokens — use frontend-design instead.

bg-szy/TOP-SKILLS

Fill out Microsoft Azure Landing Zone (ALZ) Accelerator checklists by interviewing the user, mapping their Azure subscriptions, integrating IP addressing documentation, and applying Microsoft Cloud Adoption Framework best practices. Produces a completed Excel checklist (.xlsx) ready for ALZ deployment. Use this skill whenever the user mentions Azure Landing Zone, ALZ checklist, landing zone accelerator, platform landing zone configuration, ALZ bootstrap, hub-and-spoke setup, Azure network topology planning, or wants to fill out any ALZ-related checklist or configuration file. Also trigger when the user uploads an Excel file that contains tabs like "Accelerator - Bootstrap", "Accelerator - Bicep", or "Accelerator - Terraform".

bg-szy/TOP-SKILLS

Compose a premium, animated landing page section by section in Next.js + Tailwind + Motion (Framer Motion) — built on a real design system, with editorial copy and motion that feels human-crafted, not template-generated. Use when building or rebuilding a landing page, marketing site, or hero/feature/pricing/CTA sections that need to look production-ready and bespoke from day one.

bg-szy/TOP-SKILLS

Write high-converting landing page copy using proven frameworks like PAS (Problem-Agitate-Solution), AIDA, and StoryBrand. Creates headlines, value propositions, CTAs, and full page sections optimized for conversion. Use when users need landing page copy, sales page content, or marketing website text.

bg-szy/TOP-SKILLS

Optimize landing pages for conversions, performance, and SEO. Use when improving landing pages, increasing conversions, or optimizing page performance.

bg-szy/TOP-SKILLS

Review investment portfolios for risk, diversification, fees. Asset allocation recommendations, tax-loss harvesting, rebalancing.

bg-szy/TOP-SKILLS

Beads Viewer - Graph-aware triage engine for Beads projects. Computes PageRank, betweenness, critical path, and cycles. Use --robot-* flags for AI agents.

bg-szy/TOP-SKILLS

CI red? Call us. Pipeline fire brigade deploys. Use when user mentions CI failures, build errors, test failures, or pipeline issues. Do NOT load for: local builds, standard implementation work, reviews, or setup.

bg-szy/TOP-SKILLS

CASS Memory System - procedural memory for AI coding agents. Three-layer cognitive architecture with confidence decay, anti-pattern learning, cross-agent knowledge transfer, trauma guard safety system. Bun/TypeScript CLI.

bg-szy/TOP-SKILLS

Mandatory entry point: read this first for any request to make, create, edit, animate, or render a video, animation, or motion graphic, including a promo, explainer, captioned clip, title card, overlay, slideshow or interactive deck, Remotion port, or any HyperFrames HTML composition. Also use it to inspect, diagnose, validate, preview, publish, or batch-render an existing HyperFrames project. Inputs may be a website URL, GitHub PR, Figma design or URL, text or brief, existing footage, or music. It resumes project state, captures intent when applicable, selects and installs the owning workflow, and routes domain capabilities. HyperFrames is the default output framework unless the user explicitly chooses another framework for the deliverable or asks only to record a browser session.

bg-szy/TOP-SKILLS

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

bg-szy/TOP-SKILLS

Use when the user asks to "pre-launch check the landing page", "run a Quality-Score preflight", or "verify ad-to-page message match before launch"; produces an ad↔page continuity report — message-match gaps, above-the-fold check, page-speed read, form-friction count, mobile-render flags — as a pass/fix punch list. Not for redesigning or rewriting the page — use landing-optimizer; not for scoring the account or the RQS — use ad-account-auditor. 落地页体验预检/广告落地页一致性检查

bg-szy/TOP-SKILLS

Use when the user asks to "optimize our landing page for influencer traffic", "fix our promo-code landing page", or "improve conversion from a creator campaign"; produces a message-match audit, page-structure and social-proof recommendations, a promo-code/CTA conversion plan, and an A/B test roadmap. Not for measuring campaign results after launch — use performance-analyzer.

bg-szy/TOP-SKILLS

Audit a landing page, sales page or checkout page for conversion leaks and return a fix list ordered by expected revenue impact. Use when asked to review, critique or improve a landing page, sales page, opt-in page, product page or checkout flow, when conversion rate is low, when paid traffic is not converting, or when someone asks "why isn't this page converting" or wants a CRO / landing page review.

bg-szy/TOP-SKILLS

Landing page conversion optimization with layout rules, hero section design, and CTA psychology. Covers above-the-fold formula, social proof placement, mobile design, and F-pattern reading. Use for: startup landing pages, product pages, SaaS marketing, conversion optimization. Triggers: landing page, hero section, above the fold, conversion optimization, landing page design, cta button, hero image, landing page layout, saas landing page, product page design, conversion rate, landing page best practices

bg-szy/TOP-SKILLS

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

bg-szy/TOP-SKILLS

Landing page conversion optimization with layout rules, hero section design, and CTA psychology. Covers above-the-fold formula, social proof placement, mobile design, and F-pattern reading. Use for: startup landing pages, product pages, SaaS marketing, conversion optimization. Triggers: landing page, hero section, above the fold, conversion optimization, landing page design, cta button, hero image, landing page layout, saas landing page, product page design, conversion rate, landing page best practices

bg-szy/TOP-SKILLS

Account assets, equity and fund positions, P&L, cash flow records, account statements, margin ratios, buy-power estimates, order management, and DCA recurring investments via Longbridge (most require Trade permission). Frameworks: portfolio diagnosis, rebalancing, asset allocation, risk analysis (VaR/CVaR), performance attribution, and tax-loss harvesting. Triggers: "持仓", "账户", "盈亏", "资产", "对账单", "下单", "买入", "卖出", "撤单", "定投", "组合诊断", "再平衡", "资产配置", "风险分析", "绩效归因", "税损收割", "持倉", "賬戶", "盈虧", "對賬單", "下單", "買入", "賣出", "組合診斷", "再平衡", "稅損收割", "positions", "portfolio", "P&L", "order", "buy", "sell", "DCA", "statement", "risk analysis", "rebalancing", "tax harvesting", "我的风险", "持仓风险", "风险敞口", "資產", "資產配置", "風險分析", "績效歸因", "撤單

bg-szy/TOP-SKILLS

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

bg-szy/TOP-SKILLS

Process video files with audio extraction, format conversion (mp4, webm), and Whisper transcription. Use when user mentions video conversion, audio extraction, transcription, mp4, webm, ffmpeg, or whisper transcription.

相關技能