Ai
1 Star 0 Fork 1

gzlwz/golang-pdfcpu

forked from Deeao/golang-pdfcpu 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
checkBox.go 16.31 KB
一键复制 编辑 原始数据 按行查看 历史
liuweizhi 提交于 2024-12-10 16:33 +08:00 . fix: 全局替换module名称
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
/*
Copyright 2021 The pdfcpu Authors.
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 primitives
import (
"bytes"
"fmt"
"gitee.com/gzlwz/golang-pdfcpu/pkg/pdfcpu/color"
pdffont "gitee.com/gzlwz/golang-pdfcpu/pkg/pdfcpu/font"
"gitee.com/gzlwz/golang-pdfcpu/pkg/pdfcpu/model"
"gitee.com/gzlwz/golang-pdfcpu/pkg/pdfcpu/types"
"github.com/pkg/errors"
)
// CheckBox represents a form checkbox including a positioned label.
type CheckBox struct {
pdf *PDF
content *Content
Label *TextFieldLabel
ID string
Tip string
Value bool // checked state
Default bool
Position [2]float64 `json:"pos"` // x,y
x, y float64
Width float64
Dx, Dy float64
boundingBox *types.Rectangle
Margin *Margin // applied to content box
BackgroundColor string `json:"bgCol"`
bgCol *color.SimpleColor
Tab int
Locked bool
Debug bool
Hide bool
}
type AP struct {
irDOffL, irDYesL *types.IndirectRef
irNOffL, irNYesL *types.IndirectRef
irDOffR, irDYesR *types.IndirectRef
irNOffR, irNYesR *types.IndirectRef
}
func (cb *CheckBox) validateID() error {
if cb.ID == "" {
return errors.New("pdfcpu: missing field id")
}
if cb.pdf.DuplicateField(cb.ID) {
return errors.Errorf("pdfcpu: duplicate form field: %s", cb.ID)
}
cb.pdf.FieldIDs[cb.ID] = true
return nil
}
func (cb *CheckBox) validatePosition() error {
if cb.Position[0] < 0 || cb.Position[1] < 0 {
return errors.Errorf("pdfcpu: field: %s pos value < 0", cb.ID)
}
cb.x, cb.y = cb.Position[0], cb.Position[1]
return nil
}
func (cb *CheckBox) validateMargin() error {
if cb.Margin != nil {
if err := cb.Margin.validate(); err != nil {
return err
}
}
return nil
}
func (cb *CheckBox) validateWidth() error {
if cb.Width <= 0 {
return errors.Errorf("pdfcpu: field: %s width <= 0", cb.ID)
}
return nil
}
func (cb *CheckBox) validateLabel() error {
if cb.Label != nil {
cb.Label.pdf = cb.pdf
if err := cb.Label.validate(); err != nil {
return err
}
}
return nil
}
func (cb *CheckBox) validateTab() error {
if cb.Tab < 0 {
return errors.Errorf("pdfcpu: field: %s negative tab value", cb.ID)
}
if cb.Tab == 0 {
return nil
}
page := cb.content.page
if page.Tabs == nil {
page.Tabs = types.IntSet{}
} else {
if page.Tabs[cb.Tab] {
return errors.Errorf("pdfcpu: field: %s duplicate tab value %d", cb.ID, cb.Tab)
}
}
page.Tabs[cb.Tab] = true
return nil
}
func (cb *CheckBox) validate() error {
if err := cb.validateID(); err != nil {
return err
}
if err := cb.validatePosition(); err != nil {
return err
}
if err := cb.validateWidth(); err != nil {
return err
}
if err := cb.validateMargin(); err != nil {
return err
}
if err := cb.validateLabel(); err != nil {
return err
}
return cb.validateTab()
}
func (cb *CheckBox) margin(name string) *Margin {
return cb.content.namedMargin(name)
}
func (cb *CheckBox) calcMargin() (float64, float64, float64, float64, error) {
mTop, mRight, mBottom, mLeft := 0., 0., 0., 0.
if cb.Margin != nil {
m := cb.Margin
if m.Name != "" && m.Name[0] == '$' {
// use named margin
mName := m.Name[1:]
m0 := cb.margin(mName)
if m0 == nil {
return mTop, mRight, mBottom, mLeft, errors.Errorf("pdfcpu: unknown named margin %s", mName)
}
m.mergeIn(m0)
}
if m.Width > 0 {
mTop = m.Width
mRight = m.Width
mBottom = m.Width
mLeft = m.Width
} else {
mTop = m.Top
mRight = m.Right
mBottom = m.Bottom
mLeft = m.Left
}
}
return mTop, mRight, mBottom, mLeft, nil
}
func (cb *CheckBox) labelPos(labelHeight, w, g float64) (float64, float64) {
var x, y float64
bb, horAlign := cb.boundingBox, cb.Label.HorAlign
switch cb.Label.relPos {
case types.RelPosLeft:
x = bb.LL.X - g
if horAlign == types.AlignLeft {
x -= w
if x < 0 {
x = 0
}
}
y = bb.LL.Y
case types.RelPosRight:
x = bb.UR.X + g
if horAlign == types.AlignRight {
x += w
}
y = bb.LL.Y
case types.RelPosTop:
y = bb.UR.Y + g
x = bb.LL.X
if horAlign == types.AlignRight {
x += bb.Width()
} else if horAlign == types.AlignCenter {
x += bb.Width() / 2
}
case types.RelPosBottom:
y = bb.LL.Y - g - labelHeight
x = bb.LL.X
if horAlign == types.AlignRight {
x += bb.Width()
} else if horAlign == types.AlignCenter {
x += bb.Width() / 2
}
}
return x, y
}
func (cb *CheckBox) ensureZapfDingbats(fonts model.FontMap) (*types.IndirectRef, error) {
// TODO Refactor
pdf := cb.pdf
fontName := "ZapfDingbats"
font, ok := fonts[fontName]
if ok {
if font.Res.IndRef != nil {
return font.Res.IndRef, nil
}
ir, err := pdffont.EnsureFontDict(pdf.XRefTable, fontName, "", "", false, nil)
if err != nil {
return nil, err
}
font.Res.IndRef = ir
fonts[fontName] = font
return ir, nil
}
var (
indRef *types.IndirectRef
err error
)
if pdf.Update() {
for objNr, fo := range pdf.Optimize.FormFontObjects {
//fmt.Printf("searching for %s - obj:%d fontName:%s prefix:%s\n", fontName, objNr, fo.FontName, fo.Prefix)
if fontName == fo.FontName {
//fmt.Println("Match!")
indRef = types.NewIndirectRef(objNr, 0)
break
}
}
if indRef == nil {
for objNr, fo := range pdf.Optimize.FontObjects {
if fontName == fo.FontName {
indRef = types.NewIndirectRef(objNr, 0)
break
}
}
}
}
if indRef == nil {
indRef, err = pdffont.EnsureFontDict(pdf.XRefTable, fontName, "", "", false, nil)
if err != nil {
return nil, err
}
}
font.Res = model.Resource{IndRef: indRef}
fonts[fontName] = font
return indRef, nil
}
func (cb *CheckBox) calcFont() error {
if cb.Label != nil {
f, err := cb.content.calcLabelFont(cb.Label.Font)
if err != nil {
return err
}
cb.Label.Font = f
}
return nil
}
func (cb *CheckBox) irNOff(bgCol *color.SimpleColor) (*types.IndirectRef, error) {
pdf := cb.pdf
ap, found := pdf.CheckBoxAPs[cb.Width]
if found && ap.irNOffL != nil {
return ap.irNOffL, nil
}
buf := new(bytes.Buffer)
fmt.Fprint(buf, "q ")
if bgCol != nil {
fmt.Fprintf(buf, "%.2f %.2f %.2f rg ", bgCol.R, bgCol.G, bgCol.B)
} else {
fmt.Fprint(buf, "1 g ")
}
fmt.Fprintf(buf, "0 0 %.1f %.1f re f 0.5 0.5 %.1f %.1f re s Q ", cb.Width, cb.Width, cb.Width-1, cb.Width-1)
sd, err := pdf.XRefTable.NewStreamDictForBuf(buf.Bytes())
if err != nil {
return nil, err
}
sd.InsertName("Type", "XObject")
sd.InsertName("Subtype", "Form")
sd.InsertInt("FormType", 1)
sd.Insert("BBox", types.NewNumberArray(0, 0, cb.Width, cb.Width))
sd.Insert("Matrix", types.NewNumberArray(1, 0, 0, 1, 0, 0))
if err := sd.Encode(); err != nil {
return nil, err
}
ir, err := pdf.XRefTable.IndRefForNewObject(*sd)
if err != nil {
return nil, err
}
if !found {
ap = &AP{}
pdf.CheckBoxAPs[cb.Width] = ap
}
ap.irNOffL = ir
return ir, nil
}
func (cb *CheckBox) irNYes(fonts model.FontMap, bgCol *color.SimpleColor) (*types.IndirectRef, error) {
pdf := cb.pdf
ap, found := pdf.CheckBoxAPs[cb.Width]
if found && ap.irNYesL != nil {
return ap.irNYesL, nil
}
buf := new(bytes.Buffer)
fmt.Fprint(buf, "q ")
if bgCol != nil {
fmt.Fprintf(buf, "%.2f %.2f %.2f rg ", bgCol.R, bgCol.G, bgCol.B)
} else {
fmt.Fprint(buf, "1 g ")
}
s, x, y := 14.532/18, 2.853/18, 4.081/18
fmt.Fprintf(buf, "0 0 %.1f %.1f re f 0.5 0.5 %.1f %.1f re s Q ", cb.Width, cb.Width, cb.Width-1, cb.Width-1)
fmt.Fprintf(buf, "q 1 1 %.1f %.1f re W n BT /F0 %f Tf %f %f Td (4) Tj ET Q ", cb.Width-2, cb.Width-2, s*cb.Width, x*cb.Width, y*cb.Width)
sd, err := pdf.XRefTable.NewStreamDictForBuf(buf.Bytes())
if err != nil {
return nil, err
}
sd.InsertName("Type", "XObject")
sd.InsertName("Subtype", "Form")
sd.InsertInt("FormType", 1)
sd.Insert("BBox", types.NewNumberArray(0, 0, cb.Width, cb.Width))
sd.Insert("Matrix", types.NewNumberArray(1, 0, 0, 1, 0, 0))
ir, err := cb.ensureZapfDingbats(fonts)
if err != nil {
return nil, err
}
d := types.Dict(
map[string]types.Object{
"Font": types.Dict(
map[string]types.Object{
"F0": *ir,
},
),
},
)
sd.Insert("Resources", d)
if err := sd.Encode(); err != nil {
return nil, err
}
ir, err = pdf.XRefTable.IndRefForNewObject(*sd)
if err != nil {
return nil, err
}
if !found {
ap = &AP{}
pdf.CheckBoxAPs[cb.Width] = ap
}
ap.irNYesL = ir
return ir, nil
}
func (cb *CheckBox) irDOff(bgCol *color.SimpleColor) (*types.IndirectRef, error) {
pdf := cb.pdf
ap, found := cb.pdf.CheckBoxAPs[cb.Width]
if found && ap.irDOffL != nil {
return ap.irDOffL, nil
}
buf := fmt.Sprintf("q 0.75293 g 0 0 %.1f %.1f re f 0.5 0.5 %.1f %.1f re se Q ", cb.Width, cb.Width, cb.Width-1, cb.Width-1)
sd, err := pdf.XRefTable.NewStreamDictForBuf([]byte(buf))
if err != nil {
return nil, err
}
sd.InsertName("Type", "XObject")
sd.InsertName("Subtype", "Form")
sd.InsertInt("FormType", 1)
sd.Insert("BBox", types.NewNumberArray(0, 0, cb.Width, cb.Width))
sd.Insert("Matrix", types.NewNumberArray(1, 0, 0, 1, 0, 0))
if err := sd.Encode(); err != nil {
return nil, err
}
ir, err := pdf.XRefTable.IndRefForNewObject(*sd)
if err != nil {
return nil, err
}
if !found {
ap = &AP{}
pdf.CheckBoxAPs[cb.Width] = ap
}
ap.irDOffL = ir
return ir, nil
}
func (cb *CheckBox) irDYes(fonts model.FontMap, bgCol *color.SimpleColor) (*types.IndirectRef, error) {
pdf := cb.pdf
ap, found := pdf.CheckBoxAPs[cb.Width]
if found && ap.irDYesL != nil {
return ap.irDYesL, nil
}
s, x, y := 14.532/18, 2.853/18, 4.081/18
buf := fmt.Sprintf("q 0.75293 g 0 0 %.1f %.1f re f 0.5 0.5 %.1f %.1f re se Q ", cb.Width, cb.Width, cb.Width-1, cb.Width-1)
buf += fmt.Sprintf("q 1 1 %.1f %.1f re W n BT /F0 %f Tf %f %f Td (4) Tj ET Q ", cb.Width-2, cb.Width-2, s*cb.Width, x*cb.Width, y*cb.Width)
sd, _ := cb.pdf.XRefTable.NewStreamDictForBuf([]byte(buf))
sd.InsertName("Type", "XObject")
sd.InsertName("Subtype", "Form")
sd.InsertInt("FormType", 1)
sd.Insert("BBox", types.NewNumberArray(0, 0, cb.Width, cb.Width))
sd.Insert("Matrix", types.NewNumberArray(1, 0, 0, 1, 0, 0))
ir, err := cb.ensureZapfDingbats(fonts)
if err != nil {
return nil, err
}
d := types.Dict(
map[string]types.Object{
"Font": types.Dict(
map[string]types.Object{
"F0": *ir,
},
),
},
)
sd.Insert("Resources", d)
if err := sd.Encode(); err != nil {
return nil, err
}
ir, err = pdf.XRefTable.IndRefForNewObject(*sd)
if err != nil {
return nil, err
}
if !found {
ap = &AP{}
pdf.CheckBoxAPs[cb.Width] = ap
}
ap.irDYesL = ir
return ir, nil
}
func (cb *CheckBox) appearanceIndRefs(fonts model.FontMap, bgCol *color.SimpleColor) (
*types.IndirectRef, *types.IndirectRef, *types.IndirectRef, *types.IndirectRef, error) {
irDOff, err := cb.irDOff(bgCol)
if err != nil {
return nil, nil, nil, nil, err
}
irDYes, err := cb.irDYes(fonts, bgCol)
if err != nil {
return nil, nil, nil, nil, err
}
irNOff, err := cb.irNOff(bgCol)
if err != nil {
return nil, nil, nil, nil, err
}
irNYes, err := cb.irNYes(fonts, bgCol)
if err != nil {
return nil, nil, nil, nil, err
}
return irDOff, irDYes, irNOff, irNYes, nil
}
func (cb *CheckBox) prepareDict(fonts model.FontMap) (types.Dict, error) {
id, err := types.EscapeUTF16String(cb.ID)
if err != nil {
return nil, err
}
v := "Off"
if cb.Value {
v = "Yes"
}
dv := "Off"
if cb.Default {
dv = "Yes"
if !cb.Value {
v = "Yes"
}
}
bgCol := cb.bgCol
if bgCol == nil {
bgCol = cb.content.page.bgCol
if bgCol == nil {
bgCol = cb.pdf.bgCol
}
}
irDOff, irDYes, irNOff, irNYes, err := cb.appearanceIndRefs(fonts, bgCol)
if err != nil {
return nil, err
}
d := types.Dict(
map[string]types.Object{
"Type": types.Name("Annot"),
"Subtype": types.Name("Widget"),
"FT": types.Name("Btn"),
"Rect": cb.boundingBox.Array(),
"F": types.Integer(model.AnnPrint),
"T": types.StringLiteral(*id),
"V": types.Name(v), // -> extractValue: Off or Yes
"DV": types.Name(dv),
"AS": types.Name(v),
"AP": types.Dict(
map[string]types.Object{
"D": types.Dict(
map[string]types.Object{
"Off": *irDOff,
"Yes": *irDYes,
},
),
"N": types.Dict(
map[string]types.Object{
"Off": *irNOff,
"Yes": *irNYes,
},
),
},
),
},
)
if cb.Tip != "" {
tu, err := types.EscapeUTF16String(cb.Tip)
if err != nil {
return nil, err
}
d["TU"] = types.StringLiteral(*tu)
}
if bgCol != nil {
appCharDict := types.Dict{}
if bgCol != nil {
appCharDict["BG"] = bgCol.Array()
}
d["MK"] = appCharDict
}
if cb.Locked {
d["Ff"] = types.Integer(FieldReadOnly)
}
return d, nil
}
func (cb *CheckBox) bbox() *types.Rectangle {
if cb.Label == nil {
return cb.boundingBox.Clone()
}
l := cb.Label
var r *types.Rectangle
x := l.td.X
switch l.td.HAlign {
case types.AlignCenter:
x -= float64(l.Width) / 2
case types.AlignRight:
x -= float64(l.Width)
}
y := l.td.Y
if l.relPos == types.RelPosLeft || l.relPos == types.RelPosRight {
y -= cb.boundingBox.Height() / 2
}
r = types.RectForWidthAndHeight(x, y, float64(l.Width), l.height)
return model.CalcBoundingBoxForRects(cb.boundingBox, r)
}
func (cb *CheckBox) prepareRectLL(mTop, mRight, mBottom, mLeft float64) (float64, float64) {
return cb.content.calcPosition(cb.x, cb.y, cb.Dx, cb.Dy, mTop, mRight, mBottom, mLeft)
}
func (cb *CheckBox) prepLabel(p *model.Page, pageNr int, fonts model.FontMap) error {
if cb.Label == nil {
return nil
}
l := cb.Label
v := "Default"
if l.Value != "" {
v = l.Value
}
w := float64(l.Width)
g := float64(l.Gap)
f := l.Font
fontName, fontLang, col := f.Name, f.Lang, f.col
id, err := cb.pdf.idForFontName(fontName, fontLang, p.Fm, fonts, pageNr)
if err != nil {
return err
}
td := model.TextDescriptor{
Text: v,
FontName: fontName,
Embed: true,
FontKey: id,
FontSize: f.Size,
Scale: 1.,
ScaleAbs: true,
RTL: l.RTL,
}
if col != nil {
td.StrokeCol, td.FillCol = *col, *col
}
if l.BgCol != nil {
td.ShowBackground, td.ShowTextBB, td.BackgroundCol = true, true, *l.BgCol
}
bb := model.WriteMultiLine(cb.pdf.XRefTable, new(bytes.Buffer), types.RectForFormat("A4"), nil, td)
l.height = bb.Height()
if bb.Width() > w {
w = bb.Width()
l.Width = int(bb.Width())
}
td.X, td.Y = cb.labelPos(l.height, w, g)
td.HAlign, td.VAlign = l.HorAlign, types.AlignBottom
if l.relPos == types.RelPosLeft || l.relPos == types.RelPosRight {
td.Y += cb.boundingBox.Height() / 2
td.VAlign = types.AlignMiddle
}
l.td = &td
return nil
}
func (cb *CheckBox) prepForRender(p *model.Page, pageNr int, fonts model.FontMap) error {
mTop, mRight, mBottom, mLeft, err := cb.calcMargin()
if err != nil {
return err
}
x, y := cb.prepareRectLL(mTop, mRight, mBottom, mLeft)
if err := cb.calcFont(); err != nil {
return err
}
cb.boundingBox = types.RectForWidthAndHeight(x, y, cb.Width, cb.Width)
return cb.prepLabel(p, pageNr, fonts)
}
func (cb *CheckBox) doRender(p *model.Page, fonts model.FontMap) error {
d, err := cb.prepareDict(fonts)
if err != nil {
return err
}
ann := model.FieldAnnotation{Dict: d}
if cb.Tab > 0 {
p.AnnotTabs[cb.Tab] = ann
} else {
p.Annots = append(p.Annots, ann)
}
if cb.Label != nil {
model.WriteColumn(cb.pdf.XRefTable, p.Buf, p.MediaBox, nil, *cb.Label.td, 0)
}
if cb.Debug || cb.pdf.Debug {
cb.pdf.highlightPos(p.Buf, cb.boundingBox.LL.X, cb.boundingBox.LL.Y, cb.content.Box())
}
return nil
}
func (cb *CheckBox) render(p *model.Page, pageNr int, fonts model.FontMap) error {
if err := cb.prepForRender(p, pageNr, fonts); err != nil {
return err
}
return cb.doRender(p, fonts)
}
func CalcCheckBoxASNames(d types.Dict) (types.Name, types.Name) {
apDict := d.DictEntry("AP")
d1 := apDict.DictEntry("D")
if d1 == nil {
d1 = apDict.DictEntry("N")
}
offName, yesName := "Off", "Yes"
for k := range d1 {
if k != "Off" {
yesName = k
}
}
return types.Name(offName), types.Name(yesName)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/gzlwz/golang-pdfcpu.git
git@gitee.com:gzlwz/golang-pdfcpu.git
gzlwz
golang-pdfcpu
golang-pdfcpu
v0.0.2

搜索帮助