-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
656 lines (592 loc) · 15 KB
/
main.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
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
// Copyright (c) 2014 by Christoph Hack <christoph@tux21b.org>
// All rights reserved. Distributed under the Simplified BSD License.
package main
import (
"bytes"
"fmt"
"image"
_ "image/jpeg"
"log"
"math"
"os"
"strings"
"unicode"
"unicode/utf8"
"github.com/tux21b/imp/imp/otf"
"github.com/tux21b/imp/imp/pdf"
"github.com/tux21b/imp/imp/text"
)
type Imp struct {
fontNormal *otf.Font
fontBold *otf.Font
fontItalic *otf.Font
State *State
stateStack []*State
Fonts []*otf.Font
}
func (m *Imp) GetFontId(f *otf.Font) string {
for i := 0; i < len(m.Fonts); i++ {
if m.Fonts[i] == f {
return fmt.Sprintf("/F%d", i+1)
}
}
m.Fonts = append(m.Fonts, f)
return fmt.Sprintf("/F%d", len(m.Fonts))
}
type State struct {
Imp *Imp
Font *otf.Font
Size float64
SmallCaps bool
Ligatures bool
LineHeight float64
ParSkip float64
MaxWidth float64
YPos float64
ColStart float64
Justify bool
Hyphenate bool
}
func (s *State) StringToGlyphs(text string) []otf.Index {
glyphs := s.Font.StringToGlyphs(text)
if s.SmallCaps {
glyphs = s.Font.SmallCaps(glyphs)
}
if s.Ligatures {
glyphs = s.Font.Ligatures(glyphs)
}
return glyphs
}
func (s *State) Clone() *State {
cp := *s
return &cp
}
func (m *Imp) SplitLines(tokens []Token, width float64) []Token {
minima := make([]float64, len(tokens)+1)
widths := make([]float64, len(tokens)+1)
breaks := make([]int, len(tokens)+1)
maxwidth := make([]float64, len(tokens)+1)
change := make([]bool, len(tokens))
s := m.State.Clone()
for i := range tokens {
widths[i+1] = GetWidth(s, tokens[i]) + widths[i]
minima[i+1] = math.Inf(1)
maxwidth[i+1] = s.MaxWidth
}
start := 0
for start < len(tokens) {
end := len(tokens)
for i := start; i < len(tokens); i++ {
if _, ok := tokens[i].(ParagraphBreak); ok {
end = i
break
}
}
minima[start] = 0
for i := start; i < end; i++ {
spaces := 0
for j := i + 1; j <= end; j++ {
if _, ok := tokens[j-1].(CanBreak); !ok && j != end {
continue
}
w := widths[j] - widths[i]
penalty := 0.0
if cb, ok := tokens[j-1].(CanBreak); ok {
spaces++
w += GetWidth(s, cb.Before)
if t, ok := cb.Before.(Text); ok && t == "-" {
penalty += 100.0
}
}
width := maxwidth[j]
if w > width {
break
}
cost := minima[i] + penalty
if j != end {
cost += (width - w) * (width - w) / float64(spaces)
}
if cost < minima[j] {
minima[j] = cost
breaks[j] = i
}
}
}
for j := breaks[end]; j > 0; j = breaks[j] {
change[j-1] = true
}
start = end + 1
}
ntokens := make([]Token, 0, len(tokens))
for i := range tokens {
if cb, ok := tokens[i].(CanBreak); ok {
if change[i] {
ntokens = append(ntokens, cb.Before)
ntokens = append(ntokens, LineBreak{})
} else {
ntokens = append(ntokens, cb.NoBreak)
}
} else {
ntokens = append(ntokens, tokens[i])
}
}
return ntokens
}
func (m *Imp) CalcMaxAscent(line []Token) float64 {
ascent := 0.0
s := m.State.Clone()
for _, tok := range line {
GetWidth(s, tok)
switch tok.(type) {
case LineBreak, ParagraphBreak:
return ascent
case Text, Space:
a := float64(s.Font.Scale(s.Font.Ascender, 1000)) / 1000 * s.Size
if a > ascent {
ascent = a
}
}
}
return ascent
}
func main() {
fontNormal, err := otf.Open("fonts/SourceSansPro-Regular.otf")
if err != nil {
log.Fatalln(err)
}
fontBold, err := otf.Open("fonts/SourceSansPro-Bold.otf")
if err != nil {
log.Fatalln(err)
}
fontItalic, err := otf.Open("fonts/SourceSansPro-It.otf")
if err != nil {
log.Fatalln(err)
}
fontLight, err := otf.Open("fonts/SourceSansPro-Light.otf")
if err != nil {
log.Fatalln(err)
}
imgFile, err := os.Open("buddy.jpg")
if err != nil {
log.Fatalln(err)
}
defer imgFile.Close()
img, _, err := image.Decode(imgFile)
if err != nil {
log.Fatalln(err)
}
imp := &Imp{
fontNormal: fontNormal,
fontBold: fontBold,
fontItalic: fontItalic,
State: &State{
Font: fontNormal,
Size: 12,
Ligatures: true,
LineHeight: 1.4,
ParSkip: 1.8,
MaxWidth: 0.0,
},
}
out, err := os.Create("output.pdf")
if err != nil {
log.Fatalln(err)
}
defer out.Close()
w := pdf.NewPDFWriter(out)
w.WriteHeader()
var (
info = w.NextID()
root = w.NextID()
pages = w.NextID()
page = w.NextID()
contents = w.NextID()
imgId = w.NextID()
)
pageB := &Box{
Width: MustParseLength("160mm"),
Height: MustParseLength("252mm"),
PaddingTop: MustParseLength("25mm"),
PaddingRight: MustParseLength("25mm"),
PaddingBottom: MustParseLength("20mm"),
PaddingLeft: MustParseLength("25mm"),
}
tokens := Lex(fullText)
for i := 0; i < len(tokens); i++ {
switch tok := tokens[i].(type) {
case Macro:
switch tok {
case "\\par":
tokens[i] = ParagraphBreak{}
case "\\break":
tokens[i] = LineBreak{}
case "\\bold":
tokens[i] = SetFont{Font: fontBold}
case "\\light":
tokens[i] = SetFont{Font: fontLight}
case "\\normal":
tokens[i] = SetFont{Font: fontNormal}
case "\\italic":
tokens[i] = SetFont{Font: fontItalic}
case "\\Large":
tokens[i] = SetFont{Size: 24}
case "\\large":
tokens[i] = SetFont{Size: 14}
case "\\normalsize":
tokens[i] = SetFont{Size: 12}
case "\\blue":
tokens[i] = SetTextColor{1, .34, 0, .21}
case "\\black":
tokens[i] = SetTextColor{0, 0, 0, 1}
case "\\smcpon":
tokens[i] = StateAction(func(s *State) {
s.SmallCaps = true
})
case "\\smcpoff":
tokens[i] = StateAction(func(s *State) {
s.SmallCaps = false
})
case "\\justify":
tokens[i] = StateAction(func(s *State) {
s.Justify = true
})
case "\\raggedright":
tokens[i] = StateAction(func(s *State) {
s.Justify = false
})
case "\\column":
tokens[i] = StateAction(func(s *State) {
s.ColStart = s.YPos
s.MaxWidth = 0.48 * s.MaxWidth
})
case "\\nextcolumn":
tokens[i] = ColBreak{}
}
case Space:
if strings.Count(string(tok), "\n") >= 2 {
tokens[i] = ParagraphBreak{}
} else {
tokens[i] = CanBreak{NoBreak: tok}
}
case Text:
parts := text.Hyphenate(string(tok))
repl := make([]Token, 0, 2*len(parts)-1)
for j := range parts {
if j > 0 {
repl = append(repl, CanBreak{Before: Text("-")})
}
repl = append(repl, Text(parts[j]))
}
tokens = append(tokens[:i], append(repl, tokens[i+1:]...)...)
i += len(repl) - 1
}
}
imp.State.MaxWidth = float64(pageB.Width.Computed)
tokens = imp.SplitLines(tokens, 0)
w.WriteObjectf(info, "<< /Title (Hallo Welt) >>")
w.WriteObjectf(root, "<< /Type /Catalog /Pages %d 0 R >>", pages)
w.WriteObjectf(page, `<<
/Type /Page
/Parent %d 0 R
/Contents %d 0 R
>>`, pages, contents)
buf := &bytes.Buffer{}
fmt.Fprintf(buf, ".5 w .9 G %.4f %.4f %.4f %.4f re S\n",
pageB.PaddingLeft.Computed,
pageB.PaddingBottom.Computed,
pageB.Width.Computed,
pageB.Height.Computed)
imp.State.YPos = float64(pageB.PaddingBottom.Computed+pageB.Height.Computed) - imp.CalcMaxAscent(tokens)
fmt.Fprintf(buf, "BT /F1 %.4f Tf\n1.4 TL\n%.4f %.4f Td\n",
imp.State.Size, pageB.PaddingLeft.Computed, imp.State.YPos)
inTJ := false
wordSpacing := 0.0
updateSpacing := -1
yMin := 0.0
for pos, token := range tokens {
if pos >= updateSpacing {
width := 0.0
numSpaces := 0
wordSpacing = 0
updateSpacing = len(tokens)
s := imp.State.Clone()
for i := pos; i < len(tokens); i++ {
w := GetWidth(s, tokens[i])
switch tokens[i].(type) {
case LineBreak:
if s.Justify {
wordSpacing = (s.MaxWidth - width) / float64(numSpaces)
} else {
wordSpacing = 0
}
updateSpacing = i + 1
i = len(tokens)
case ParagraphBreak:
updateSpacing = i + 1
i = len(tokens)
case Space:
numSpaces++
}
width += w
}
}
switch x := token.(type) {
case Text:
if !inTJ {
buf.WriteString("[")
inTJ = true
}
buf.WriteString("<")
glyphs := imp.State.StringToGlyphs(string(x))
for i := range glyphs {
if i > 0 {
kern := imp.State.Font.Kerning(1000, glyphs[i-1], glyphs[i])
if kern != 0 {
fmt.Fprintf(buf, "> %d <", -kern)
}
}
fmt.Fprintf(buf, "%04x", glyphs[i])
}
buf.WriteString("> ")
case Space:
if !inTJ {
buf.WriteString("[")
inTJ = true
}
fmt.Fprintf(buf, "<%04x> ", imp.State.Font.Index(' '))
if wordSpacing > 0 {
fmt.Fprintf(buf, "%d ", -int(wordSpacing/imp.State.Size*1000))
}
case LineBreak:
if inTJ {
buf.WriteString("] TJ\n")
inTJ = false
}
fmt.Fprintf(buf, "0 %.4f Td\n", -imp.State.LineHeight*imp.State.Size)
imp.State.YPos += -imp.State.LineHeight * float64(imp.State.Size)
case ParagraphBreak:
if inTJ {
buf.WriteString("] TJ\n")
inTJ = false
}
fmt.Fprintf(buf, "0 %.4f Td\n", -imp.State.LineHeight*imp.State.Size*imp.State.ParSkip)
imp.State.YPos += -imp.State.LineHeight * float64(imp.State.Size) * imp.State.ParSkip
case ColBreak:
if inTJ {
buf.WriteString("] TJ\n")
inTJ = false
}
yOff := imp.State.ColStart - imp.State.YPos
xOff := float64(pageB.Width.Computed) - imp.State.MaxWidth
fmt.Fprintf(buf, "%.4f %.4f Td\n", xOff, yOff)
yMin = imp.State.YPos
imp.State.YPos = imp.State.ColStart
case SetFont:
if inTJ {
buf.WriteString("] TJ\n")
inTJ = false
}
if x.Font != nil {
imp.State.Font = x.Font
}
if x.Size != 0 {
imp.State.Size = float64(x.Size)
}
id := imp.GetFontId(imp.State.Font)
fmt.Fprintf(buf, "%s %.4f Tf\n", id, imp.State.Size)
case SetTextColor:
if inTJ {
buf.WriteString("] TJ\n")
inTJ = false
}
fmt.Fprintf(buf, "%.4f %.4f %.4f %.4f k\n", x.C, x.M, x.Y, x.K)
case StateAction:
x(imp.State)
}
}
if inTJ {
buf.WriteString("] TJ\n")
}
buf.WriteString("ET\n")
if y := imp.State.YPos; y < yMin {
yMin = y
}
imgS := img.Bounds().Size()
imgB := &ImageBox{
B: Bounds{
X: float64(pageB.PaddingLeft.Computed),
Y: float64(pageB.PaddingBottom.Computed),
W: float64(pageB.Width.Computed),
H: float64(imgS.Y) * float64(pageB.Width.Computed) / float64(imgS.X),
},
Img: img,
}
fmt.Fprintf(buf, `q 1 0 0 1 %.4f %.4f cm %.4f 0 0 %.4f 0 0 cm /I1 Do Q `,
imgB.B.X, imgB.B.Y, imgB.B.W, imgB.B.H)
w.WriteObjectStart(contents)
w.WriteStreamPlain(buf.String())
w.WriteObjectEnd()
fontBuf := &bytes.Buffer{}
fontIds := make([]int, len(imp.Fonts))
for i := range imp.Fonts {
fontIds[i] = w.NextID()
fmt.Fprintf(fontBuf, "/F%d %d 0 R ", i+1, fontIds[i])
}
w.WriteObjectf(pages, `<<
/Type /Pages
/MediaBox [0 0 %.4f %.4f]
/Resources
<<
/Font << %s >>
/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]
/XObject << /I1 %d 0 R >>
>>
/Kids [%d 0 R]
/Count 1
>>`, pageB.TotalWidth(), pageB.TotalHeight(), fontBuf.String(), imgId, page)
for i := range imp.Fonts {
w.WriteFontEmbedded(fontIds[i], imp.Fonts[i])
}
w.WriteImageJPEG(imgId, img)
w.WriteFooter(root, info)
}
func Lex(input string) []Token {
var tokens []Token
pos := 0
for pos < len(input) {
r, n := utf8.DecodeRuneInString(input[pos:])
if unicode.IsSpace(r) {
end := pos + n
for end < len(input) {
r, n := utf8.DecodeRuneInString(input[end:])
if !unicode.IsSpace(r) {
break
}
end += n
}
tokens = append(tokens, Space(input[pos:end]))
pos = end
} else if r == '\\' {
end := pos + n
for end < len(input) {
r, n := utf8.DecodeRuneInString(input[end:])
if !unicode.IsLetter(r) {
break
}
end += n
}
tokens = append(tokens, Macro(input[pos:end]))
pos = end
for pos < len(input) {
r, n := utf8.DecodeRuneInString(input[pos:])
if !unicode.IsSpace(r) {
break
}
pos += n
}
} else {
end := pos + n
for end < len(input) {
r, n := utf8.DecodeRuneInString(input[end:])
if unicode.IsSpace(r) || r == '\\' {
break
}
end += n
}
tokens = append(tokens, Text(input[pos:end]))
pos = end
}
}
return tokens
}
func GetWidth(s *State, t Token) float64 {
switch t := t.(type) {
case Text:
glyphs := s.StringToGlyphs(string(t))
width := 0.0
for i := range glyphs {
width += float64(s.Font.Scale(s.Font.HMetric(glyphs[i]).Width, 1000)) / 1000 * s.Size
if i > 0 {
kern := s.Font.Kerning(1000, glyphs[i-1], glyphs[i])
if kern != 0 {
width += float64(kern) / 1000 * s.Size
}
}
}
return width
case CanBreak:
return GetWidth(s, t.NoBreak)
case Space:
return float64(s.Font.Scale(s.Font.HMetric(s.Font.Index(' ')).Width, 1000)) / 1000 * s.Size
case SetFont:
if t.Font != nil {
s.Font = t.Font
}
if t.Size != 0 {
s.Size = float64(t.Size)
}
case StateAction:
t(s)
}
return 0
}
type Token interface {
// Execute(s *State, w *bytes.Buffer)
}
type LineBreak struct{}
type ParagraphBreak struct{}
type CanBreak struct {
Before Token
NoBreak Token
After Token
}
type Text string
type Space string
type Macro string
type SetTextColor struct {
C, M, Y, K float32
}
type ColBreak struct{}
type SetFont struct {
Font *otf.Font
Size int
}
type Bounds struct {
X, Y float64
W, H float64
}
type ImageBox struct {
B Bounds
Img image.Image
}
type StateAction func(s *State)
var fullText = `\Large\bold\blue\smcpon Hello Imp!\smcpoff\normal\normalsize\black\par
\large\light\justify This output was produced by \normal Imp\light, a very early
prototype of a \italic modern typesetting system \light written in Go. Imp is able
to output PDF files, has full Unicode support and supports modern font
formats like OpenType™ and TrueType™.\normal\normalsize\par\break
\column\justify\blue\smcpon\bold OpenType™ Fonts\smcpoff\normal\black\par
You can use your favorite OpenType™ and TrueType™ fonts with Imp, including
special features like \italic kerning\normal, \italic ligatures \normal and
\italic small caps\normal. Adobe's excellent \bold Source Sans Pro \normal
font family is included by default.
\blue\smcpon\bold Unicode Support\smcpoff\normal\black\par
Imp comes with full Unicode support. You can simply type any character you
want and Imp will happily display it as long as your font contains a suitable
glyph for it.
\blue\smcpon\bold Extensive Markup\smcpoff\normal\black\par
Future versions of Imp should feature a simple markup language with an
extensive macro system similar to \italic TeX \normal or \italic lout\normal.
Defining such a language is however a very complex task and no
progress has been made so far.
\nextcolumn\blue\smcpon\bold Go Package\smcpoff\normal\black\par
Imp's main strength is typesetting generated content automatically in a
beautiful way. The Go package allows you to easily embed Imp in your own
application for server side PDF generation. Complex layouts can be achieved
by extending Imp with additional plug-ins written in Go.
\blue\smcpon\bold Open Source\smcpoff\normal\black\par
The whole project is available freely and licensed under the \italic
BSD (3 clause) license\normal. Development has just started and the
source code of the prototype still looks horrible. Sorry for that.
Anyway, feel free to grab the source from \bold GitHub \normal and join
the project today!`