[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+154 -65
View File
@@ -2,91 +2,180 @@
id: wiki-2026-0508-pdf-format
title: PDF Format
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-PDFF-001]
aliases: [Portable Document Format, ISO 32000, PDF/A]
duplicate_of: none
source_trust_level: A
confidence_score: 0.94
tags: [auto-reinforced, pdf, document-standard, layout-preservation, digital-paper, cross-platform]
confidence_score: 0.9
verification_status: applied
tags: [pdf, document, format, parsing, generation]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: pypdf
---
# [[PDF-Format|PDF-Format]]
# PDF Format
## 📌 한 줄 통찰 (The Karpathy Summary)
> "디지털 종이의 표준: 어떤 운영체제, 어떤 기기에서 열어도 글꼴, 이미지, 레이아웃이 단 1픽셀의 오차 없이 똑같이 보이게 보장하며, 수정은 어렵지만 영구 보존과 배포에는 최적인 '박제된 문서'."
## 한 줄
> **"매 cross-reference table 의 random-access 의 binary container"**. 매 Adobe (1993) 의 PostScript-derived 의 ISO 32000 의 standardize 의 page-fixed-layout 의 dominant interchange format. 매 2026 년 의 PDF/A-4 (archival) + PDF 2.0 의 modern variant 의 LLM-extraction 의 challenge 의 source (no semantic structure 의 guarantee).
## 📖 구조화된 지식 (Synthesized Content)
PDF(Portable Document Format)는 어도비에서 개발한 장치 독립형 문서 형식입니다.
## 매 핵심
1. **특징**:
* **Fixed Layout**: 생성 시점의 디자인을 그대로 유지. (UX와 연결)
* **Encapsulation**: 글꼴, 이미지, 벡터 그래픽을 파일 내부에 포함. ([[Modularity|Modularity]]적 접근)
* **Security**: 암호화, 디지털 서명, 편집 방지 기능 제공.
2. **왜 중요한가?**:
* 계약서, 매뉴얼, 학술 논문 등 '문서의 무결성'과 '정확한 전달'이 생명인 영역에서의 글로벌 표준이기 때문임. ([[Global-Standard|Global-Standard]]와 연결)
### 매 file 구조
1. **Header**`%PDF-2.0` (또는 1.x).
2. **Body** — sequence of indirect objects (`N G obj ... endobj`).
3. **Cross-reference table** (`xref`) — byte offset of each object.
4. **Trailer** — root + info + size + xref offset.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 내용을 추출(Scraping)하기 어려운 '죽은 데이터 정책'으로 불려왔으나, 현대 정책은 지능형 OCR과 레이아웃 분석 AI 정책을 통해 PDF 속 데이터를 완벽하게 구조화된 지식 정책으로 불러오는 '동적 지식 추출 정책'이 가능해짐(RL Update). ([[Optical-Character-Recognition|Optical-Character-Recognition]]와 연결)
- **정책 변화(RL Update)**: 단순히 보기만 하는 파일을 넘어, AI가 PDF와 대화(Chat with PDF)하여 요약하고 질문에 답하는 '대화형 인터페이스 정책'이 지식 작업의 새로운 표준 정책이 됨.
### 매 object types
- Boolean, Number, String (literal `()` or hex `<>`), Name (`/Name`), Array, Dictionary, Stream (filtered binary).
- Page tree (Catalog → Pages → Page) + Resources (Font, XObject, etc.).
## 🔗 지식 연결 (Graph)
- [[Global-Standard|Global-Standard]], [[Optical-Character-Recognition|Optical-Character-Recognition]], [[Documentation-Strategy|Documentation-Strategy]], [[Hardware|Hardware]], [[Efficiency|Efficiency]]
- **Modern Tech/Tools**: Adobe Acrobat, PDF.js, PDF-lib, LayoutLM.
---
### 매 응용
1. Text/table extraction (LLM 의 RAG ingest).
2. Form fill (AcroForm / XFA).
3. Digital signature (PAdES).
4. Print fidelity (PDF/X for press).
5. Archive (PDF/A — embed fonts, no encryption).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Text extraction (pypdf, 2026)
```python
from pypdf import PdfReader
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
reader = PdfReader("doc.pdf")
text = ""
for page in reader.pages:
text += page.extract_text() + "\n"
# pypdf 5.x: layout-mode option for column-aware
text = "\n".join(p.extract_text(extraction_mode="layout") for p in reader.pages)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Better extraction with pdfplumber (preserves layout)
```python
import pdfplumber
**선택 A를 써야 할 때:**
- *(TODO)*
with pdfplumber.open("doc.pdf") as pdf:
for page in pdf.pages:
# Tables
for table in page.extract_tables():
print(table)
# Words with bbox
for word in page.extract_words():
print(word['text'], word['x0'], word['top'])
```
**선택 B를 써야 할 때:**
- *(TODO)*
### LLM-grade extraction with Unstructured (2026)
```python
from unstructured.partition.pdf import partition_pdf
**기본값:**
> *(TODO)*
elements = partition_pdf(
filename="doc.pdf",
strategy="hi_res", # uses layout model
infer_table_structure=True,
extract_images_in_pdf=True,
)
# Each element: Title, NarrativeText, Table, Image
```
## ❌ 안티패턴 (Anti-Patterns)
### Generate PDF (reportlab)
```python
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
c = canvas.Canvas("out.pdf", pagesize=A4)
c.setFont("Helvetica-Bold", 16)
c.drawString(72, 800, "Invoice #1234")
c.setFont("Helvetica", 10)
for i, line in enumerate(items):
c.drawString(72, 760 - i*14, line)
c.showPage()
c.save()
```
### Modern HTML→PDF (Playwright, replaces wkhtmltopdf)
```python
from playwright.async_api import async_playwright
async def html_to_pdf(html, out):
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.set_content(html)
await page.pdf(path=out, format="A4", print_background=True)
await browser.close()
```
### Sign PDF (PAdES, pyhanko)
```python
from pyhanko.sign import signers, fields
from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter
with open("input.pdf", "rb") as inf:
w = IncrementalPdfFileWriter(inf)
fields.append_signature_field(w, sig_field_spec=fields.SigFieldSpec("Sig1", box=(50, 50, 200, 100)))
signer = signers.SimpleSigner.load("cert.pem", "key.pem")
with open("signed.pdf", "wb") as out:
signers.sign_pdf(w, signers.PdfSignatureMetadata(field_name="Sig1"), signer=signer, output=out)
```
### Repair / linearize (qpdf CLI)
```bash
qpdf --linearize input.pdf output.pdf
qpdf --object-streams=generate --compress-streams=y input.pdf small.pdf
qpdf --check input.pdf # validate xref + structure
```
### Encrypted PDF
```python
from pypdf import PdfWriter
writer = PdfWriter(clone_from="doc.pdf")
writer.encrypt(user_password="user", owner_password="owner", algorithm="AES-256")
with open("encrypted.pdf", "wb") as f:
writer.write(f)
```
## 매 결정 기준
| 상황 | Tool |
|---|---|
| Text extraction (simple) | pypdf 5.x |
| Layout / tables | pdfplumber |
| LLM RAG ingest | Unstructured + hi_res / Marker / Docling |
| Generation (reports) | reportlab / WeasyPrint |
| HTML → PDF (modern) | Playwright (Chrome headless) |
| Forms / signing | pyhanko + qpdf |
| Repair / optimize | qpdf, mutool |
**기본값**: 매 ingest → Unstructured (layout-aware), 매 generate → Playwright (HTML).
## 🔗 Graph
- 부모: [[Document Format]] · [[ISO Standards]]
- 변형: [[PDF/A]] · [[PDF/X]] · [[XFA]]
- 응용: [[RAG Ingestion]] · [[Document AI]] · [[Digital Signature]]
- Adjacent: [[PostScript]] · [[OCR]] · [[Layout Analysis]]
## 🤖 LLM 활용
**언제**: 매 form-filled PDF 의 question. 매 extraction tool 의 selection. 매 schema mapping.
**언제 X**: 매 binary blob 의 direct edit 의 LLM 의 X. 매 spec-conformant tool 의 use.
## ❌ 안티패턴
- **Regex-based PDF parsing**: 매 binary + xref 의 fragile. 매 lib 의 사용.
- **Single extraction strategy**: 매 scanned PDF 의 OCR fallback. 매 hi_res strategy.
- **No PDF/A for archive**: 매 font 의 missing 의 future render fail.
## 🧪 검증 / 중복
- Verified (ISO 32000-2:2020, pypdf docs, Unstructured docs, qpdf manual).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — PDF structure + 2026 extraction/generation toolchain |