Repository navigation
Expand file tree
/
Copy pathcache_content_text.go
More file actions
558 lines (482 loc) · 16.1 KB
/
Copy pathcache_content_text.go
File metadata and controls
558 lines (482 loc) · 16.1 KB
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
package gopdf
import (
"errors"
"fmt"
"io"
"math"
"strconv"
)
const defaultCoefLineHeight = float64(1)
const defaultCoefUnderlinePosition = float64(1)
const defaultcoefUnderlineThickness = float64(1)
// ContentTypeCell cell
const ContentTypeCell = 0
// ContentTypeText text
const ContentTypeText = 1
var ErrContentTypeNotFound = errors.New("contentType not found")
type cacheContentText struct {
//---setup---
rectangle *Rect
textColor ICacheColorText
grayFill float64
txtColorMode string
fontCountIndex int //Curr.FontFontCount+1
fontSize float64
fontStyle int
charSpacing float64
setXCount int //จำนวนครั้งที่ใช้ setX
x, y float64
fontSubset *SubsetFontObj
pageheight float64
contentType int
cellOpt CellOption
lineWidth float64
text string
//---result---
cellWidthPdfUnit, textWidthPdfUnit float64
cellHeightPdfUnit float64
isPlaceHolder bool
}
func (c *cacheContentText) isSame(cache cacheContentText) bool {
if c.rectangle != nil {
//if rectangle != nil we assume this is not same content
return false
}
// if both colors are nil we assume them equal
if ((c.textColor == nil && cache.textColor == nil) ||
(c.textColor != nil && c.textColor.equal(cache.textColor))) &&
c.grayFill == cache.grayFill &&
c.fontCountIndex == cache.fontCountIndex &&
c.fontSize == cache.fontSize &&
c.fontStyle == cache.fontStyle &&
c.charSpacing == cache.charSpacing &&
c.setXCount == cache.setXCount &&
c.y == cache.y &&
c.isPlaceHolder == cache.isPlaceHolder {
return true
}
return false
}
func (c *cacheContentText) setPageHeight(pageheight float64) {
c.pageheight = pageheight
}
func (c *cacheContentText) pageHeight() float64 {
return c.pageheight //841.89
}
func convertTypoUnit(val float64, unitsPerEm uint, fontSize float64) float64 {
val = val * 1000.00 / float64(unitsPerEm)
return val * fontSize / 1000.0
}
// justifyAdjustment returns the TJ-array number to emit after each interior
// space so that a line of glyphs (textWidth) is stretched to fill its cell.
// slackPts is (cellWidth - textWidth) in points, spread over gapCount gaps.
// TJ numbers are thousandths of glyph space, scaled by font size, and are
// SUBTRACTED from the pen advance, so a negative number widens the gap.
// Returns 0 when there is nothing to distribute.
func justifyAdjustment(slackPts float64, gapCount int, fontSize float64) int {
if gapCount <= 0 || slackPts <= 0 || fontSize <= 0 {
return 0
}
perGap := slackPts / float64(gapCount)
return int(math.Round(-(perGap * 1000.0 / fontSize)))
}
// Fallback ratios (fractions of the logical font size) used when a font's
// OS/2 table carries no usable script metrics.
const defaultScriptScale = 0.583
const defaultSuperscriptRise = 0.333
const defaultSubscriptDrop = 0.141
// scriptFontSizeAndRise returns the glyph size to emit in Tf and the Ts
// baseline rise (both in points) for the given style; plain styles return
// (fontSize, 0). The logical fontSize keeps governing vertical layout; only
// glyph size and baseline shift are derived here. Superscript wins if both
// script bits are set.
func scriptFontSizeAndRise(f *SubsetFontObj, fontStyle int, fontSize float64) (float64, float64) {
super := fontStyle&Superscript == Superscript
sub := fontStyle&Subscript == Subscript
if !super && !sub {
return fontSize, 0
}
unitsPerEm := float64(f.ttfp.UnitsPerEm())
// frac converts an OS/2 metric to a fraction of the em, or falls back
// when the font has no usable value.
frac := func(metric int, fallback float64) float64 {
if metric > 0 && unitsPerEm > 0 {
return float64(metric) / unitsPerEm
}
return fallback
}
if super {
return fontSize * frac(f.ttfp.SuperscriptYSize(), defaultScriptScale),
fontSize * frac(f.ttfp.SuperscriptYOffset(), defaultSuperscriptRise)
}
return fontSize * frac(f.ttfp.SubscriptYSize(), defaultScriptScale),
-fontSize * frac(f.ttfp.SubscriptYOffset(), defaultSubscriptDrop)
}
// nonSpaceBounds returns the byte index of the first and last non-space
// (' ') rune in text, or (-1, -1) when text is empty or all spaces.
func nonSpaceBounds(text string) (first, last int) {
first, last = -1, -1
for i, r := range text {
if r != ' ' {
if first < 0 {
first = i
}
last = i
}
}
return first, last
}
// interiorSpaceCount counts the ' ' runes that have a non-space rune both
// before and after them (i.e. word gaps eligible for justification, with
// leading/trailing spaces excluded).
func interiorSpaceCount(text string) int {
first, last := nonSpaceBounds(text)
if first < 0 {
return 0
}
count := 0
for i, r := range text {
if r == ' ' && i > first && i < last {
count++
}
}
return count
}
// lineAlign returns the alignment to apply to a single wrapped line. The last
// line of a justified paragraph is left-aligned (standard typographic
// behavior) rather than stretched; all other cases are returned unchanged.
func lineAlign(align int, isLastLine bool) int {
if isLastLine && align&Justify == Justify {
return align&^Justify | Left
}
return align
}
func (c *cacheContentText) calTypoAscender() float64 {
return convertTypoUnit(float64(c.fontSubset.ttfp.TypoAscender()), c.fontSubset.ttfp.UnitsPerEm(), float64(c.fontSize))
}
func (c *cacheContentText) calTypoDescender() float64 {
return convertTypoUnit(float64(c.fontSubset.ttfp.TypoDescender()), c.fontSubset.ttfp.UnitsPerEm(), float64(c.fontSize))
}
func (c *cacheContentText) calY() (float64, error) {
pageHeight := c.pageHeight()
if c.contentType == ContentTypeText {
return pageHeight - c.y, nil
} else if c.contentType == ContentTypeCell {
y := float64(0.0)
if c.cellOpt.Align&Bottom == Bottom {
y = pageHeight - c.y - c.cellHeightPdfUnit - c.calTypoDescender()
} else if c.cellOpt.Align&Middle == Middle {
y = pageHeight - c.y - c.cellHeightPdfUnit*0.5 - (c.calTypoDescender()+c.calTypoAscender())*0.5
} else {
//top
y = pageHeight - c.y - c.calTypoAscender()
}
return y, nil
}
return 0.0, ErrContentTypeNotFound
}
func (c *cacheContentText) calX() (float64, error) {
if c.contentType == ContentTypeText {
return c.x, nil
} else if c.contentType == ContentTypeCell {
x := float64(0.0)
if c.cellOpt.Align&Right == Right {
x = c.x + c.cellWidthPdfUnit - c.textWidthPdfUnit
} else if c.cellOpt.Align&Center == Center {
x = c.x + c.cellWidthPdfUnit*0.5 - c.textWidthPdfUnit*0.5
} else {
x = c.x
}
return x, nil
}
return 0.0, ErrContentTypeNotFound
}
// FormatFloatTrim converts a float64 into a string, like Sprintf("%.3f")
// but with trailing zeroes (and possibly ".") removed
func FormatFloatTrim(floatval float64) (formatted string) {
const precisionFactor = 1000.0
roundedFontSize := math.Round(precisionFactor*floatval) / precisionFactor
return strconv.FormatFloat(roundedFontSize, 'f', -1, 64)
}
func (c *cacheContentText) write(w io.Writer, protection *PDFProtection) error {
x, err := c.calX()
if err != nil {
return err
}
y, err := c.calY()
if err != nil {
return err
}
hasTransparency := len(c.cellOpt.extGStateIndexes) > 0
if hasTransparency {
if _, err := io.WriteString(w, "q\n"); err != nil {
return err
}
}
for _, extGStateIndex := range c.cellOpt.extGStateIndexes {
linkToGSObj := fmt.Sprintf("/GS%d gs\n", extGStateIndex)
if _, err := io.WriteString(w, linkToGSObj); err != nil {
return err
}
}
if _, err := io.WriteString(w, "BT\n"); err != nil {
return err
}
// Superscript/subscript: glyphs shrink to the effective size and the
// baseline shifts via Ts. Ts is written for every draw (0 for plain
// text) because text state persists across BT/ET blocks.
effFontSize, textRise := scriptFontSizeAndRise(c.fontSubset, c.fontStyle, c.fontSize)
fmt.Fprintf(w, "%0.2f %0.2f TD\n", x, y)
fmt.Fprintf(w, "/F%d %s Tf %s Tc %s Ts\n", c.fontCountIndex, FormatFloatTrim(effFontSize), FormatFloatTrim(c.charSpacing), FormatFloatTrim(textRise))
if c.txtColorMode == "color" {
c.textColor.write(w, protection)
}
io.WriteString(w, "[<")
// justify: distribute leftover width across interior word gaps by emitting
// a negative TJ number after each interior space (widening the gap).
justify := c.contentType == ContentTypeCell &&
c.cellOpt.Align&Justify == Justify &&
c.rectangle != nil
tjAdjust := 0
firstNonSpace, lastNonSpace := -1, -1
if justify {
slack := c.cellWidthPdfUnit - c.textWidthPdfUnit
tjAdjust = justifyAdjustment(slack, interiorSpaceCount(c.text), effFontSize)
if tjAdjust == 0 {
justify = false // no slack or no gaps: fall back to left alignment
} else {
firstNonSpace, lastNonSpace = nonSpaceBounds(c.text)
}
}
unitsPerEm := int(c.fontSubset.ttfp.UnitsPerEm())
var leftRune rune
var leftRuneIndex uint
for i, r := range c.text {
glyphindex, err := c.fontSubset.CharIndex(r)
if err == ErrCharNotFound {
continue
} else if err != nil {
return err
}
pairvalPdfUnit := 0
if i > 0 && c.fontSubset.ttfFontOption.UseKerning { //kerning
pairval := kern(c.fontSubset, leftRune, r, leftRuneIndex, glyphindex)
pairvalPdfUnit = convertTTFUnit2PDFUnit(int(pairval), unitsPerEm)
if pairvalPdfUnit != 0 {
fmt.Fprintf(w, ">%d<", (-1)*pairvalPdfUnit)
}
}
fmt.Fprintf(w, "%04X", glyphindex)
if justify && r == ' ' && i > firstNonSpace && i < lastNonSpace {
fmt.Fprintf(w, ">%d<", tjAdjust)
}
leftRune = r
leftRuneIndex = glyphindex
}
io.WriteString(w, ">] TJ\n")
io.WriteString(w, "ET\n")
if c.fontStyle&Underline == Underline {
if err := c.underline(w); err != nil {
return err
}
}
c.drawBorder(w)
if hasTransparency {
if _, err := io.WriteString(w, "Q\n"); err != nil {
return err
}
}
return nil
}
func (c *cacheContentText) drawBorder(w io.Writer) error {
//stream.WriteString(fmt.Sprintf("%.2f w\n", 0.1))
lineOffset := c.lineWidth * 0.5
if c.cellOpt.Border&Top == Top {
startX := c.x - lineOffset
startY := c.pageHeight() - c.y
endX := c.x + c.cellWidthPdfUnit + lineOffset
endY := startY
_, err := fmt.Fprintf(w, "%0.2f %0.2f m %0.2f %0.2f l s\n", startX, startY, endX, endY)
if err != nil {
return err
}
}
if c.cellOpt.Border&Left == Left {
startX := c.x
startY := c.pageHeight() - c.y
endX := c.x
endY := startY - c.cellHeightPdfUnit
_, err := fmt.Fprintf(w, "%0.2f %0.2f m %0.2f %0.2f l s\n", startX, startY, endX, endY)
if err != nil {
return err
}
}
if c.cellOpt.Border&Right == Right {
startX := c.x + c.cellWidthPdfUnit
startY := c.pageHeight() - c.y
endX := c.x + c.cellWidthPdfUnit
endY := startY - c.cellHeightPdfUnit
_, err := fmt.Fprintf(w, "%0.2f %0.2f m %0.2f %0.2f l s\n", startX, startY, endX, endY)
if err != nil {
return err
}
}
if c.cellOpt.Border&Bottom == Bottom {
startX := c.x - lineOffset
startY := c.pageHeight() - c.y - c.cellHeightPdfUnit
endX := c.x + c.cellWidthPdfUnit + lineOffset
endY := startY
_, err := fmt.Fprintf(w, "%0.2f %0.2f m %0.2f %0.2f l s\n", startX, startY, endX, endY)
if err != nil {
return err
}
}
return nil
}
func (c *cacheContentText) underline(w io.Writer) error {
if c.fontSubset == nil {
return errors.New("error AppendUnderline not found font")
}
coefLineHeight := defaultCoefLineHeight
if c.cellOpt.CoefLineHeight != 0 {
coefLineHeight = c.cellOpt.CoefLineHeight
}
coefUnderlinePosition := defaultCoefUnderlinePosition
if c.cellOpt.CoefUnderlinePosition != 0 {
coefUnderlinePosition = c.cellOpt.CoefUnderlinePosition
}
coefUnderlineThickness := defaultcoefUnderlineThickness
if c.cellOpt.CoefUnderlineThickness != 0 {
coefUnderlineThickness = c.cellOpt.CoefUnderlineThickness
}
ascenderPx := c.fontSubset.GetAscenderPx(c.fontSize)
descenderPx := -c.fontSubset.GetDescenderPx(c.fontSize)
contentHeight := ascenderPx + descenderPx
virtualHeight := coefLineHeight * float64(c.fontSize)
leading := (contentHeight - virtualHeight) / 2
baseline := ascenderPx + leading
underlinePositionPx := c.fontSubset.GetUnderlinePositionPx(c.fontSize) * coefUnderlinePosition
underlineThicknessPx := c.fontSubset.GetUnderlineThicknessPx(c.fontSize) * coefUnderlineThickness
yUnderlinePosition := c.pageHeight() - c.y + underlinePositionPx - baseline
if _, err := fmt.Fprintf(w, "%0.2f %0.2f %0.2f %0.2f re f\n", c.x, yUnderlinePosition, c.cellWidthPdfUnit, underlineThicknessPx); err != nil {
return err
}
return nil
}
func (c *cacheContentText) createContent() (float64, float64, error) {
cellWidthPdfUnit, cellHeightPdfUnit, textWidthPdfUnit, err := createContent(c.fontSubset, c.text, c.fontSize, c.fontStyle, c.charSpacing, c.rectangle)
if err != nil {
return 0, 0, err
}
c.cellWidthPdfUnit = cellWidthPdfUnit
c.cellHeightPdfUnit = cellHeightPdfUnit
c.textWidthPdfUnit = textWidthPdfUnit
return cellWidthPdfUnit, cellHeightPdfUnit, nil
}
func createContent(f *SubsetFontObj, text string, fontSize float64, fontStyle int, charSpacing float64, rectangle *Rect) (float64, float64, float64, error) {
// Widths use the effective (script-scaled) glyph size so measurement and
// wrapping match rendering; heights keep the logical size so script text
// shares the line layout of its neighbors.
effFontSize, _ := scriptFontSizeAndRise(f, fontStyle, fontSize)
unitsPerEm := int(f.ttfp.UnitsPerEm())
var leftRune rune
var leftRuneIndex uint
sumWidth := int(0)
//fmt.Printf("unitsPerEm = %d", unitsPerEm)
for i, r := range text {
glyphindex, err := f.CharIndex(r)
if err == ErrCharNotFound {
continue
} else if err != nil {
return 0, 0, 0, err
}
pairvalPdfUnit := 0
if i > 0 && f.ttfFontOption.UseKerning { //kerning
pairval := kern(f, leftRune, r, leftRuneIndex, glyphindex)
pairvalPdfUnit = convertTTFUnit2PDFUnit(int(pairval), unitsPerEm)
}
width, err := f.CharWidth(r)
if err != nil {
return 0, 0, 0, err
}
unitsPerPt := float64(unitsPerEm) / effFontSize
spaceWidthInPt := unitsPerPt * charSpacing
spaceWidthPdfUnit := convertTTFUnit2PDFUnit(int(spaceWidthInPt), unitsPerEm)
sumWidth += int(width) + int(pairvalPdfUnit) + spaceWidthPdfUnit
leftRune = r
leftRuneIndex = glyphindex
}
cellWidthPdfUnit := float64(0)
cellHeightPdfUnit := float64(0)
if rectangle == nil {
cellWidthPdfUnit = float64(sumWidth) * (effFontSize / 1000.0)
typoAscender := convertTypoUnit(float64(f.ttfp.TypoAscender()), f.ttfp.UnitsPerEm(), float64(fontSize))
typoDescender := convertTypoUnit(float64(f.ttfp.TypoDescender()), f.ttfp.UnitsPerEm(), float64(fontSize))
cellHeightPdfUnit = typoAscender - typoDescender
} else {
cellWidthPdfUnit = rectangle.W
cellHeightPdfUnit = rectangle.H
}
textWidthPdfUnit := float64(sumWidth) * (effFontSize / 1000.0)
return cellWidthPdfUnit, cellHeightPdfUnit, textWidthPdfUnit, nil
}
func kern(f *SubsetFontObj, leftRune rune, rightRune rune, leftIndex uint, rightIndex uint) int16 {
pairVal := int16(0)
if haveKerning, kval := f.KernValueByLeft(leftIndex); haveKerning {
if ok, v := kval.ValueByRight(rightIndex); ok {
pairVal = v
}
}
if f.funcKernOverride != nil {
pairVal = f.funcKernOverride(
leftRune,
rightRune,
leftIndex,
rightIndex,
pairVal,
)
}
return pairVal
}
// CacheContent Export cacheContent
type CacheContent struct {
cacheContentText
}
// Setup setup all information for cacheContent
func (c *CacheContent) Setup(rectangle *Rect,
textColor ICacheColorText,
grayFill float64,
fontCountIndex int, //Curr.FontFontCount+1
fontSize float64,
fontStyle int,
charSpacing float64,
setXCount int, //จำนวนครั้งที่ใช้ setX
x, y float64,
fontSubset *SubsetFontObj,
pageheight float64,
contentType int,
cellOpt CellOption,
lineWidth float64,
) {
c.cacheContentText = cacheContentText{
fontSubset: fontSubset,
rectangle: rectangle,
textColor: textColor,
grayFill: grayFill,
fontCountIndex: fontCountIndex,
fontSize: fontSize,
fontStyle: fontStyle,
charSpacing: charSpacing,
setXCount: setXCount,
x: x,
y: y,
pageheight: pageheight,
contentType: ContentTypeCell,
cellOpt: cellOpt,
lineWidth: lineWidth,
}
}
// WriteTextToContent write text to content
func (c *CacheContent) WriteTextToContent(text string) {
c.cacheContentText.text += text
}