Communitygithub.com

kyopark2014/strands-skills

展示如何在 Strands SDK 中使用代理技能。

strands-skills 是什麼?

該技能提供了使用 Python 程式庫進行 PDF 處理的完整指南,特別針對韓文(한국어)內容進行了優化,是開發 Strands SDK 代理應用的理想參考。技能詳盡說明了如何透過 reportlab 建立 PDF,包括從字型註冊(優先使用 NanumGothic TTF,其次為內建 CID 字型 HYGothic-Medium)到樣式定義與完整文件生成的完整流程,並涵蓋了錯誤字型(如 macOS 的 AppleSDGothicNeo.ttc)的限制。此外,還透過 pypdf 展示了讀取、合併、分割、旋轉及密碼保護等操作,並說明了如何使用 pdfplumber 從現有 PDF 中提取表格。技能支援所有主流 AI 代理平台(如 Claude Code、Cursor、Codex),並通過 `execute_code` 工具執行 Python 程式碼,所有產出檔案應儲存至 `artifacts/` 目錄。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add kyopark2014/strands-skills

在你喜歡的 AI 中提問

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

說明文件

PDF 處理指南

概述

本指南涵蓋使用 Python 程式庫進行 PDF 處理的基本操作。 請使用 execute_code 工具執行下方顯示的 Python 程式碼。 所有產生的檔案應儲存至 artifacts/ 目錄。

韓文字型設定(必要 — 所有 PDF 生成程式碼必須包含)

建立包含韓文的 PDF 時,必須註冊韓文字型。 請務必將下列字型註冊程式碼包含在所有 PDF 生成程式碼的最前面。

重要:macOS 的 AppleSDGothicNeo.ttc 使用 PostScript 外框,因此 reportlab 無法使用。

字型優先順序:

  1. assets/NanumGothic-Regular.ttf(TTF 檔案 — 最可靠)
  2. CID 字型 HYGothic-Medium(reportlab 內建 — 無需額外檔案,可靠的備用方案)
import os
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.cidfonts import UnicodeCIDFont

def register_korean_font():
    """註冊韓文字型並回傳字型名稱。產生 PDF 前必須呼叫。"""
    # 第1優先:NanumGothic TTF
    ttf_paths = [
        os.path.join("assets", "NanumGothic-Regular.ttf"),
        "/usr/share/fonts/truetype/nanum/NanumGothic.ttf",
        "/usr/share/fonts/nanum/NanumGothic.ttf",
        "/Library/Fonts/NanumGothic.ttf",
    ]
    for path in ttf_paths:
        if os.path.exists(path):
            try:
                pdfmetrics.registerFont(TTFont("KoreanFont", path))
                return "KoreanFont"
            except Exception:
                continue

    # 第2優先:CID 字型 (reportlab 內建,無需額外檔案)
    try:
        pdfmetrics.registerFont(UnicodeCIDFont("HYGothic-Medium"))
        return "HYGothic-Medium"
    except Exception:
        pass

    return "Helvetica"  # 最終備用 (不支援韓文)

font_name = register_korean_font()

建立新 PDF (reportlab)

基本 PDF 建立(僅英文)

from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
import os

os.makedirs("artifacts", exist_ok=True)
c = canvas.Canvas("artifacts/hello.pdf", pagesize=A4)
width, height = A4
c.drawString(100, height - 100, "Hello World!")
c.save()

韓文 PDF 生成(建議模式)

import os
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import inch
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.cidfonts import UnicodeCIDFont

# 1) 註冊韓文字型
font_name = "Helvetica"
for path in [os.path.join("assets", "NanumGothic-Regular.ttf"),
             "/usr/share/fonts/truetype/nanum/NanumGothic.ttf"]:
    if os.path.exists(path):
        try:
            pdfmetrics.registerFont(TTFont("KoreanFont", path))
            font_name = "KoreanFont"
            break
        except Exception:
            continue
if font_name == "Helvetica":
    try:
        pdfmetrics.registerFont(UnicodeCIDFont("HYGothic-Medium"))
        font_name = "HYGothic-Medium"
    except Exception:
        pass

# 2) 定義韓文樣式
styles = getSampleStyleSheet()
styles.add(ParagraphStyle("Title_KO",   parent=styles["Title"],    fontName=font_name, fontSize=20, spaceAfter=20, textColor=colors.HexColor("#1a1a2e")))
styles.add(ParagraphStyle("H1_KO",      parent=styles["Heading1"], fontName=font_name, fontSize=16, spaceAfter=14, textColor=colors.HexColor("#16213e")))
styles.add(ParagraphStyle("H2_KO",      parent=styles["Heading2"], fontName=font_name, fontSize=14, spaceAfter=12, textColor=colors.HexColor("#0f3460")))
styles.add(ParagraphStyle("Normal_KO",  parent=styles["Normal"],   fontName=font_name, fontSize=10, leading=14, spaceAfter=8))
styles.add(ParagraphStyle("Bullet_KO",  parent=styles["Normal"],   fontName=font_name, fontSize=10, leading=14, leftIndent=20, bulletIndent=10))

