PDF 基础层

概述

pdf 包(Layer 1)提供底层 PDF 基础功能。大多数用户仅需使用该包中的颜色函数 — 其余部分由布局引擎内部使用。

import "github.com/gpdf-dev/gpdf/pdf"

颜色

颜色是 pdf 包中最常用的类型。

颜色构造函数

// RGB (float values 0.0 – 1.0)
pdf.RGB(1.0, 0.5, 0.0)     // Orange

// Hex (uint32)
pdf.RGBHex(0xFF6B6B)       // Coral
pdf.RGBHex(0x1A237E)       // Dark blue

// Grayscale (0.0 = black, 1.0 = white)
pdf.Gray(0.0)              // Black
pdf.Gray(0.5)              // Medium gray
pdf.Gray(1.0)              // White

// CMYK (for print)
pdf.CMYK(0, 1, 1, 0)      // Red in CMYK

预定义颜色

pdf.Black    // Gray(0)
pdf.White    // Gray(1)
pdf.Red      // RGB(1, 0, 0)
pdf.Green    // RGB(0, 1, 0)
pdf.Blue     // RGB(0, 0, 1)
pdf.Yellow   // RGB(1, 1, 0)
pdf.Cyan     // RGB(0, 1, 1)
pdf.Magenta  // RGB(1, 0, 1)

颜色使用

颜色与 TextColor()BgColor() 文本选项一起使用:

c.Text("Red on yellow",
    template.TextColor(pdf.Red),
    template.BgColor(pdf.Yellow),
)

以及表格/分割线选项:

// Table header
template.TableHeaderStyle(
    template.TextColor(pdf.White),
    template.BgColor(pdf.RGBHex(0x1A237E)),
)

// Line color
template.LineColor(pdf.Blue)

颜色空间

type ColorSpace int

const (
    ColorSpaceRGB  ColorSpace = iota
    ColorSpaceGray
    ColorSpaceCMYK
)

Color 类型

type Color struct {
    R, G, B float64     // RGB components (0.0 – 1.0)
    A       float64     // Alpha or K (for CMYK)
    Space   ColorSpace
}

Writer(高级)

PDF Writer 处理底层 PDF 对象创建。大多数用户不需要直接使用。

type Writer struct {}

func NewWriter(w io.Writer) *Writer
func (pw *Writer) AllocObject() ObjectRef
func (pw *Writer) WriteObject(ref ObjectRef, obj Object) error
func (pw *Writer) RegisterFont(name string, data []byte) error
func (pw *Writer) AddPage(page *PageContent) error
func (pw *Writer) Close() error
func (pw *Writer) SetDocumentInfo(info DocumentInfo)

PDF 对象(高级)

底层 PDF 对象类型:

// Scalar types
type Name string
type LiteralString string
type HexString string
type Integer int64
type Real float64
type Boolean bool
type Null struct{}

// Composite types
type Dict map[string]Object
type Array []Object

// Stream (content, images, fonts)
type Stream struct {
    Data       []byte
    Dictionary Dict
}

// Object reference
type ObjectRef struct {
    Number     int
    Generation int
}

字体包(高级)

pdf/font 子包处理 TrueType 字体解析和子集化:

import "github.com/gpdf-dev/gpdf/pdf/font"

// Parse a TrueType font
ttf, err := font.ParseTrueType(data)

// Get font name and metrics
name := ttf.Name()
metrics := ttf.Metrics()  // Ascender, Descender, CapHeight, XHeight

// Create a subset with only used glyphs
subset, err := ttf.Subset(runes)

// Measure text width
width := font.MeasureString(ttf, "Hello", 12.0)

// Break text into lines
lines := font.LineBreak(ttf, text, 12.0, maxWidth)

架构

Layer 3: template ─── Builder API, JSON Schema, Components
    │
    ▼
Layer 2: document ─── Nodes, Box Model, Layout Engine
    │
    ▼
Layer 1: pdf ──────── Writer, Streams, Fonts, Images
    │
    ▼
          io.Writer (file, HTTP response, buffer...)

每一层仅依赖其下方的层 — 绝不向上依赖。