diff --git a/assets/webui/index.html b/assets/webui/index.html
index 62c7be5..08fb13b 100644
--- a/assets/webui/index.html
+++ b/assets/webui/index.html
@@ -590,6 +590,10 @@
0
+
+ 转换提示
+
+
- 加密
- 未加密
- 算法
diff --git a/assets/webui/ofdgo.css b/assets/webui/ofdgo.css
index c8f6520..bbdf9ff 100644
--- a/assets/webui/ofdgo.css
+++ b/assets/webui/ofdgo.css
@@ -2161,6 +2161,19 @@ button.outline-link:hover {
text-decoration: underline;
}
+.conversion-notice {
+ margin-block: 12px;
+}
+
+.conversion-notice > summary {
+ cursor: pointer;
+}
+
+.conversion-notice p {
+ margin-block: 8px;
+ overflow-wrap: anywhere;
+}
+
.attachment-detail {
color: var(--text-muted);
font-size: 12px;
diff --git a/assets/webui/ofdgo.js b/assets/webui/ofdgo.js
index 164561a..bd663b0 100644
--- a/assets/webui/ofdgo.js
+++ b/assets/webui/ofdgo.js
@@ -29,6 +29,7 @@ let credentialRequest = null;
let cancelPageTouch = null;
const state = {
+ conversionWarnings: [],
composite: null,
annotationEdit: null,
annotationCreate: null,
@@ -440,6 +441,8 @@ const el = {
refreshAppButton: document.querySelector("#refreshAppButton"),
metaFile: document.querySelector("#metaFile"),
metaTitle: document.querySelector("#metaTitle"),
+ conversionNotice: document.querySelector("#conversionNotice"),
+ conversionWarnings: document.querySelector("#conversionWarnings"),
metaSubject: document.querySelector("#metaSubject"),
metaAuthor: document.querySelector("#metaAuthor"),
metaCreationDate: document.querySelector("#metaCreationDate"),
@@ -1929,6 +1932,7 @@ async function toggleEditor() {
state.composite = null;
state.selectObjects = true;
state.ofdBytes = null;
+ state.conversionWarnings = [];
state.objectClipboard = null;
state.styleClipboard = null;
canvasEditor.clear();
@@ -3331,6 +3335,7 @@ async function openOFD(file) {
setBusy(true, "正在读取文档", 10, STATUS.opening);
try {
let bytes = new Uint8Array(await file.arrayBuffer());
+ let warnings = [];
if (openSeq !== state.openSeq) {
return;
}
@@ -3341,8 +3346,10 @@ async function openOFD(file) {
const converted = await callWASM("ofdgoConvertPDF", bytes);
if (openSeq !== state.openSeq) return;
bytes = converted.bytes;
+ warnings = JSON.parse(converted.warnings || "null") || [];
}
state.ofdBytes = bytes;
+ state.conversionWarnings = warnings;
state.fileName = (file.name || "ofdgo.ofd").replace(/\.pdf$/i, ".ofd");
state.editing = false;
state.composite = null;
@@ -6310,6 +6317,14 @@ function markThumbnailError(index) {
function renderMeta(keepDetails = false) {
renderSecurity();
+ el.conversionNotice.hidden = !state.conversionWarnings.length;
+ renderMetaContent(el.conversionWarnings, state.conversionWarnings, () => {
+ el.conversionWarnings.replaceChildren(...state.conversionWarnings.map(warning => {
+ const item = document.createElement("p");
+ item.textContent = `第${warning.Page}页 · 位置${warning.Offset}:${warning.Message}`;
+ return item;
+ }));
+ });
const doc = state.doc || {};
el.metaPanel.setAttribute("aria-busy", String(!!doc.detailsPending));
document.title = `OFDGo WebUI - ${state.fileName}`;
diff --git a/go.mod b/go.mod
index 964b852..24607b1 100644
--- a/go.mod
+++ b/go.mod
@@ -9,7 +9,7 @@ require (
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
+ github.com/xiaoqidun/pdfgo v0.0.0-20260924091402-7973f8a3807a
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 374257a..e0c9f78 100644
--- a/go.sum
+++ b/go.sum
@@ -60,8 +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/xiaoqidun/pdfgo v0.0.0-20260924091402-7973f8a3807a h1:+mspTtduelAEpmCAw/Pc6p2azO1vkuF2wIJRDogZHU4=
+github.com/xiaoqidun/pdfgo v0.0.0-20260924091402-7973f8a3807a/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 e05e21f..dff83f9 100644
--- a/internal/webui/wasm.go
+++ b/internal/webui/wasm.go
@@ -314,7 +314,7 @@ func safeCall(fn func([]js.Value) (any, error), args []js.Value) (data any, err
// convertPDFDocument 通过库转换PDF,不替换当前文档会话
// 入参: args PDF数据
-// 返回: any OFD数据, error 错误信息
+// 返回: any OFD数据及转换警告, error 错误信息
func convertPDFDocument(args []js.Value) (any, error) {
if len(args) != 1 {
return nil, fmt.Errorf("missing PDF data")
@@ -324,11 +324,15 @@ func convertPDFDocument(args []js.Value) (any, error) {
return nil, err
}
var output bytes.Buffer
- _, err = ofdgo.ConvertPDF(context.Background(), bytes.NewReader(data), int64(len(data)), &output, ofdgo.PDFImportOptions{})
+ report, 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
+ warnings, err := json.Marshal(report.Warnings)
+ if err != nil {
+ return nil, err
+ }
+ return successResult(map[string]any{"bytes": bytesToJS(output.Bytes()), "warnings": string(warnings)}), nil
}
// openDocument 打开OFD文档
diff --git a/ofdgo_pdf.go b/ofdgo_pdf.go
index 499c418..12e11b4 100644
--- a/ofdgo_pdf.go
+++ b/ofdgo_pdf.go
@@ -25,18 +25,22 @@ import (
"github.com/xiaoqidun/pdfgo"
)
-// PDFImportOptions 指定PDF转换的运行时后端与进度通知
+// PDFImportOptions 指定PDF转换的运行时后端、进度通知与源文件检查策略
+// Strict禁止恢复缺失的图形状态资源,默认恢复并在报告中记录警告
type PDFImportOptions struct {
Backends *RenderBackends
Progress func(int) error
+ Strict bool
}
-// PDFImportReport 汇总成功转换的页面和可编辑对象
+// PDFImportReport 汇总转换页数、对象数、链接数和源文件恢复警告
type PDFImportReport struct {
Pages int
TextObjects int
PathObjects int
ImageObjects int
+ Links int
+ Warnings []pdfgo.Diagnostic
}
// pdfImporter 保存单次转换的对象与资源状态
@@ -50,6 +54,9 @@ type pdfImporter struct {
fontMetrics map[string]FontMetrics
cmykSpace string
objects []GraphicObject
+ pages map[pdfgo.Reference]*pdfgo.Page
+ pageIDs map[pdfgo.Reference]string
+ imageIDs map[*pdfgo.Stream]string
}
// ImportPDF 将PDF内容转换为独立OFD编辑文档,失败时不返回部分结果
@@ -67,15 +74,34 @@ func ImportPDF(ctx context.Context, source io.ReaderAt, size int64, options PDFI
if options.Backends != nil {
editor.SetRenderBackends(*options.Backends)
}
- importer := pdfImporter{reader: reader, editor: editor, fontIDs: map[*pdfgo.Font]string{}, fontMetrics: map[string]FontMetrics{}}
+ importer := pdfImporter{reader: reader, editor: editor, fontIDs: map[*pdfgo.Font]string{}, fontMetrics: map[string]FontMetrics{}, pages: map[pdfgo.Reference]*pdfgo.Page{}, pageIDs: map[pdfgo.Reference]string{}}
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 {
+ _, width, height := pdfPageMatrix(page)
+ if _, err := editor.AddPage(width, height); err != nil {
return err
}
- if err := reader.WalkPage(ctx, page, pdfgo.Visitor{Path: importer.path, Text: importer.text, Image: importer.image}); err != nil {
+ importer.pages[page.Reference] = page
+ importer.pageIDs[page.Reference] = editor.pages[index].ID
+ return nil
+ })
+ if err != nil {
+ return nil, PDFImportReport{}, err
+ }
+ err = reader.WalkPages(ctx, func(index int, page *pdfgo.Page) error {
+ matrix, _, _ := pdfPageMatrix(page)
+ importer.matrix = matrix
+ importer.page = index
+ visitor := pdfgo.Visitor{Path: importer.path, Text: importer.text, Image: importer.image}
+ if !options.Strict {
+ visitor.Warning = func(warning pdfgo.Diagnostic) {
+ warning.Page = index + 1
+ importer.report.Warnings = append(importer.report.Warnings, warning)
+ }
+ }
+ if err := reader.WalkPage(ctx, page, visitor); err != nil {
+ return fmt.Errorf("import PDF page %d: %w", index+1, err)
+ }
+ if err := importer.links(page); 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 {
@@ -113,6 +139,8 @@ func ConvertPDF(ctx context.Context, source io.ReaderAt, size int64, output io.W
}
// pdfPageMatrix 将裁剪框、用户单位及页面旋转转换为OFD毫米坐标
+// 入参: page PDF页面
+// 返回: pdfgo.Matrix 坐标变换, float64 页面宽度, float64 页面高度
func pdfPageMatrix(page *pdfgo.Page) (pdfgo.Matrix, float64, float64) {
b := page.CropBox
scale := 25.4 / 72 * page.UserUnit
@@ -132,6 +160,8 @@ func pdfPageMatrix(page *pdfgo.Page) (pdfgo.Matrix, float64, float64) {
}
// pdfNumbers 按OFD数值格式序列化坐标
+// 入参: values 数值列表
+// 返回: string 空格分隔的数值
func pdfNumbers(values ...float64) string {
parts := make([]string, len(values))
for n, v := range values {
@@ -141,9 +171,13 @@ func pdfNumbers(values ...float64) string {
}
// pdfBoundary 序列化对象边界
+// 入参: b 对象边界
+// 返回: string OFD边界数据
func pdfBoundary(b Box) string { return pdfNumbers(b.X, b.Y, b.W, b.H) }
// pdfBounds 计算点集合的包围框
+// 入参: points 坐标点集合
+// 返回: Box 包围框
func pdfBounds(points []pdfgo.Point) Box {
if len(points) == 0 {
return Box{}
@@ -159,6 +193,8 @@ func pdfBounds(points []pdfgo.Point) Box {
}
// color 保留设备色彩分量并复用文档颜色空间
+// 入参: paint PDF颜色与不透明度
+// 返回: *FillColor OFD颜色
func (p *pdfImporter) color(paint pdfgo.Paint) *FillColor {
alpha := int(math.Round(paint.Alpha * 255))
if paint.CMYK != nil {
@@ -173,6 +209,8 @@ func (p *pdfImporter) color(paint pdfgo.Paint) *FillColor {
}
// pathData 将PDF路径转换为相对对象边界的OFD路径
+// 入参: path PDF路径, origin 对象边界
+// 返回: string OFD路径数据
func (p *pdfImporter) pathData(path pdfgo.Path, origin Box) string {
var parts []string
for _, segment := range path.Segments {
@@ -186,6 +224,8 @@ func (p *pdfImporter) pathData(path pdfgo.Path, origin Box) string {
}
// clips 保持裁剪路径的交集,不随对象CTM重复变换
+// 入参: paths 裁剪路径, origin 对象边界
+// 返回: *Clips OFD裁剪区域,无裁剪时为空
func (p *pdfImporter) clips(paths []pdfgo.Path, origin Box) *Clips {
if len(paths) == 0 {
return nil
@@ -210,7 +250,12 @@ func (p *pdfImporter) clips(paths []pdfgo.Path, origin Box) *Clips {
}
// path 添加独立可编辑路径
+// 入参: mark PDF路径绘制信息
+// 返回: error 错误信息
func (p *pdfImporter) path(mark pdfgo.PathMark) error {
+ if mark.Fill && mark.Style.FillOverprint && !pdfOpaqueBlack(mark.Style.Fill) || mark.Stroke && mark.Style.StrokeOverprint && !pdfOpaqueBlack(mark.Style.Stroke) {
+ return &pdfgo.UnsupportedError{Feature: "color separation overprint"}
+ }
var points []pdfgo.Point
for _, segment := range mark.Path.Segments {
for _, point := range segment.Points {
@@ -244,3 +289,10 @@ func (p *pdfImporter) path(mark pdfgo.PathMark) error {
p.report.PathObjects++
return nil
}
+
+// pdfOpaqueBlack 判断不受底层分色影响的全黑设备色
+// 入参: paint PDF颜色与不透明度
+// 返回: bool 是否为不透明全黑CMYK颜色
+func pdfOpaqueBlack(paint pdfgo.Paint) bool {
+ return paint.Alpha == 1 && paint.CMYK != nil && paint.CMYK[3] == 1
+}
diff --git a/ofdgo_pdf_link.go b/ofdgo_pdf_link.go
new file mode 100644
index 0000000..47201ad
--- /dev/null
+++ b/ofdgo_pdf_link.go
@@ -0,0 +1,150 @@
+// 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 (
+ "fmt"
+
+ "github.com/xiaoqidun/pdfgo"
+)
+
+// links 将无外观链接转换为OFD点击区域,其他注解或外观返回不支持错误
+// 入参: page PDF页面
+// 返回: error 错误信息
+func (p *pdfImporter) links(page *pdfgo.Page) error {
+ annotations, err := page.Annotations()
+ if err != nil {
+ return err
+ }
+ for _, annotation := range annotations {
+ dict := annotation.Dictionary
+ if annotation.Subtype != "Link" {
+ return &pdfgo.UnsupportedError{Feature: "annotation " + string(annotation.Subtype)}
+ }
+ for _, key := range []pdfgo.Name{"AP", "AA", "BS", "QuadPoints", "OC"} {
+ if dict[key] != nil {
+ return &pdfgo.UnsupportedError{Feature: fmt.Sprintf("link annotation field %q", key)}
+ }
+ }
+ if value, err := p.reader.Resolve(dict["F"]); err != nil {
+ return err
+ } else if value != nil {
+ flags, ok := value.(pdfgo.Integer)
+ if !ok {
+ return fmt.Errorf("invalid PDF annotation flags")
+ }
+ if flags != 0 && flags != 4 {
+ return &pdfgo.UnsupportedError{Feature: "link annotation flags"}
+ }
+ }
+ border, err := p.reader.Resolve(dict["Border"])
+ if err != nil {
+ return err
+ }
+ array, ok := border.(pdfgo.Array)
+ if !ok || len(array) != 3 || (array[2] != pdfgo.Integer(0) && array[2] != pdfgo.Real(0)) {
+ return &pdfgo.UnsupportedError{Feature: "visible link border"}
+ }
+ action := Action{Event: "CLICK"}
+ target := dict["Dest"]
+ if dict["A"] != nil {
+ value, err := p.reader.Resolve(dict["A"])
+ if err != nil {
+ return err
+ }
+ a, ok := value.(pdfgo.Dictionary)
+ if !ok {
+ return fmt.Errorf("invalid PDF link action")
+ }
+ if a["Next"] != nil {
+ return &pdfgo.UnsupportedError{Feature: "chained link actions"}
+ }
+ switch a["S"] {
+ case pdfgo.Name("GoTo"):
+ target = a["D"]
+ case pdfgo.Name("URI"):
+ value, err := p.reader.Resolve(a["URI"])
+ if err != nil {
+ return err
+ }
+ uri, ok := value.(pdfgo.String)
+ if !ok {
+ return fmt.Errorf("invalid PDF URI")
+ }
+ isMap, err := p.reader.Resolve(a["IsMap"])
+ if err != nil {
+ return err
+ }
+ if isMap != nil && isMap != pdfgo.Boolean(false) && isMap != pdfgo.Boolean(true) {
+ return fmt.Errorf("invalid PDF URI image map flag")
+ }
+ if isMap == pdfgo.Boolean(true) {
+ return &pdfgo.UnsupportedError{Feature: "URI image map"}
+ }
+ base, err := p.reader.BaseURI()
+ if err != nil {
+ return err
+ }
+ action.URI = &URI{URI: string(uri), Base: base}
+ default:
+ return &pdfgo.UnsupportedError{Feature: "link action"}
+ }
+ }
+ if action.URI == nil {
+ destination, err := p.reader.ReadDestination(target)
+ if err != nil {
+ return err
+ }
+ targetPage := p.pages[destination.Page]
+ if targetPage == nil {
+ return fmt.Errorf("PDF destination page missing")
+ }
+ matrix, _, _ := pdfPageMatrix(targetPage)
+ dest := &Dest{Type: string(destination.Mode), PageID: p.pageIDs[destination.Page]}
+ if destination.Mode == "XYZ" {
+ values := [3]float64{}
+ for n, v := range destination.Parameters {
+ switch v := v.(type) {
+ case pdfgo.Integer:
+ values[n] = float64(v)
+ case pdfgo.Real:
+ values[n] = float64(v)
+ case nil:
+ if n < 2 {
+ return &pdfgo.UnsupportedError{Feature: "retained destination coordinates"}
+ }
+ }
+ }
+ point := matrix.Apply(pdfgo.Point{X: values[0], Y: values[1]})
+ dest.Left, dest.Top, dest.Zoom = point.X, point.Y, values[2]
+ } else if destination.Mode != "Fit" {
+ return &pdfgo.UnsupportedError{Feature: "destination mode " + string(destination.Mode)}
+ }
+ action.Goto = &Goto{Dest: dest}
+ }
+ b := annotation.Rect
+ box := pdfBounds([]pdfgo.Point{p.matrix.Apply(pdfgo.Point{X: b.XMin, Y: b.YMin}), p.matrix.Apply(pdfgo.Point{X: b.XMax, Y: b.YMax})})
+ object, err := NewShape(ShapeRectangle, box)
+ if err != nil {
+ return err
+ }
+ no := false
+ object.Fill, object.Stroke = &no, &no
+ object.Actions = []Action{action}
+ p.objects = append(p.objects, GraphicObject{Type: "PathObject", PathObject: object})
+ p.report.Links++
+ }
+ return nil
+}
diff --git a/ofdgo_pdf_object.go b/ofdgo_pdf_object.go
index 0ec681e..266f8f9 100644
--- a/ofdgo_pdf_object.go
+++ b/ofdgo_pdf_object.go
@@ -30,108 +30,64 @@ import (
)
// image 转换图像样本,不将整页或其他对象栅格化
+// 入参: mark PDF图像绘制信息
+// 返回: error 错误信息
func (p *pdfImporter) image(mark pdfgo.ImageMark) error {
+ if mark.Style.FillOverprint {
+ return &pdfgo.UnsupportedError{Feature: "image color separation overprint"}
+ }
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
- }
+ id := p.imageIDs[source.Stream]
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
+ id = ""
}
- var encoded bytes.Buffer
- if jpegOriginal {
- encoded.Write(source.Stream.Data)
- } else {
- if err := png.Encode(&encoded, decoded); err != nil {
+ if id == "" {
+ filter, err := p.reader.Resolve(source.Stream.Dictionary["Filter"])
+ if err != nil {
return err
}
- }
- id, err := p.editor.AddImage(encoded.Bytes())
- if err != nil {
- return err
+ jpegOriginal := filter == pdfgo.Name("DCTDecode") && len(source.Decode) == 0 && !source.ImageMask && source.ColorSpace != pdfgo.Name("DeviceCMYK") && source.Mask == nil && source.SoftMask == nil
+ decoded, err := source.DecodeImage()
+ if err != nil {
+ return err
+ }
+ 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
+ }
+ if !source.ImageMask {
+ if p.imageIDs == nil {
+ p.imageIDs = map[*pdfgo.Stream]string{}
+ }
+ p.imageIDs[source.Stream] = id
+ }
}
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})})
@@ -143,12 +99,17 @@ func (p *pdfImporter) image(mark pdfgo.ImageMark) error {
}
// text 保留原字体、字形编号与逐字基线,不重新塑形
+// 入参: mark PDF文字绘制信息
+// 返回: error 错误信息
func (p *pdfImporter) text(mark pdfgo.TextMark) error {
+ if (mark.Mode == 0 || mark.Mode == 2) && mark.Style.FillOverprint && !pdfOpaqueBlack(mark.Style.Fill) || (mark.Mode == 1 || mark.Mode == 2) && mark.Style.StrokeOverprint && !pdfOpaqueBlack(mark.Style.Stroke) {
+ return &pdfgo.UnsupportedError{Feature: "text color separation overprint"}
+ }
font := mark.Font
if len(font.Program) == 0 {
return &pdfgo.UnsupportedError{Feature: "text without embedded font"}
}
- if font.ProgramType != "FontFile2" && font.ProgramType != "OpenType" {
+ if font.ProgramType != "FontFile2" && font.ProgramType != "OpenType" && font.ProgramType != "Type1C" && font.ProgramType != "CIDFontType0C" {
return &pdfgo.UnsupportedError{Feature: "font program " + string(font.ProgramType)}
}
id := p.fontIDs[font]
@@ -187,6 +148,13 @@ func (p *pdfImporter) text(mark pdfgo.TextMark) error {
position := 0
for n, glyph := range mark.Glyphs {
gid := glyph.ID
+ if glyph.Text == "" && glyph.HasID {
+ character := getUnicodeFromName(glyph.Name)
+ if character == 0 {
+ character = packedGlyphRune(gid)
+ }
+ glyph.Text = string(character)
+ }
if !glyph.HasID {
if utf8.RuneCountInString(glyph.Text) != 1 {
return &pdfgo.UnsupportedError{Feature: "simple font glyph ligature mapping"}
@@ -242,9 +210,19 @@ func (p *pdfImporter) text(mark pdfgo.TextMark) error {
return nil
}
-// pdfFontProgram 为PDF子集字体补齐封装表,不改动字形轮廓、编号或原始度量
+// pdfFontProgram 为PDF子集字体补齐封装表,保留字形轮廓和编号
+// 入参: source PDF字体
+// 返回: []byte 封装后的字体数据, error 错误信息
func pdfFontProgram(source *pdfgo.Font) ([]byte, error) {
- tables, err := fontFileTables(source.Program, 0)
+ program := source.Program
+ if source.ProgramType == "Type1C" || source.ProgramType == "CIDFontType0C" {
+ var err error
+ program, _, err = wrapCFFToOTF(source.Program)
+ if err != nil {
+ return nil, err
+ }
+ }
+ tables, err := fontFileTables(program, 0)
if err != nil {
return nil, err
}
@@ -310,7 +288,7 @@ func pdfFontProgram(source *pdfgo.Font) ([]byte, error) {
changed = true
}
if !changed {
- return source.Program, nil
+ return program, nil
}
return serializeOTF(tables)
}