# 3) 建立 PDF
os.makedirs("artifacts", exist_ok=True)
doc = SimpleDocTemplate("artifacts/report.pdf", pagesize=A4,
    topMargin=0.8*inch, bottomMargin=0.8*inch, leftMargin=0.75*inch, rightMargin=0.75*inch)

story = []
story.append(Paragraph("報告書標題", styles["Title_KO"]))
story.append(Spacer(1, 16))
story.append(Paragraph("1. 概述", styles["H1_KO"]))
story.append(Paragraph("本報告書包含範例內容。", styles["Normal_KO"]))
story.append(Spacer(1, 8))
story.append(Paragraph("2. 詳細內容", styles["H1_KO"]))
story.append(Paragraph("• 第一個項目", styles["Bullet_KO"]))
story.append(Paragraph("• 第二個項目", styles["Bullet_KO"]))
story.append(PageBreak())
story.append(Paragraph("3. 附錄", styles["H1_KO"]))
story.append(Paragraph("這是額外內容。", styles["Normal_KO"]))

doc.build(story)
print("PDF 建立完成:artifacts/report.pdf")

包含韓文表格的 PDF

import os
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.cidfonts import UnicodeCIDFont

# 字型註冊
font_name = "Helvetica"
for path in [os.path.join("assets", "NanumGothic-Regular.ttf"),
             "/usr/share/fonts/truetype/nanum/NanumGothic.ttf"]:
    if os.path.exists(path):
        try:
            pdfmetrics.registerFont(TTFont("KoreanFont", path))
            font_name = "KoreanFont"
            break
        except Exception:
            continue
if font_name == "Helvetica":
    try:
        pdfmetrics.registerFont(UnicodeCIDFont("HYGothic-Medium"))
        font_name = "HYGothic-Medium"
    except Exception:
        pass

styles = getSampleStyleSheet()
styles.add(ParagraphStyle("Title_KO",  parent=styles["Title"],  fontName=font_name, fontSize=18, textColor=colors.HexColor("#1a1a2e")))
styles.add(ParagraphStyle("Normal_KO", parent=styles["Normal"], fontName=font_name, fontSize=10))

os.makedirs("artifacts", exist_ok=True)
doc = SimpleDocTemplate("artifacts/table_report.pdf", pagesize=A4)

data = [
    ["項目", "說明", "費用"],
    ["伺服器", "EC2 實例", "$120"],
    ["儲存", "S3 儲存桶", "$45"],
    ["資料庫", "RDS PostgreSQL", "$89"],
]
table = Table(data, colWidths=[120, 200, 80])
table.setStyle(TableStyle([
    ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#e8eaf6")),
    ("TEXTCOLOR", (0, 0), (-1, 0), colors.HexColor("#1a1a2e")),
    ("FONTNAME", (0, 0), (-1, -1), font_name),
    ("FONTSIZE", (0, 0), (-1, -1), 10),
    ("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#bdbdbd")),
    ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ("TOPPADDING", (0, 0), (-1, -1), 6),
    ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
]))

doc.build([
    Paragraph("成本分析報告", styles["Title_KO"]),
    Spacer(1, 16),
    table
])
print("PDF 建立完成:artifacts/table_report.pdf")

reportlab 的重要注意事項

  • 使用韓文文字時,務必包含上述字型註冊程式碼。
  • macOS 的 AppleSDGothicNeo.ttc 使用 PostScript 外框,因此 reportlab 無法使用。絕對不要使用。
  • 如果沒有 TTF 字型 (assets/NanumGothic-Regular.ttf),請改用 CID 字型 HYGothic-Medium。
  • 未註冊字型會導致韓文顯示錯誤或出現空心方塊 (□)。
  • 請勿在 ReportLab PDF 中使用 Unicode 下標/上標字元 (₀₁₂₃₄₅₆₇₈₉) — 請改用 <sub> 和 <sup> 標籤。

讀取 PDF (pypdf)

提取文字

from pypdf import PdfReader

reader = PdfReader("input.pdf")
text = ""
for page in reader.pages:
    text += page.extract_text()
print(text)

合併 PDF

from pypdf import PdfWriter, PdfReader

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

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

分割 PDF

from pypdf import PdfReader, PdfWriter

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

旋轉頁面

from pypdf import PdfReader, PdfWriter

reader = PdfReader("input.pdf")
writer = PdfWriter()
page = reader.pages[0]
page.rotate(90)
writer.add_page(page)

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

密碼保護

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("artifacts/encrypted.pdf", "wb") as output:
    writer.write(output)

表格提取 (pdfplumber)

import pdfplumber

with pdfplumber.open("input.pdf") as pdf:
    for page in pdf.pages:
        text = page.extract_text()
        tables = page.extract_tables()
        for table in tables:
            for row in table:
                print(row)

快速參考

任務程式庫主要函式
建立 PDFreportlabSimpleDocTemplate / canvas
讀取/合併/分割 PDFpypdfPdfReader / PdfWriter
提取表格pdfplumberpage.extract_tables()
密碼保護pypdfwriter.encrypt()
旋轉頁面pypdfpage.rotate()

相關技能