From 86330dddd714a947ca513b9ced2a766c78e6f302 Mon Sep 17 00:00:00 2001 From: xiaoqidun Date: Thu, 24 Sep 2026 16:18:38 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E8=BD=AC=E6=8D=A2=E8=83=BD=E5=8A=9B):=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9EPDF=E8=A7=A3=E6=9E=90=E3=80=81=E5=8F=AF?= =?UTF-8?q?=E7=BC=96=E8=BE=91OFD=E8=BD=AC=E6=8D=A2=E5=8F=8AWebUI=E6=89=93?= =?UTF-8?q?=E5=BC=80=E8=83=BD=E5=8A=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets/webui/index.html | 2 +- assets/webui/ofdgo.js | 22 ++- assets/webui/ofdgo.json | 3 +- go.mod | 3 +- go.sum | 6 +- internal/webui/wasm.go | 20 +++ ofdgo_pdf.go | 246 +++++++++++++++++++++++++++++++ ofdgo_pdf_object.go | 316 ++++++++++++++++++++++++++++++++++++++++ 8 files changed, 606 insertions(+), 12 deletions(-) create mode 100644 ofdgo_pdf.go create mode 100644 ofdgo_pdf_object.go diff --git a/assets/webui/index.html b/assets/webui/index.html index c8767e2..62c7be5 100644 --- a/assets/webui/index.html +++ b/assets/webui/index.html @@ -12,7 +12,7 @@
- +
diff --git a/assets/webui/ofdgo.js b/assets/webui/ofdgo.js index 59fc7eb..164561a 100644 --- a/assets/webui/ofdgo.js +++ b/assets/webui/ofdgo.js @@ -2916,7 +2916,7 @@ async function openOFDFromDrop(event) { return; } const file = event.dataTransfer.files[0]; - if (file && isOFDFile(file)) { + if (file && isDocumentFile(file)) { await requestLocalFontsBeforeOpen(); } await openOFD(file); @@ -3317,7 +3317,7 @@ async function openOFD(file) { if (!file) { return; } - if (!isOFDFile(file)) { + if (!isDocumentFile(file)) { el.ofdInput.value = ""; showError(new Error("选择 OFD 文件"), !state.doc); return; @@ -3330,12 +3330,20 @@ async function openOFD(file) { const openSeq = ++state.openSeq; setBusy(true, "正在读取文档", 10, STATUS.opening); try { - const bytes = new Uint8Array(await file.arrayBuffer()); + let bytes = new Uint8Array(await file.arrayBuffer()); if (openSeq !== state.openSeq) { return; } + if (/\.pdf$/i.test(file.name || "")) { + setProgress("正在转换 PDF", 25); + await ensureWASM(); + if (openSeq !== state.openSeq) return; + const converted = await callWASM("ofdgoConvertPDF", bytes); + if (openSeq !== state.openSeq) return; + bytes = converted.bytes; + } state.ofdBytes = bytes; - state.fileName = file.name || "ofdgo.ofd"; + state.fileName = (file.name || "ofdgo.ofd").replace(/\.pdf$/i, ".ofd"); state.editing = false; state.composite = null; state.annotationCreate = null; @@ -3368,14 +3376,14 @@ async function openOFD(file) { await openDocument({ pageIndex: 0, resetScroll: true, openSeq }); } catch (err) { if (openSeq === state.openSeq) { - showError(err, true); + showError(err, !state.doc); setBusy(false); } } } -function isOFDFile(file) { - return /\.ofd$/i.test(file.name || ""); +function isDocumentFile(file) { + return /\.(ofd|pdf)$/i.test(file.name || ""); } async function openSelectedFonts(event) { diff --git a/assets/webui/ofdgo.json b/assets/webui/ofdgo.json index 44f14c0..3dc1cb7 100644 --- a/assets/webui/ofdgo.json +++ b/assets/webui/ofdgo.json @@ -11,7 +11,8 @@ { "action": "./", "accept": { - "application/ofd": [".ofd"] + "application/ofd": [".ofd"], + "application/pdf": [".pdf"] }, "launch_type": "multiple-clients" } diff --git a/go.mod b/go.mod index b30e978..964b852 100644 --- a/go.mod +++ b/go.mod @@ -6,9 +6,10 @@ require ( github.com/emmansun/gmsm v0.44.1 github.com/go-fonts/latin-modern v0.3.3 github.com/go-text/typesetting v0.3.5 - github.com/tdewolff/canvas v0.0.0-20260913163248-dd4999d1c76a + github.com/tdewolff/canvas v0.0.0-20260923214215-09804640d00c github.com/tdewolff/font v0.0.0-20260913163313-54f98bb59ee6 github.com/xiaoqidun/jbig2 v1.1.1 + github.com/xiaoqidun/pdfgo v0.0.0-20260924080829-a19c3fd78f51 golang.org/x/crypto v0.57.0 golang.org/x/image v0.46.0 golang.org/x/text v0.42.0 diff --git a/go.sum b/go.sum index 09f566e..374257a 100644 --- a/go.sum +++ b/go.sum @@ -48,8 +48,8 @@ github.com/srwiley/scanFT v0.0.0-20220128184157-0d1ee492111f h1:uLR2GaV0kWYZ3Ns3 github.com/srwiley/scanFT v0.0.0-20220128184157-0d1ee492111f/go.mod h1:LZwgIPG9X6nH6j5Ef+xMFspl6Hru4b5EJxzMfeqHYJY= github.com/srwiley/scanx v0.0.0-20190309010443-e94503791388 h1:ZdkidVdpLW13BQ9a+/3uerT2ezy9J7KQWH18JCfhDmI= github.com/srwiley/scanx v0.0.0-20190309010443-e94503791388/go.mod h1:C/WY5lmWfMtPFYYBTd3Lzdn4FTLr+RxlIeiBNye+/os= -github.com/tdewolff/canvas v0.0.0-20260913163248-dd4999d1c76a h1:Qxn+Q+tIBhRGMkWXOXhhOmJMlj7FbSmdMabXyAOtBzI= -github.com/tdewolff/canvas v0.0.0-20260913163248-dd4999d1c76a/go.mod h1:K9Ux3cwFtyAFRITZ46g7v+ORXgI3ENtQa5rL9yjNz5Y= +github.com/tdewolff/canvas v0.0.0-20260923214215-09804640d00c h1:eXJXpQAo8l0AdVnsjJctG38GlBnHnwHfhLOTLYxZYNE= +github.com/tdewolff/canvas v0.0.0-20260923214215-09804640d00c/go.mod h1:K9Ux3cwFtyAFRITZ46g7v+ORXgI3ENtQa5rL9yjNz5Y= github.com/tdewolff/font v0.0.0-20260913163313-54f98bb59ee6 h1:phNTWRYLLTlPpUgxkd6FDmWLlrOzpEpQAqq1ryLXYS8= github.com/tdewolff/font v0.0.0-20260913163313-54f98bb59ee6/go.mod h1:ipESUihcEdgRBhIwTRHmBTOMamccMQrp4iCxfa1aFws= github.com/tdewolff/minify/v2 v2.24.17 h1:6AbitfVyq0M7aW6i+XL7+49DeTQZwloOMs9O574arBg= @@ -60,6 +60,8 @@ github.com/tdewolff/test v1.0.12 h1:7F21DqIajswxuche0geHdrUZRCWE4oko4b7bcmkkrxk= github.com/tdewolff/test v1.0.12/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8= github.com/xiaoqidun/jbig2 v1.1.1 h1:SjliS9ZO0e9HX5oYUfBuXrfFsXhWricrSz+XY4zORDI= github.com/xiaoqidun/jbig2 v1.1.1/go.mod h1:8QonVWtENmh2kc6l+leqeGl7psb79DWlHDkCpdChjfQ= +github.com/xiaoqidun/pdfgo v0.0.0-20260924080829-a19c3fd78f51 h1:HOToanGdlILAjOAGQkH4XQDmGLwPoePBb3WSj3dSif4= +github.com/xiaoqidun/pdfgo v0.0.0-20260924080829-a19c3fd78f51/go.mod h1:/D0XHgfZ7xNhix95swpNaThpuqoJjVR5wIadogtR5pI= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= github.com/yuin/goldmark v1.8.5 h1:r6N5afV5qj/5S4UTch8agZHJ8UxNCMwX7WjkkJam2NA= diff --git a/internal/webui/wasm.go b/internal/webui/wasm.go index 25cafbf..e05e21f 100644 --- a/internal/webui/wasm.go +++ b/internal/webui/wasm.go @@ -156,6 +156,7 @@ func awaitExport(fn js.Value, args ...any) error { // RunWASM 注册浏览器WASM接口并阻塞运行 func RunWASM() { registerCallback("ofdgoOpen", openDocument) + registerCallback("ofdgoConvertPDF", convertPDFDocument) registerCallback("ofdgoConfigure", configureDocument) registerCallback("ofdgoDocumentInfo", documentInfo) registerCallback("ofdgoVerifySignatures", verifySignatures) @@ -311,6 +312,25 @@ func safeCall(fn func([]js.Value) (any, error), args []js.Value) (data any, err return fn(args) } +// convertPDFDocument 通过库转换PDF,不替换当前文档会话 +// 入参: args PDF数据 +// 返回: any OFD数据, error 错误信息 +func convertPDFDocument(args []js.Value) (any, error) { + if len(args) != 1 { + return nil, fmt.Errorf("missing PDF data") + } + data, err := bytesFromJS(args[0]) + if err != nil { + return nil, err + } + var output bytes.Buffer + _, err = ofdgo.ConvertPDF(context.Background(), bytes.NewReader(data), int64(len(data)), &output, ofdgo.PDFImportOptions{}) + if err != nil { + return nil, err + } + return successResult(map[string]any{"bytes": bytesToJS(output.Bytes())}), nil +} + // openDocument 打开OFD文档 // 入参: args 浏览器参数 // 返回: any 文档信息, error 错误信息 diff --git a/ofdgo_pdf.go b/ofdgo_pdf.go new file mode 100644 index 0000000..499c418 --- /dev/null +++ b/ofdgo_pdf.go @@ -0,0 +1,246 @@ +// 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 ofdgo + +import ( + "context" + "fmt" + "io" + "math" + "strconv" + "strings" + + "github.com/xiaoqidun/pdfgo" +) + +// PDFImportOptions 指定PDF转换的运行时后端与进度通知 +type PDFImportOptions struct { + Backends *RenderBackends + Progress func(int) error +} + +// PDFImportReport 汇总成功转换的页面和可编辑对象 +type PDFImportReport struct { + Pages int + TextObjects int + PathObjects int + ImageObjects int +} + +// pdfImporter 保存单次转换的对象与资源状态 +type pdfImporter struct { + reader *pdfgo.Reader + editor *Editor + report PDFImportReport + matrix pdfgo.Matrix + page int + fontIDs map[*pdfgo.Font]string + fontMetrics map[string]FontMetrics + cmykSpace string + objects []GraphicObject +} + +// ImportPDF 将PDF内容转换为独立OFD编辑文档,失败时不返回部分结果 +// 入参: ctx 取消上下文, source PDF数据, size 字节数, options 转换选项 +// 返回: *Editor 编辑文档, PDFImportReport 转换统计, error 错误信息 +func ImportPDF(ctx context.Context, source io.ReaderAt, size int64, options PDFImportOptions) (*Editor, PDFImportReport, error) { + if err := ctx.Err(); err != nil { + return nil, PDFImportReport{}, err + } + reader, err := pdfgo.NewReader(source, size) + if err != nil { + return nil, PDFImportReport{}, err + } + editor := NewEditor() + if options.Backends != nil { + editor.SetRenderBackends(*options.Backends) + } + importer := pdfImporter{reader: reader, editor: editor, fontIDs: map[*pdfgo.Font]string{}, fontMetrics: map[string]FontMetrics{}} + err = reader.WalkPages(ctx, func(index int, page *pdfgo.Page) error { + matrix, width, height := pdfPageMatrix(page) + importer.matrix = matrix + importer.page, err = editor.AddPage(width, height) + if err != nil { + return err + } + if err := reader.WalkPage(ctx, page, pdfgo.Visitor{Path: importer.path, Text: importer.text, Image: importer.image}); err != nil { + return fmt.Errorf("import PDF page %d: %w", index+1, err) + } + if _, err := editor.CopyObjects(importer.page, importer.objects, 0, 0); err != nil { + return fmt.Errorf("import PDF page %d: %w", index+1, err) + } + importer.objects = nil + importer.report.Pages++ + if options.Progress != nil { + return options.Progress(index + 1) + } + return ctx.Err() + }) + if err != nil { + return nil, PDFImportReport{}, err + } + if importer.report.Pages == 0 { + return nil, PDFImportReport{}, fmt.Errorf("PDF contains no pages") + } + return editor, importer.report, nil +} + +// ConvertPDF 将PDF转换并写入OFD,转换阶段失败时不写入目标 +// 入参: ctx 取消上下文, source PDF数据, size 字节数, output OFD输出, options 转换选项 +// 返回: PDFImportReport 转换统计, error 错误信息 +func ConvertPDF(ctx context.Context, source io.ReaderAt, size int64, output io.Writer, options PDFImportOptions) (PDFImportReport, error) { + editor, report, err := ImportPDF(ctx, source, size, options) + if err != nil { + return PDFImportReport{}, err + } + if err := ctx.Err(); err != nil { + return PDFImportReport{}, err + } + _, err = editor.WriteTo(output) + return report, err +} + +// pdfPageMatrix 将裁剪框、用户单位及页面旋转转换为OFD毫米坐标 +func pdfPageMatrix(page *pdfgo.Page) (pdfgo.Matrix, float64, float64) { + b := page.CropBox + scale := 25.4 / 72 * page.UserUnit + width, height := (b.XMax-b.XMin)*scale, (b.YMax-b.YMin)*scale + m := pdfgo.Matrix{scale, 0, 0, -scale, -b.XMin * scale, b.YMax * scale} + switch page.Rotation { + case 90: + m = pdfgo.Matrix{0, 1, -1, 0, height, 0}.Mul(m) + width, height = height, width + case 180: + m = pdfgo.Matrix{-1, 0, 0, -1, width, height}.Mul(m) + case 270: + m = pdfgo.Matrix{0, -1, 1, 0, 0, width}.Mul(m) + width, height = height, width + } + return m, width, height +} + +// pdfNumbers 按OFD数值格式序列化坐标 +func pdfNumbers(values ...float64) string { + parts := make([]string, len(values)) + for n, v := range values { + parts[n] = strconv.FormatFloat(v, 'g', -1, 64) + } + return strings.Join(parts, " ") +} + +// pdfBoundary 序列化对象边界 +func pdfBoundary(b Box) string { return pdfNumbers(b.X, b.Y, b.W, b.H) } + +// pdfBounds 计算点集合的包围框 +func pdfBounds(points []pdfgo.Point) Box { + if len(points) == 0 { + return Box{} + } + minX, minY, maxX, maxY := points[0].X, points[0].Y, points[0].X, points[0].Y + for _, p := range points { + minX = math.Min(minX, p.X) + minY = math.Min(minY, p.Y) + maxX = math.Max(maxX, p.X) + maxY = math.Max(maxY, p.Y) + } + return Box{minX, minY, math.Max(maxX-minX, 1e-6), math.Max(maxY-minY, 1e-6)} +} + +// color 保留设备色彩分量并复用文档颜色空间 +func (p *pdfImporter) color(paint pdfgo.Paint) *FillColor { + alpha := int(math.Round(paint.Alpha * 255)) + if paint.CMYK != nil { + if p.cmykSpace == "" { + p.cmykSpace = p.editor.nextID() + p.editor.resources = append(p.editor.resources, editorResource{space: &ColorSpace{ID: p.cmykSpace, Type: "CMYK", BitsPerComponent: 16}}) + } + v := paint.CMYK + return &FillColor{ColorSpace: p.cmykSpace, Value: pdfNumbers(math.Round(v[0]*65535), math.Round(v[1]*65535), math.Round(v[2]*65535), math.Round(v[3]*65535)), Alpha: &alpha} + } + return &FillColor{Value: pdfNumbers(math.Round(paint.RGB[0]*255), math.Round(paint.RGB[1]*255), math.Round(paint.RGB[2]*255)), Alpha: &alpha} +} + +// pathData 将PDF路径转换为相对对象边界的OFD路径 +func (p *pdfImporter) pathData(path pdfgo.Path, origin Box) string { + var parts []string + for _, segment := range path.Segments { + parts = append(parts, segment.Operator) + for _, point := range segment.Points { + point = p.matrix.Apply(point) + parts = append(parts, pdfNumbers(point.X-origin.X, point.Y-origin.Y)) + } + } + return strings.Join(parts, " ") +} + +// clips 保持裁剪路径的交集,不随对象CTM重复变换 +func (p *pdfImporter) clips(paths []pdfgo.Path, origin Box) *Clips { + if len(paths) == 0 { + return nil + } + flag := false + clips := &Clips{TransFlag: &flag} + for _, path := range paths { + var points []pdfgo.Point + for _, segment := range path.Segments { + for _, point := range segment.Points { + points = append(points, p.matrix.Apply(point)) + } + } + box := pdfBounds(points) + rule := "NonZero" + if path.EvenOdd { + rule = "Even-Odd" + } + clips.Clip = append(clips.Clip, Clip{Area: []ClipArea{{Path: []PathObject{{Boundary: pdfBoundary(Box{box.X - origin.X, box.Y - origin.Y, box.W, box.H}), AbbreviatedData: p.pathData(path, box), Rule: rule}}}}}) + } + return clips +} + +// path 添加独立可编辑路径 +func (p *pdfImporter) path(mark pdfgo.PathMark) error { + var points []pdfgo.Point + for _, segment := range mark.Path.Segments { + for _, point := range segment.Points { + points = append(points, p.matrix.Apply(point)) + } + } + if len(points) == 0 { + return fmt.Errorf("empty PDF painted path") + } + box := pdfBounds(points) + scale := math.Hypot(p.matrix[0], p.matrix[1]) + if mark.Stroke { + margin := mark.Style.LineWidth * scale / 2 * math.Max(1, mark.Style.MiterLimit) + box = Box{box.X - margin, box.Y - margin, box.W + 2*margin, box.H + 2*margin} + } + strokeColor := StrokeColor(*p.color(mark.Style.Stroke)) + object := PathObject{Boundary: pdfBoundary(box), AbbreviatedData: p.pathData(mark.Path, box), Fill: &mark.Fill, Stroke: &mark.Stroke, FillColor: p.color(mark.Style.Fill), StrokeColor: &strokeColor, LineWidth: mark.Style.LineWidth * scale, Cap: []string{"Butt", "Round", "Square"}[mark.Style.Cap], Join: []string{"Miter", "Round", "Bevel"}[mark.Style.Join], MiterLimit: mark.Style.MiterLimit, Clips: p.clips(mark.Style.Clips, box)} + if mark.Path.EvenOdd { + object.Rule = "Even-Odd" + } + if len(mark.Style.Dash) > 0 { + values := make([]float64, len(mark.Style.Dash)) + for n, v := range mark.Style.Dash { + values[n] = v * scale + } + object.DashPattern = pdfNumbers(values...) + phase := mark.Style.DashPhase * scale + object.DashOffset = &phase + } + p.objects = append(p.objects, GraphicObject{Type: "PathObject", PathObject: object}) + p.report.PathObjects++ + return nil +} diff --git a/ofdgo_pdf_object.go b/ofdgo_pdf_object.go new file mode 100644 index 0000000..0ec681e --- /dev/null +++ b/ofdgo_pdf_object.go @@ -0,0 +1,316 @@ +// 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 ofdgo + +import ( + "bytes" + "encoding/binary" + "fmt" + "image" + "image/color" + "image/png" + "math" + "strconv" + "unicode/utf16" + "unicode/utf8" + + "github.com/xiaoqidun/pdfgo" +) + +// image 转换图像样本,不将整页或其他对象栅格化 +func (p *pdfImporter) image(mark pdfgo.ImageMark) error { + source := mark.Image + filter, err := p.reader.Resolve(source.Stream.Dictionary["Filter"]) + if err != nil { + return err + } + jpegOriginal := filter == pdfgo.Name("DCTDecode") && len(source.Decode) == 0 && !source.ImageMask && source.ColorSpace != pdfgo.Name("DeviceCMYK") + if source.Mask != nil || source.SoftMask != nil { + return &pdfgo.UnsupportedError{Feature: "image mask conversion"} + } + if !source.ImageMask && source.ColorSpace != pdfgo.Name("DeviceRGB") && source.ColorSpace != pdfgo.Name("DeviceGray") && source.ColorSpace != pdfgo.Name("DeviceCMYK") { + return &pdfgo.UnsupportedError{Feature: "image color management"} + } + if source.Stream.Dictionary["Intent"] != nil || source.Stream.Dictionary["SMaskInData"] != nil { + return &pdfgo.UnsupportedError{Feature: "image rendering attributes"} + } + decoded, err := source.DecodeSamples() + if err != nil { + return err + } + if len(source.Decode) > 0 { + components := 1 + if source.ColorSpace == pdfgo.Name("DeviceRGB") { + components = 3 + } else if source.ColorSpace == pdfgo.Name("DeviceCMYK") { + components = 4 + } + if len(source.Decode) != components*2 { + return fmt.Errorf("invalid PDF image field %q", "Decode") + } + ranges := make([]float64, len(source.Decode)) + for n, v := range source.Decode { + switch v := v.(type) { + case pdfgo.Integer: + ranges[n] = float64(v) + case pdfgo.Real: + ranges[n] = float64(v) + default: + return fmt.Errorf("invalid PDF image field %q", "Decode") + } + } + adjusted := image.NewNRGBA64(image.Rect(0, 0, source.Width, source.Height)) + for y := 0; y < source.Height; y++ { + for x := 0; x < source.Width; x++ { + if components == 4 { + cmyk, ok := decoded.At(x, y).(color.CMYK) + if !ok { + return fmt.Errorf("invalid CMYK image samples") + } + values := []uint8{cmyk.C, cmyk.M, cmyk.Y, cmyk.K} + for c := range values { + value := ranges[2*c] + float64(values[c])/255*(ranges[2*c+1]-ranges[2*c]) + values[c] = uint8(math.Round(math.Max(0, math.Min(1, value)) * 255)) + } + adjusted.Set(x, y, color.CMYK{C: values[0], M: values[1], Y: values[2], K: values[3]}) + continue + } + r, g, b, _ := decoded.At(x, y).RGBA() + values := []uint32{r, g, b} + for c := range values { + index := c + if components == 1 { + index = 0 + } + value := ranges[2*index] + float64(values[c])/65535*(ranges[2*index+1]-ranges[2*index]) + values[c] = uint32(math.Round(math.Max(0, math.Min(1, value)) * 65535)) + } + adjusted.SetNRGBA64(x, y, color.NRGBA64{R: uint16(values[0]), G: uint16(values[1]), B: uint16(values[2]), A: 65535}) + } + } + decoded = adjusted + } + if source.ImageMask { + if mark.Style.Fill.CMYK != nil { + return &pdfgo.UnsupportedError{Feature: "CMYK stencil image"} + } + stencil := image.NewNRGBA64(image.Rect(0, 0, source.Width, source.Height)) + fill := mark.Style.Fill.RGB + for y := 0; y < source.Height; y++ { + for x := 0; x < source.Width; x++ { + gray, _, _, _ := decoded.At(x, y).RGBA() + stencil.SetNRGBA64(x, y, color.NRGBA64{ + R: uint16(math.Round(fill[0] * 65535)), + G: uint16(math.Round(fill[1] * 65535)), + B: uint16(math.Round(fill[2] * 65535)), + A: uint16(65535 - gray), + }) + } + } + decoded = stencil + } + var encoded bytes.Buffer + if jpegOriginal { + encoded.Write(source.Stream.Data) + } else { + if err := png.Encode(&encoded, decoded); err != nil { + return err + } + } + id, err := p.editor.AddImage(encoded.Bytes()) + if err != nil { + return err + } + m := p.matrix.Mul(mark.Matrix).Mul(pdfgo.Matrix{1, 0, 0, -1, 0, 1}) + box := pdfBounds([]pdfgo.Point{m.Apply(pdfgo.Point{}), m.Apply(pdfgo.Point{X: 1}), m.Apply(pdfgo.Point{Y: 1}), m.Apply(pdfgo.Point{X: 1, Y: 1})}) + alpha := int(math.Round(mark.Style.Fill.Alpha * 255)) + object := ImageObject{Boundary: pdfBoundary(box), ResourceID: id, CTM: pdfNumbers(m[0], m[1], m[2], m[3], m[4]-box.X, m[5]-box.Y), Alpha: &alpha, Clips: p.clips(mark.Style.Clips, box)} + p.objects = append(p.objects, GraphicObject{Type: "ImageObject", ImageObject: object}) + p.report.ImageObjects++ + return nil +} + +// text 保留原字体、字形编号与逐字基线,不重新塑形 +func (p *pdfImporter) text(mark pdfgo.TextMark) error { + font := mark.Font + if len(font.Program) == 0 { + return &pdfgo.UnsupportedError{Feature: "text without embedded font"} + } + if font.ProgramType != "FontFile2" && font.ProgramType != "OpenType" { + return &pdfgo.UnsupportedError{Feature: "font program " + string(font.ProgramType)} + } + id := p.fontIDs[font] + if id == "" { + var err error + program, err := pdfFontProgram(font) + if err != nil { + return err + } + id, err = p.editor.AddFont(FontFile{Name: font.Name + ".ttf", Data: program}, 0) + if err != nil { + return err + } + p.fontIDs[font] = id + } + metrics := p.fontMetrics[id] + if metrics == nil { + if p.editor.backends.Fonts == nil { + return fmt.Errorf("PDF font backend unavailable") + } + var err error + metrics, err = p.editor.backends.Fonts.OpenFont(p.editor.fonts[id].Data) + if err != nil { + return err + } + p.fontMetrics[id] = metrics + } + outline, ok := metrics.(FontOutlines) + if !ok { + return fmt.Errorf("PDF font backend does not provide glyph outlines") + } + const unit = 25.4 / 72 + m := p.matrix.Mul(mark.Matrix).Mul(pdfgo.Matrix{1 / unit, 0, 0, -1 / unit, 0, 0}) + var points []pdfgo.Point + object := TextObject{Font: id, Size: mark.Size * unit, HScale: mark.HorizontalScale} + position := 0 + for n, glyph := range mark.Glyphs { + gid := glyph.ID + if !glyph.HasID { + if utf8.RuneCountInString(glyph.Text) != 1 { + return &pdfgo.UnsupportedError{Feature: "simple font glyph ligature mapping"} + } + char, _ := utf8.DecodeRuneInString(glyph.Text) + gid = metrics.GlyphIndex(char) + if gid == 0 && char != 0 { + return fmt.Errorf("missing PDF glyph for %U", char) + } + } + if gid >= metrics.NumGlyphs() { + return fmt.Errorf("PDF glyph index outside embedded font") + } + origin := mark.Positions[n] + object.TextCode = append(object.TextCode, TextCode{X: pdfNumbers(origin.X * unit), Y: pdfNumbers(-origin.Y * unit), Value: glyph.Text}) + object.CGTransform = append(object.CGTransform, CGTransform{CodePosition: position, CodeCount: utf8.RuneCountInString(glyph.Text), GlyphCount: 1, Glyphs: strconv.Itoa(int(gid))}) + position += utf8.RuneCountInString(glyph.Text) + path, err := outline.GlyphOutline(gid, object.Size) + if err != nil { + return err + } + bounds, err := path.Bounds() + if err != nil { + return err + } + for _, point := range []pdfgo.Point{{X: bounds.X, Y: bounds.Y}, {X: bounds.X + bounds.W, Y: bounds.Y}, {X: bounds.X, Y: bounds.Y + bounds.H}, {X: bounds.X + bounds.W, Y: bounds.Y + bounds.H}} { + points = append(points, m.Apply(pdfgo.Point{X: origin.X*unit + point.X*mark.HorizontalScale, Y: -origin.Y*unit + point.Y})) + } + } + box := pdfBounds(points) + fill, stroke, visible := mark.Mode == 0 || mark.Mode == 2, mark.Mode == 1 || mark.Mode == 2, mark.Mode != 3 + if stroke { + margin := mark.Style.LineWidth * unit * math.Hypot(m[0], m[1]) / 2 * math.Max(1, mark.Style.MiterLimit) + box = Box{box.X - margin, box.Y - margin, box.W + 2*margin, box.H + 2*margin} + color := StrokeColor(*p.color(mark.Style.Stroke)) + object.StrokeColor = &color + object.LineWidth = mark.Style.LineWidth * unit + object.Join = []string{"Miter", "Round", "Bevel"}[mark.Style.Join] + object.MiterLimit = mark.Style.MiterLimit + if len(mark.Style.Dash) > 0 { + return &pdfgo.UnsupportedError{Feature: "dashed text stroke"} + } + } + object.Boundary = pdfBoundary(box) + object.CTM = pdfNumbers(m[0], m[1], m[2], m[3], m[4]-box.X, m[5]-box.Y) + object.Fill = &fill + object.Stroke = &stroke + object.Visible = &visible + object.FillColor = p.color(mark.Style.Fill) + object.Clips = p.clips(mark.Style.Clips, box) + p.objects = append(p.objects, GraphicObject{Type: "TextObject", TextObject: object}) + p.report.TextObjects++ + return nil +} + +// pdfFontProgram 为PDF子集字体补齐封装表,不改动字形轮廓、编号或原始度量 +func pdfFontProgram(source *pdfgo.Font) ([]byte, error) { + tables, err := fontFileTables(source.Program, 0) + if err != nil { + return nil, err + } + if len(tables["head"]) < 54 || len(tables["maxp"]) < 6 || len(tables["hhea"]) < 36 || len(tables["hmtx"]) == 0 { + return nil, fmt.Errorf("embedded PDF font lacks required metrics") + } + count := binary.BigEndian.Uint16(tables["maxp"][4:6]) + if count == 0 { + return nil, fmt.Errorf("embedded PDF font has no glyphs") + } + changed := false + if len(tables["cmap"]) == 0 { + mapping := map[rune]uint16{} + for code := range source.Unicode { + glyphs, err := source.Decode([]byte(code)) + if err != nil { + return nil, err + } + if len(glyphs) != 1 || !glyphs[0].HasID { + return nil, &pdfgo.UnsupportedError{Feature: "font without explicit glyph mapping"} + } + glyph := glyphs[0] + if utf8.RuneCountInString(glyph.Text) == 1 { + char, _ := utf8.DecodeRuneInString(glyph.Text) + if _, exists := mapping[char]; !exists { + mapping[char] = glyph.ID + } + } + } + addPackedGlyphMapping(mapping, count) + tables["cmap"] = buildCmapTable(count, mapping) + changed = true + } + if len(fontNamesFromTable(tables["name"])) == 0 { + name := utf16.Encode([]rune(source.Name)) + if len(name) == 0 || len(name) > 32767 { + return nil, fmt.Errorf("PDF font name missing or excessive") + } + data := make([]byte, 42+len(name)*2) + binary.BigEndian.PutUint16(data[2:], 3) + binary.BigEndian.PutUint16(data[4:], 42) + for n, id := range []uint16{1, 4, 6} { + record := data[6+n*12:] + binary.BigEndian.PutUint16(record, 3) + binary.BigEndian.PutUint16(record[2:], 1) + binary.BigEndian.PutUint16(record[4:], 0x409) + binary.BigEndian.PutUint16(record[6:], id) + binary.BigEndian.PutUint16(record[8:], uint16(len(name)*2)) + } + for n, v := range name { + binary.BigEndian.PutUint16(data[42+n*2:], v) + } + tables["name"] = data + changed = true + } + if len(tables["post"]) == 0 { + tables["post"] = buildPostTable() + changed = true + } + if len(tables["OS/2"]) == 0 { + hhea := tables["hhea"] + tables["OS/2"] = buildOS2TableWithMetrics(int16(binary.BigEndian.Uint16(hhea[4:6])), int16(binary.BigEndian.Uint16(hhea[6:8]))) + changed = true + } + if !changed { + return source.Program, nil + } + return serializeOTF(tables) +}