-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathappearance.go
372 lines (323 loc) · 11.1 KB
/
appearance.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package contentstream
import (
"errors"
"fmt"
"image/color"
"math"
"github.com/benoitkugler/pdf/fonts"
"github.com/benoitkugler/pdf/model"
)
var (
errNoFont = errors.New("no font is currently selected")
errUnbalanced = errors.New("unbalanced save/restore state operators")
)
type GraphicState struct {
Font fonts.BuiltFont // the current usable font
FontSize Fl
XTLM Fl // The x position of the text line matrix.
YTLM Fl // The y position of the text line matrix.
Leading Fl // The current text leading.
Matrix model.Matrix
// current state to avoid unecessary instructions
strokeColor OpSetStrokeRGBColor
fillColor OpSetFillRGBColor
strokeAlpha, fillAlpha Fl
}
// GraphicStream is a buffer of graphics operation,
// with a state. It provides convenient methods
// to ease the creation of a content stream.
// Once ready, it can be transformed to an XObjectForm,
// a Page object or a Tilling pattern.
type GraphicStream struct {
resources model.ResourcesDict
fillAlphaState, strokeAlphaState map[model.ObjFloat]*model.GraphicState
ops []Operation
stateList []GraphicState
State GraphicState
BoundingBox model.Rectangle
}
// NewGraphicStream setup the BBox and initialize the
// resources dictionary.
func NewGraphicStream(bbox model.Rectangle) GraphicStream {
return GraphicStream{
BoundingBox: bbox,
resources: model.ResourcesDict{
Font: make(map[model.ObjName]*model.FontDict),
XObject: make(map[model.ObjName]model.XObject),
Shading: make(map[model.ObjName]*model.ShadingDict),
ExtGState: make(map[model.ObjName]*model.GraphicState),
Pattern: make(map[model.ObjName]model.Pattern),
},
State: GraphicState{
Matrix: model.Matrix{1, 0, 0, 1, 0, 0},
strokeAlpha: 1,
fillAlpha: 1,
},
fillAlphaState: make(map[model.ObjFloat]*model.GraphicState),
strokeAlphaState: make(map[model.ObjFloat]*model.GraphicState),
}
}
// ToXFormObject write the appearance to a new object,
// and associate it the resources, which are shallow copied.
// The content is optionaly compressed with the Flater filter.
func (ap GraphicStream) ToXFormObject(compress bool) *model.XObjectForm {
out := new(model.XObjectForm)
out.BBox = ap.BoundingBox
out.Resources = ap.resources.ShallowCopy()
out.Content = WriteOperations(ap.ops...)
if compress {
out.Stream = model.NewCompressedStream(out.Content)
}
return out
}
// ApplyToPageObject update the given page with a single Content,
// build from the appearance.
// The content is optionaly compressed with the Flater filter.
func (ap GraphicStream) ApplyToPageObject(page *model.PageObject, compress bool) {
fo := ap.ToXFormObject(compress)
page.Contents = []model.ContentStream{fo.ContentStream}
page.MediaBox = &fo.BBox
page.Resources = &fo.Resources
}
// ApplyToTilling update the fields BBox, ContentStream and Resources
// of the given pattern.
func (ap GraphicStream) ApplyToTilling(pattern *model.PatternTiling) {
pattern.BBox = ap.BoundingBox
pattern.Resources = ap.resources.ShallowCopy()
pattern.ContentStream.Content = WriteOperations(ap.ops...)
}
// Ops adds one or more graphic command. Some commands usually need
// to also update the state: see the other methods.
func (ap *GraphicStream) Ops(op ...Operation) {
ap.ops = append(ap.ops, op...)
}
func (app *GraphicStream) SetColorFill(c color.Color) {
r, g, b := colorRGB(c)
op := OpSetFillRGBColor{R: r, G: g, B: b}
if app.State.fillColor == op {
return
}
app.State.fillColor = op
app.Ops(op)
}
func (app *GraphicStream) SetColorStroke(c color.Color) {
r, g, b := colorRGB(c)
op := OpSetStrokeRGBColor{R: r, G: g, B: b}
if app.State.strokeColor == op {
return
}
app.State.strokeColor = op
app.Ops(op)
}
func (app *GraphicStream) SetFillAlpha(alpha Fl) {
if app.State.fillAlpha == alpha {
return
}
app.State.fillAlpha = alpha
state, has := app.fillAlphaState[model.ObjFloat(alpha)]
if !has {
state = &model.GraphicState{Ca: model.ObjFloat(alpha)}
app.fillAlphaState[model.ObjFloat(alpha)] = state
}
app.SetGraphicState(state)
}
func (app *GraphicStream) SetStrokeAlpha(alpha Fl) {
if app.State.strokeAlpha == alpha {
return
}
app.State.strokeAlpha = alpha
state, has := app.strokeAlphaState[model.ObjFloat(alpha)]
if !has {
state = &model.GraphicState{CA: model.ObjFloat(alpha)}
app.strokeAlphaState[model.ObjFloat(alpha)] = state
}
app.SetGraphicState(state)
}
// SetGraphicState register the given state and write it on the stream
func (app *GraphicStream) SetGraphicState(state *model.GraphicState) {
name := app.AddExtGState(state)
app.Ops(OpSetExtGState{Dict: name})
}
// Shading register the given shading and apply it on the stream.
// It is a shortcut for `AddShading` followed by `Ops(OpShFill)`.
func (app *GraphicStream) Shading(sh *model.ShadingDict) {
name := app.AddShading(sh)
app.Ops(OpShFill{Shading: name})
}
// check is the font is in the resources map or generate a new name and add the font
func (ap GraphicStream) addFont(newFont *model.FontDict) model.ObjName {
for name, f := range ap.resources.Font {
if f == newFont {
return name
}
}
// this convention must be respected so that the names are distincts
name := model.ObjName(fmt.Sprintf("FT%d", len(ap.resources.Font)))
ap.resources.Font[name] = newFont
return name
}
// SetFontAndSize sets the font and the size (in points) for the subsequent text writing.
func (ap *GraphicStream) SetFontAndSize(font fonts.BuiltFont, size Fl) {
if ap.State.Font.Meta == font.Meta && ap.State.FontSize == size {
return
}
ap.State.Font = font
ap.State.FontSize = size
name := ap.addFont(font.Meta) // store and add the PDF name
ap.Ops(OpSetFont{Font: name, Size: size})
}
// SetLeading sets the text leading parameter, which is measured in text space units.
// It specifies the vertical distance
// between the baselines of adjacent lines of text.
func (ap *GraphicStream) SetLeading(leading Fl) {
ap.State.Leading = leading
ap.Ops(OpSetTextLeading{L: leading})
}
// BeginVariableText starts a MarkedContent sequence of text
func (ap *GraphicStream) BeginVariableText() {
ap.Ops(OpBeginMarkedContent{Tag: "Tx"})
}
// EndVariableText end a MarkedContent sequence of text
func (ap *GraphicStream) EndVariableText() {
ap.Ops(OpEndMarkedContent{})
}
// BeginText starts the writing of text.
func (ap *GraphicStream) BeginText() {
ap.State.XTLM = 0
ap.State.YTLM = 0
ap.Ops(OpBeginText{})
}
// EndText ends the writing of text
func (ap *GraphicStream) EndText() {
ap.State.XTLM = 0
ap.State.YTLM = 0
ap.Ops(OpEndText{})
}
// MoveText moves to the start of the next line, offset from the start of the current line.
func (ap *GraphicStream) MoveText(x, y Fl) {
ap.State.XTLM += x
ap.State.YTLM += y
ap.Ops(OpTextMove{X: x, Y: y})
}
// ShowText shows the `text`, after encoding it
// according to the current font.
// And error is returned (only) if a font has not been setup.
// A typical text drawing should apply the following methods ;
// - BeginText
// - SetFontAndSize
// - ShowText
// - EndText
func (ap *GraphicStream) ShowText(text string) error {
if ap.State.Font.Font == nil {
return errNoFont
}
s := string(ap.State.Font.Encode([]rune(text)))
ap.Ops(OpShowText{Text: s})
return nil
}
// NewlineShowText moves to the next line and shows text.
func (ap *GraphicStream) NewlineShowText(text string) error {
if ap.State.Font.Font == nil {
return errNoFont
}
ap.State.YTLM -= ap.State.Leading
s := string(ap.State.Font.Encode([]rune(text)))
ap.Ops(OpMoveShowText{Text: s})
return nil
}
// Transform changes the current matrix, by applying a Concat Op with the given `mat` and
// updating the current state.
func (ap *GraphicStream) Transform(mat model.Matrix) {
ap.Ops(OpConcat{Matrix: mat})
ap.State.Matrix = mat.Multiply(ap.State.Matrix)
}
// SetTextMatrix changes the text matrix.
// This operation also initializes the current point position.
func (ap *GraphicStream) SetTextMatrix(a, b, c, d, x, y Fl) {
ap.State.XTLM = x
ap.State.YTLM = y
ap.Ops(OpSetTextMatrix{Matrix: model.Matrix{a, b, c, d, x, y}})
}
// Saves the graphic state. SaveState and RestoreState must be balanced.
func (ap *GraphicStream) SaveState() {
ap.Ops(OpSave{})
ap.stateList = append(ap.stateList, ap.State)
}
// RestoreState restores the graphic state.
// An error is returned (only) if the calls of SaveState and RestoreState are not balanced.
func (ap *GraphicStream) RestoreState() error {
idx := len(ap.stateList) - 1
if idx < 0 {
return errUnbalanced
}
ap.Ops(OpRestore{})
ap.State = ap.stateList[idx]
ap.stateList = ap.stateList[:idx]
return nil
}
// check if the image or content is in the resources map or generate a new name and add the object
func (ap *GraphicStream) addXobject(xobj model.XObject) model.Name {
for name, obj := range ap.resources.XObject {
if obj == xobj {
return name
}
}
// this convention must be respected so that the names are distincts
name := model.ObjName(fmt.Sprintf("XO%d", len(ap.resources.XObject)))
ap.resources.XObject[name] = xobj
return name
}
// AddXObjectDims puts an image or an XObjectForm in the current page, at the given position,
// with the given dimentions.
// See `RenderingDims` for several ways of specifying image dimentions.
func (ap *GraphicStream) AddXObjectDims(obj model.XObject, x, y, width, height Fl) {
xObjectName := ap.addXobject(obj)
ap.Ops(
OpSave{},
OpConcat{Matrix: model.Matrix{width, 0, 0, height, x, y}},
OpXObject{XObject: xObjectName},
OpRestore{},
)
}
// AddXObject is the same as AddXObjectDims, but do not change the CTM.
func (ap *GraphicStream) AddXObject(obj model.XObject) {
// since we don't change the CTM we dont need to save and restore the state
// ap.AddXObjectDims(obj, 0, 0, 1, 1)
xObjectName := ap.addXobject(obj)
ap.Ops(OpXObject{XObject: xObjectName})
}
// approximate arc for border radius
const myArc = (4.0 / 3.0) * (math.Sqrt2 - 1.0)
// RoundedRectPath returns a rectangle path with rounded corners.
// The rectangle is of width `w` and height `h`. Its upper left corner is positioned at point (`x`, `y`).
// The radius for each corner are given by `rTL` (top-left), `rTR` (top-right)
// `rBR` (bottom-right), `rBL` (bottom-left) (0 means square corners)
func RoundedRectPath(x, y, w, h, rTL, rTR, rBR, rBL model.Fl) []Operation {
out := make([]Operation, 0, 4)
out = append(out, OpMoveTo{X: x + rTL, Y: y})
xc := x + w - rTR
yc := y + rTR
out = append(out, OpLineTo{X: xc, Y: y})
if rTR > 0 {
out = append(out, OpCubicTo{X1: xc + rTR*myArc, Y1: yc - rTR, X2: xc + rTR, Y2: yc - rTR*myArc, X3: xc + rTR, Y3: yc})
}
xc = x + w - rBR
yc = y + h - rBR
out = append(out, OpLineTo{X: x + w, Y: yc})
if rBR > 0 {
out = append(out, OpCubicTo{X1: xc + rBR, Y1: yc + rBR*myArc, X2: xc + rBR*myArc, Y2: yc + rBR, X3: xc, Y3: yc + rBR})
}
xc = x + rBL
yc = y + h - rBL
out = append(out, OpLineTo{X: xc, Y: y + h})
if rBL != 0 {
out = append(out, OpCubicTo{X1: xc - rBL*myArc, Y1: yc + rBL, X2: xc - rBL, Y2: yc + rBL*myArc, X3: xc - rBL, Y3: yc})
}
xc = x + rTL
yc = y + rTL
out = append(out, OpLineTo{X: x, Y: yc})
if rTL != 0 {
out = append(out, OpCubicTo{X1: xc - rTL, Y1: yc - rTL*myArc, X2: xc - rTL*myArc, Y2: yc - rTL, X3: xc, Y3: yc - rTL})
}
return out
}