feat(文件归并): 归并PDF适配与解析逻辑
build.yaml / build (push) Successful in 48s

This commit is contained in:
xiaoqidun committed 2026-10-14 09:22:47 +08:00
1 parent b3c4bbc844
commit 961bc52038
43 files changed
+2283 -2594

No files matched your search

+50
View File
@@ -20,6 +20,7 @@ import (
"encoding/binary"
"math"
basegeom "github.com/xiaoqidun/ofdgo/internal/base/geom"
"github.com/xiaoqidun/pdfgo"
)
@@ -65,3 +66,52 @@ func ClipPathKey(ctx context.Context, path pdfgo.Path, matrix pdfgo.Matrix) ([32
hash.Sum(key[:0])
return key, nil
}
// ClipContainsBoundary 判断单一矩形裁剪是否完整覆盖对象边界,不近似曲线或斜边
// 入参: path PDF裁剪路径, matrix 页面变换, boundary OFD对象边界
// 返回: bool 是否可由对象边界代替裁剪
func ClipContainsBoundary(path pdfgo.Path, matrix pdfgo.Matrix, boundary basegeom.Box) bool {
if len(path.Text) != 0 || len(path.Segments) < 4 || len(path.Segments) > 6 || !finite(boundary.X) || !finite(boundary.Y) || !finite(boundary.W) || !finite(boundary.H) || boundary.W <= 0 || boundary.H <= 0 {
return false
}
var points [4]pdfgo.Point
for index := range 4 {
segment := path.Segments[index]
operator := "L"
if index == 0 {
operator = "M"
}
if segment.Operator != operator || len(segment.Points) != 1 {
return false
}
points[index] = matrix.Apply(segment.Points[0])
if !finite(points[index].X) || !finite(points[index].Y) {
return false
}
}
end := 4
if end < len(path.Segments) && path.Segments[end].Operator == "L" {
segment := path.Segments[end]
if len(segment.Points) != 1 || matrix.Apply(segment.Points[0]) != points[0] {
return false
}
end++
}
if end < len(path.Segments) {
segment := path.Segments[end]
if segment.Operator != "C" || len(segment.Points) != 0 {
return false
}
end++
}
if end != len(path.Segments) {
return false
}
a, b, c, d := points[0], points[1], points[2], points[3]
if !(a.Y == b.Y && b.X == c.X && c.Y == d.Y && d.X == a.X || a.X == b.X && b.Y == c.Y && c.X == d.X && d.Y == a.Y) {
return false
}
left, right := math.Min(a.X, c.X), math.Max(a.X, c.X)
top, bottom := math.Min(a.Y, c.Y), math.Max(a.Y, c.Y)
return left < right && top < bottom && boundary.X >= left && boundary.Y >= top && boundary.X+boundary.W <= right && boundary.Y+boundary.H <= bottom
}
+112
View File
@@ -15,6 +15,8 @@
package pdf
import (
"fmt"
"github.com/xiaoqidun/pdfgo"
)
@@ -35,3 +37,113 @@ func OutputColor(space *pdfgo.ColorSpace, values [4]float64) ([3]float64, error)
func NormalBlend(mode pdfgo.Name) bool {
return mode == "" || mode == "Normal" || mode == "Compatible"
}
// NativePaint 使用库层色料定义求值设备四色,不以备用色代替原生浓度
// 入参: paint 源画刷, space 设备四色空间, intent 渲染意图
// 返回: *pdfgo.Paint 原生画刷或nil, [4]bool 显式通道, error 色料定义错误
func NativePaint(paint pdfgo.Paint, space *pdfgo.ColorSpace, intent pdfgo.Name) (*pdfgo.Paint, [4]bool, error) {
if paint.Colorant == nil {
return nil, [4]bool{}, nil
}
result, err := paint.Colorant.Space.ResolveInGroup(paint.Colorant.Tints, &pdfgo.ColorantDevice{Space: space}, space, intent, false)
if err != nil || len(result.Alternates) != 0 {
return nil, [4]bool{}, err
}
return result.Process, result.ProcessMask, nil
}
// CompositeColor 将原始画刷变换到混合空间,渐变在源空间求值
// 入参: paint 画刷, point 页面坐标, space 混合空间, intent 渲染意图, conversion 设备转换函数
// 返回: [4]float64 混合分量, bool 是否着色, error 颜色错误
func CompositeColor(paint pdfgo.Paint, point pdfgo.Point, space *pdfgo.ColorSpace, intent pdfgo.Name, conversion pdfgo.ColorConversion) ([4]float64, bool, error) {
if paint.Shading != nil {
return [4]float64{}, false, &pdfgo.UnsupportedError{Feature: "local shading pattern compositing"}
}
if paint.Tiling != nil {
return [4]float64{}, false, &pdfgo.UnsupportedError{Feature: "local tiling pattern compositing"}
}
var values [4]float64
var source *pdfgo.ColorSpace
if paint.Function != nil {
g := paint.Function
if g.Bounds != nil {
inverse, ok := g.PatternMatrix.Inverse()
if !ok {
return values, false, fmt.Errorf("singular function shading bounds transform")
}
local := inverse.Apply(point)
if local.X < g.Bounds.XMin || local.X > g.Bounds.XMax || local.Y < g.Bounds.YMin || local.Y > g.Bounds.YMax {
return values, false, nil
}
}
inverse, ok := g.Matrix.Inverse()
if !ok {
return values, false, fmt.Errorf("singular function shading transform")
}
local := inverse.Apply(point)
source, intent = g.Space, g.Intent
if local.X < g.Domain.XMin || local.X > g.Domain.XMax || local.Y < g.Domain.YMin || local.Y > g.Domain.YMax {
if g.Background == nil {
return values, false, nil
}
values = *g.Background
} else {
var err error
values, err = g.ValuesAt(local)
if err != nil {
return values, false, err
}
}
} else if paint.Axial != nil || paint.Radial != nil {
var background *[4]float64
var bounds *pdfgo.Rectangle
var matrix pdfgo.Matrix
if g := paint.Axial; g != nil {
source, intent = g.Space, g.Intent
background, bounds, matrix = g.Background, g.Bounds, g.Matrix
} else {
g := paint.Radial
source, intent = g.Space, g.Intent
background, bounds, matrix = g.Background, g.Bounds, g.Matrix
}
if bounds != nil {
local := point
if matrix != (pdfgo.Matrix{}) {
inverse, ok := matrix.Inverse()
if !ok {
return values, false, fmt.Errorf("singular shading transform")
}
local = inverse.Apply(point)
}
if local.X < bounds.XMin || local.X > bounds.XMax || local.Y < bounds.YMin || local.Y > bounds.YMax {
return values, false, nil
}
}
t, visible := ShadingPosition(paint, point)
var err error
if !visible {
if background == nil {
return values, false, nil
}
values = *background
} else if paint.Axial != nil {
values, err = paint.Axial.ValuesAt(t)
} else {
values, err = paint.Radial.ValuesAt(t)
}
if err != nil {
return values, false, err
}
} else if paint.Space != nil {
values, source = paint.Values, paint.Space
} else if paint.CMYK != nil {
values, source = *paint.CMYK, &pdfgo.ColorSpace{Model: "DeviceCMYK"}
} else if paint.SourceSpace == "DeviceGray" {
values[0], source = paint.RGB[0], &pdfgo.ColorSpace{Model: "DeviceGray"}
} else {
copy(values[:], paint.RGB[:])
source = &pdfgo.ColorSpace{Model: "DeviceRGB"}
}
values, err := space.ConvertWith(values[:source.Components()], source, intent, conversion)
return values, true, err
}
+14
View File
@@ -93,3 +93,17 @@ func (s *NativeImage) NRGBA64At(x, y int) color.NRGBA64 {
rgb, _ := OutputColor(s.Space, values)
return color.NRGBA64{R: uint16(math.Round(rgb[0] * 65535)), G: uint16(math.Round(rgb[1] * 65535)), B: uint16(math.Round(rgb[2] * 65535)), A: uint16(math.Round(alpha * 65535))}
}
// ImageProcessColorants 识别可在四色设备上直接绘制的专色色料
// 入参: image PDF图像
// 返回: [4]bool 参与绘制的四色通道, bool 是否全部属于印刷原色, error 色空间错误
func ImageProcessColorants(image *pdfgo.Image) ([4]bool, bool, error) {
source, err := image.ColorantSpace()
if err != nil {
return [4]bool{}, false, err
}
space := &pdfgo.ColorSpace{Model: "DeviceCMYK"}
process := source.PrepareProcess(&pdfgo.ColorantDevice{Space: space}, space, false)
mask := process.Mask()
return mask, mask != ([4]bool{}), nil
}
+121
View File
@@ -0,0 +1,121 @@
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pdf
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"fmt"
"github.com/xiaoqidun/pdfgo"
)
// ReferenceCache 保存单次会话拥有的引用文档及页面,零值可用,须串行使用且使用后不应复制
// Close只释放缓存自行打开的阅读器,不关闭来源文档或调用方提供的阅读器
type ReferenceCache struct {
readers map[[32]byte]*pdfgo.Reader
streams map[*pdfgo.Stream]*pdfgo.Reader
pages map[referencePageKey]*pdfgo.Page
}
// referencePageKey 区分目标文档、索引和文本标签,避免重复遍历页面树
type referencePageKey struct {
reader *pdfgo.Reader
index int64
label string
labeled bool
}
// Resolve 解析引用目标,目标不可用时按PDF标准保留代理内容
// 入参: ctx 取消上下文, source 来源文档, reference 引用目标, fileResolver 外部文件读取, referenceResolver 调用方页面解析, warning 诊断回调
// 返回: *pdfgo.Page 目标页面,不可用时为空, error 取消或调用方解析错误
func (c *ReferenceCache) Resolve(ctx context.Context, source *pdfgo.Reader, reference pdfgo.ReferenceXObject, fileResolver pdfgo.FileResolver, referenceResolver pdfgo.ReferenceResolver, warning func(pdfgo.Diagnostic)) (*pdfgo.Page, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if referenceResolver != nil {
return referenceResolver(ctx, source, reference)
}
reader := c.streams[reference.File.Embedded]
if reader == nil {
if reference.File.Embedded == nil && fileResolver == nil {
return referenceProxy(ctx, fmt.Errorf("external reference file unavailable"), warning)
}
data, err := source.ReadFileData(ctx, reference.File, fileResolver)
if err != nil {
return referenceProxy(ctx, err, warning)
}
key := sha256.Sum256(data)
reader = c.readers[key]
if reader == nil {
reader, err = pdfgo.NewReaderWithOptions(bytes.NewReader(data), int64(len(data)), pdfgo.ReaderOptions{Warning: warning})
if err != nil {
return referenceProxy(ctx, err, warning)
}
if c.readers == nil {
c.readers = make(map[[32]byte]*pdfgo.Reader)
}
c.readers[key] = reader
}
if reference.File.Embedded != nil {
if c.streams == nil {
c.streams = make(map[*pdfgo.Stream]*pdfgo.Reader)
}
c.streams[reference.File.Embedded] = reader
}
}
key := referencePageKey{reader: reader, index: reference.PageIndex}
if reference.PageLabel != nil {
key.index, key.label, key.labeled = 0, *reference.PageLabel, true
}
if page := c.pages[key]; page != nil {
return page, ctx.Err()
}
page, err := reader.ResolveReferencePage(ctx, reference)
if err != nil {
return referenceProxy(ctx, err, warning)
}
if c.pages == nil {
c.pages = make(map[referencePageKey]*pdfgo.Page)
}
c.pages[key] = page
return page, ctx.Err()
}
// referenceProxy 记录目标不可用原因,不将合法的代理绘制视为转换失败
// 入参: ctx 取消上下文, cause 目标不可用原因, warning 诊断回调
// 返回: *pdfgo.Page 空目标, error 取消错误
func referenceProxy(ctx context.Context, cause error, warning func(pdfgo.Diagnostic)) (*pdfgo.Page, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if errors.Is(cause, context.Canceled) || errors.Is(cause, context.DeadlineExceeded) {
return nil, cause
}
if warning != nil {
warning(pdfgo.Diagnostic{Message: "reference XObject proxy retained: " + cause.Error()})
}
return nil, nil
}
// Close 释放本次会话打开的引用文档并清空缓存,可重复调用,之后可重新解析
func (c *ReferenceCache) Close() {
for _, reader := range c.readers {
reader.Close()
}
c.readers, c.streams, c.pages = nil, nil, nil
}
+20 -3
View File
@@ -48,11 +48,11 @@ func ShadingColorantSpace(paint pdfgo.Paint) *pdfgo.ColorantSpace {
// 返回: *ShadingColorants 独立采样状态,不可原生映射时为nil
func PrepareShadingColorants(paint pdfgo.Paint, space *pdfgo.ColorSpace, softMask bool) *ShadingColorants {
colorants := ShadingColorantSpace(paint)
Process := colorants.PrepareProcess(&pdfgo.ColorantDevice{Space: space}, space, softMask)
if Process == nil || Process.Mask() == ([4]bool{}) {
process := colorants.PrepareProcess(&pdfgo.ColorantDevice{Space: space}, space, softMask)
if process == nil || process.Mask() == ([4]bool{}) {
return nil
}
s := &ShadingColorants{paint: paint, Process: Process, tints: make([]float64, len(colorants.Names))}
s := &ShadingColorants{paint: paint, Process: process, tints: make([]float64, len(colorants.Names))}
if paint.Mesh != nil {
s.mesh = paint.Mesh.NewSampler()
}
@@ -94,3 +94,20 @@ func (s *ShadingColorants) MeshAt(patch int, u, v float64) ([4]float64, error) {
}
return s.Process.Convert(s.tints)
}
// ShadingPosition 计算渐变参数,未延伸区域及不存在非负圆半径的位置不着色
// 入参: paint 渐变画刷, point 页面坐标
// 返回: float64 归一化参数, bool 是否着色
func ShadingPosition(paint pdfgo.Paint, point pdfgo.Point) (float64, bool) {
var geometry pdfgo.GradientPosition
var err error
if g := paint.Axial; g != nil {
geometry, err = g.PreparePosition()
} else {
geometry, err = paint.Radial.PreparePosition()
}
if err != nil {
return 0, false
}
return geometry.PositionAt(point)
}