Files
ofdgo/internal/codec/pdf/metadata.go
T
2026-10-20 18:45:00 +08:00

79 lines
2.6 KiB
Go

// 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 (
"fmt"
"strings"
"time"
"github.com/xiaoqidun/pdfgo"
)
// NormalizeDate 校验PDF日期,非严格模式补齐完整时区偏移的分隔符
// 入参: text PDF日期字符串, strict 是否严格校验
// 返回: string 标准日期字符串, error 日期错误
func NormalizeDate(text string, strict bool) (string, error) {
if text == "" {
return text, nil
}
_, err := pdfgo.ParseDate(text)
if err == nil || strict {
return text, err
}
offset := len(text) - 5
if offset < 6 || text[offset] != '+' && text[offset] != '-' {
return text, err
}
for _, digit := range text[offset+1:] {
if digit < '0' || digit > '9' {
return text, err
}
}
normalized := text[:offset+3] + "'" + text[offset+3:] + "'"
if _, parseErr := pdfgo.ParseDate(normalized); parseErr != nil {
return text, err
}
return normalized, nil
}
// MetadataDate 保留当地日历日期,PDF省略时区按GMT,XMP省略日或时区时不推算
// 入参: text 来源日期, xmp 是否为XMP日期
// 返回: time.Time 解析值, bool 是否精确到日, bool 是否可比较绝对时间, error 日期错误
func MetadataDate(text string, xmp bool) (time.Time, bool, bool, error) {
if text == "" {
return time.Time{}, false, false, nil
}
if !xmp {
date, err := pdfgo.ParseDate(text)
return date, err == nil && date.Year() > 0, err == nil, err
}
if !strings.Contains(text, ",") {
for _, layout := range []string{time.RFC3339Nano, "2006-01-02T15:04Z07:00", "2006-01-02T15:04:05", "2006-01-02T15:04", "2006-01-02", "2006-01", "2006"} {
if date, err := time.Parse(layout, text); err == nil {
zoned := strings.Contains(layout, "Z07:00")
if zoned && !strings.HasSuffix(text, "Z") {
zone := text[len(text)-6:]
if zone[1:3] > "23" || zone[4:] > "59" {
return time.Time{}, false, false, fmt.Errorf("invalid XMP time zone")
}
}
return date, len(text) >= 10 && date.Year() > 0, zoned, nil
}
}
}
return time.Time{}, false, false, fmt.Errorf("invalid XMP date")
}