-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpicturebook.go
1169 lines (853 loc) · 29.4 KB
/
picturebook.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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package picturebook
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"image/png"
"io"
"log/slog"
"path/filepath"
"strings"
"sync"
"github.com/aaronland/go-image/decode"
"github.com/aaronland/go-image/rotate"
"github.com/aaronland/go-mimetypes"
"github.com/aaronland/go-picturebook/bucket"
"github.com/aaronland/go-picturebook/caption"
"github.com/aaronland/go-picturebook/filter"
"github.com/aaronland/go-picturebook/picture"
"github.com/aaronland/go-picturebook/process"
"github.com/aaronland/go-picturebook/progress"
"github.com/aaronland/go-picturebook/sort"
"github.com/aaronland/go-picturebook/tempfile"
"github.com/aaronland/go-picturebook/text"
"github.com/go-pdf/fpdf"
"github.com/sfomuseum/go-font-ocra"
)
// MM2INCH defines the number if millimeters in an inch.
const MM2INCH float64 = 25.4
// PictureBookOptions defines a struct containing configuration information for a given picturebook instance.
type PictureBookOptions struct {
// The orientation of the final picturebook. Valid options are "P" and "L" for portrait and landscape respectively.
Orientation string
// A string label corresponding to known size. Valid options are "a1", "a2", "a3", "a4", "a5", "a6", "a7", "letter", "legal" and "tabloid".
Size string
// The width of the final picturebook.
Width float64
// The height of the final picturebook.
Height float64
// The unit of measurement to use for the `Width` and `Height` options.
Units string
// The number dots per inch to use when calculating the size of the final picturebook. Valid options are "inches", "centimeters", "millimeters".
DPI float64
// The size of any border to apply to each image in the final picturebook.
Border float64
// The size of any additional bleed to apply to the final picturebook.
Bleed float64
// The size of any margin to add to the top of each page.
MarginTop float64
// The size of any margin to add to the bottom of each page.
MarginBottom float64
// The size of any margin to add to the left-hand side of each page.
MarginLeft float64
// The size of any margin to add to the right-hand side of each page.
MarginRight float64
// An optional `filter.Filter` instance used to determine whether or not an image should be included in the final picturebook.
Filter filter.Filter
// Zero or more optional `process.Process` instance used to transform images being included in the final picturebook.
PreProcess process.Process
// Zero or more optional `process.Process` instance used to transform images after having been rotated to fill the page and before being included in the final picturebook.
RotateToFillPostProcess process.Process
// An optional `caption.Caption` instance used to derive a caption string for each image added to the final picturebook.
Caption caption.Caption
// An optional `text.Text` instance used to derive a text string for each image added to the final picturebook.
Text text.Text
// An optional `sort.Sorter` instance used to sort images before they are added to the final picturebook.
Sort sort.Sorter
// A boolean value signaling that an image should be rotated if necessary to fill the maximum amount of any given page.
FillPage bool
// A boolean value to enable verbose logging during the creation of a picturebook.
Verbose bool
// A boolean value to enable to use of an OCRA font for writing captions.
OCRAFont bool
// A `aaronland/go-picturebook/bucket.Bucket` instance where picturebook data is read from.
Source bucket.Bucket
// A `aaronland/go-picturebook/bucket.Bucket` instance where the final picturebook is written to.
Target bucket.Bucket
// A `aaronland/go-picturebook/bucket.Bucket` instance where the temporary files necessary in the creation of the picturebook are written to.
Temporary bucket.Bucket
// A `aaronland/go-picturebook/progress.Monitor` instance used to signal picturebook creation progress.
Monitor progress.Monitor
// A boolean value signaling that images should only be added on even-numbered pages.
EvenOnly bool
// A boolean value signaling that images should only be added on odd-numbered pages.
OddOnly bool
// An optional value to indicate that a picturebook should not exceed this number of pages
MaxPages int
}
// type PictureBookMargins defines a struct for storing margins to be applied to a picturebook
type PictureBookMargins struct {
// The size of any margin to add to the top of each page.
Top float64
// The size of any margin to add to the bottom of each page.
Bottom float64
// The size of any margin to add to the left-hand side of each page.
Left float64
// The size of any margin to add to the right-hand side of each page.
Right float64
}
// type PictureBookBorders defines a struct for storing borders to be applied to a images in a picturebook.
type PictureBookBorders struct {
// The size of any border to add to the top of each image.
Top float64
// The size of any border to add to the bottom of each image.
Bottom float64
// The size of any border to add to the left-hand side of each image.
Left float64
// The size of any border to add to the right-hand side of each image.
Right float64
}
// type PictureBookCanvas defines a struct for storing canvas information for a picturebook.
type PictureBookCanvas struct {
// The width of the internal picturebook canvas.
Width float64
// The height of the internal picturebook canvas.
Height float64
}
// type PictureBookText defines a struct for storing information for how text should be displayed in a picturebook.
type PictureBookText struct {
// The name of the font to use for text strings.
Font string
// The style of the font to use for text strings.
Style string
// The size of the font to use for text strings.
Size float64
// The margin to apply to text strings.
Margin float64
// The colour of the font to use for text strings.
Colour []int
}
// type PictureBook provides a struct for creating a PDF file from a folder of images (a picturebook).
type PictureBook struct {
// A `fpdf.Fpdf` instance used to produce the picturebook PDF file.
PDF *fpdf.Fpdf
// A `sync.Mutex` instance used to add images in an orderly fashion.
Mutex *sync.Mutex
// The `PictureBookBorders` definition to use for this picturebook
Borders *PictureBookBorders
// The `PictureBookMargins` definition to use for this picturebook
Margins *PictureBookMargins
// The `PictureBookCanvas` definition to use for this picturebook
Canvas PictureBookCanvas
// The `PictureBookText` definition to use for this picturebook
Text PictureBookText
// The `PictureBookOptions` used to create this picturebook
Options *PictureBookOptions
// The `GatherPicturesProcessFunc` function used to determine whether an image is included in a picturebook
ProcessFunc GatherPicturesProcessFunc
// The number of pages in this picturebook
pages int
// A list of temporary files used in the creation of a picturebook and to be removed when the picturebook is saved
tmpfiles []string
monitor progress.Monitor
}
// type GatherPicturesProcessFunc defines a method for processing the path to an image file in to a `picture.PictureBookPicture` instance.
type GatherPicturesProcessFunc func(context.Context, string) (*picture.PictureBookPicture, error)
// DefaultGatherPicturesProcessFunc returns a default GatherPicturesProcessFunc used to derive a `picture.PictureBookPicture` instance
//
// from the path to an image file. It applies any filters and transformation processes and derives caption data per settings defined in 'pb_opts'.
func DefaultGatherPicturesProcessFunc(pb_opts *PictureBookOptions) (GatherPicturesProcessFunc, error) {
fn := func(ctx context.Context, path string) (*picture.PictureBookPicture, error) {
select {
case <-ctx.Done():
return nil, nil
default:
// pass
}
abs_path := path
is_image := false
logger := slog.Default()
logger = logger.With("path", abs_path)
// Be sure to strip/account for fragment if present
parts := strings.Split(path, "#")
ext := filepath.Ext(parts[0])
ext = strings.ToLower(ext)
for _, t := range mimetypes.TypesByExtension(ext) {
if strings.HasPrefix(t, "image/") {
is_image = true
break
}
}
if !is_image {
logger.Debug("File does not appear to be an image, skipping", "extension", ext)
return nil, nil
}
if pb_opts.Filter != nil {
ok, err := pb_opts.Filter.Continue(ctx, pb_opts.Source, abs_path)
if err != nil {
logger.Error("Failed to filter image", "error", err)
return nil, nil
}
if !ok {
return nil, nil
}
logger.Debug("Include image")
}
caption := ""
text_body := ""
if pb_opts.Caption != nil {
txt, err := pb_opts.Caption.Text(ctx, pb_opts.Source, abs_path)
if err != nil {
logger.Error("Failed to derive caption text", "error", err)
return nil, nil
}
caption = txt
}
if pb_opts.Text != nil {
txt, err := pb_opts.Text.Body(ctx, pb_opts.Source, abs_path)
if err != nil {
logger.Error("Failed to derive text body", "error", err)
return nil, nil
}
text_body = txt
}
var final_bucket bucket.Bucket
final_path := parts[0] // abs_path
var tmpfile_path string
if pb_opts.PreProcess != nil {
logger.Debug("Pre-processing image")
processed_path, err := pb_opts.PreProcess.Transform(ctx, pb_opts.Source, pb_opts.Temporary, abs_path)
if err != nil {
logger.Error("Failed to process image", "error", err)
return nil, nil
}
logger.Debug("After pre-processing path becomes", "processed_path", processed_path)
if processed_path != "" && processed_path != abs_path {
final_path = processed_path
final_bucket = pb_opts.Temporary
tmpfile_path = processed_path
}
}
logger.Debug("Append path to list for processing", "final_path", final_path)
pic := &picture.PictureBookPicture{
Source: abs_path,
Bucket: final_bucket,
Path: final_path,
Caption: caption,
Text: text_body,
TempFile: tmpfile_path,
}
return pic, nil
}
return fn, nil
}
// NewPictureBookDefaultOptions returns a `PictureBookOptions` with default settings.
func NewPictureBookDefaultOptions(ctx context.Context) (*PictureBookOptions, error) {
opts := &PictureBookOptions{
Orientation: "P",
Size: "letter",
Width: 0.0,
Height: 0.0,
Units: "inches",
DPI: 150.0,
Border: 0.01,
Bleed: 0.0,
MarginTop: 1.0,
MarginBottom: 1.0,
MarginLeft: 1.0,
MarginRight: 1.0,
Verbose: false,
}
return opts, nil
}
// NewPictureBook returns a new `PictureBook` instances configured according to the settings in 'opts'.
func NewPictureBook(ctx context.Context, opts *PictureBookOptions) (*PictureBook, error) {
var pdf *fpdf.Fpdf
// opts_w := opts.Width
// opts_h := opts.Height
// opts_b := opts.Bleed
// Start by convert everything to inches - not because it's better but
// just because it's expedient right now (20210218/straup)
if opts.Width == 0.0 && opts.Height == 0.0 {
switch strings.ToLower(opts.Size) {
case "a1":
opts.Width = 584.0 / MM2INCH
opts.Height = 841.0 / MM2INCH
case "a2":
opts.Width = 420 / MM2INCH
opts.Height = 594 / MM2INCH
case "a3":
opts.Width = 297 / MM2INCH
opts.Height = 420 / MM2INCH
case "a4":
opts.Width = 210.0 / MM2INCH
opts.Height = 297.0 / MM2INCH
case "a5":
opts.Width = 148 / MM2INCH
opts.Height = 210 / MM2INCH
case "a6":
opts.Width = 105 / MM2INCH
opts.Height = 148 / MM2INCH
case "a7":
opts.Width = 74 / MM2INCH
opts.Height = 105 / MM2INCH
case "letter":
opts.Width = 8.5
opts.Height = 11.0
case "legal":
opts.Width = 11.0
opts.Height = 17.0
case "tabloid":
opts.Width = 11.0
opts.Height = 17.0
default:
return nil, fmt.Errorf("Unrecognized page size '%s'", opts.Size)
}
} else {
switch opts.Units {
case "inches":
// pass
case "millimeters":
opts.Width = opts.Width / MM2INCH
opts.Height = opts.Height / MM2INCH
case "centimeters":
opts.Width = (opts.Width * 10.0) / MM2INCH
opts.Height = (opts.Height * 10.0) / MM2INCH
default:
return nil, fmt.Errorf("Invalid or unsupported unit '%s'", opts.Units)
}
}
// log.Printf("%0.2f x %0.2f (%s)\n", opts.Width, opts.Height, opts.Size)
sz := fpdf.SizeType{
Wd: opts.Width + (opts.Bleed * 2.0),
Ht: opts.Height + (opts.Bleed * 2.0),
}
init := fpdf.InitType{
OrientationStr: opts.Orientation,
UnitStr: "in",
SizeStr: "",
Size: sz,
FontDirStr: "",
}
pdf = fpdf.NewCustom(&init)
t := PictureBookText{
Font: "Helvetica",
Style: "",
Size: 8.0,
Margin: 0.1,
Colour: []int{128, 128, 128},
}
if opts.OCRAFont {
font, err := ocra.LoadFPDFFont()
if err != nil {
return nil, fmt.Errorf("Failed to load OCRA font, %w", err)
}
pdf.AddFontFromBytes(font.Family, font.Style, font.JSON, font.Z)
pdf.SetFont(font.Family, "", 8.0)
pdf.SetTextColor(t.Colour[0], t.Colour[1], t.Colour[2])
} else {
pdf.SetFont(t.Font, t.Style, t.Size)
}
w, h, _ := pdf.PageSize(1)
page_w := w * opts.DPI
page_h := h * opts.DPI
// https://github.com/aaronland/go-picturebook/issues/22
// margin around each page (inclusive of page bleed)
margin_top := (opts.MarginTop + (opts.Bleed * 2.0)) * opts.DPI
margin_bottom := (opts.MarginBottom + (opts.Bleed * 2.0)) * opts.DPI
margin_left := (opts.MarginLeft + (opts.Bleed * 2.0)) * opts.DPI
margin_right := (opts.MarginRight + (opts.Bleed * 2.0)) * opts.DPI
margins := &PictureBookMargins{
Top: margin_top,
Bottom: margin_bottom,
Left: margin_left,
Right: margin_right,
}
// border around each image
border_top := opts.Border * opts.DPI
border_bottom := opts.Border * opts.DPI
border_left := opts.Border * opts.DPI
border_right := opts.Border * opts.DPI
borders := &PictureBookBorders{
Top: border_top,
Bottom: border_bottom,
Left: border_left,
Right: border_right,
}
// Remember: margins have been calculated inclusive of page bleeds
canvas_w := page_w - (margin_left + margin_right + border_left + border_right)
canvas_h := page_h - (margin_top + margin_bottom + border_top + border_bottom)
pdf.SetAutoPageBreak(false, border_bottom)
canvas := PictureBookCanvas{
Width: canvas_w,
Height: canvas_h,
}
tmpfiles := make([]string, 0)
mu := new(sync.Mutex)
process_func, err := DefaultGatherPicturesProcessFunc(opts)
if err != nil {
return nil, fmt.Errorf("Failed to return DefaultGatherPicturesProcessFunc, %w", err)
}
pb := PictureBook{
PDF: pdf,
Mutex: mu,
Borders: borders,
Margins: margins,
Canvas: canvas,
Text: t,
Options: opts,
ProcessFunc: process_func,
pages: 0,
tmpfiles: tmpfiles,
}
return &pb, nil
}
// AddPictures adds images founds in one or more folders defined 'paths' to the picturebook instance.
func (pb *PictureBook) AddPictures(ctx context.Context, paths []string) error {
pictures, err := pb.GatherPictures(ctx, paths)
if err != nil {
return fmt.Errorf("Failed to gather pictures, %w", err)
}
slog.Debug("Pictures gathered", "count", len(pictures))
if pb.Options.Sort != nil {
sorted, err := pb.Options.Sort.Sort(ctx, pb.Options.Source, pictures)
if err != nil {
return fmt.Errorf("Failed to sort pictures, %w", err)
}
pictures = sorted
}
for _, pic := range pictures {
pb.Mutex.Lock()
pb.pages += 1
pagenum := pb.pages
pb.Mutex.Unlock()
go func(page_num int) {
page_count := max(pb.pages, len(pictures))
ev := progress.NewEvent(page_num, page_count)
pb.Options.Monitor.Signal(ctx, ev)
}(pb.pages)
var err error
if pb.Options.EvenOnly {
if pagenum%2 != 0 {
pb.AddBlankPage(ctx, pagenum)
pb.pages += 1
pagenum = pb.pages
}
if pic.Text != "" {
pb.AddText(ctx, pagenum, pic)
pb.pages += 1
pagenum = pb.pages
pb.AddBlankPage(ctx, pagenum)
pb.pages += 1
pagenum = pb.pages
}
err = pb.AddPicture(ctx, pagenum, pic)
} else if pb.Options.OddOnly {
if pagenum == 1 {
pb.AddBlankPage(ctx, pagenum)
pb.pages += 1
pagenum = pb.pages
}
if pagenum%2 == 0 {
err = pb.AddBlankPage(ctx, pagenum)
pb.pages += 1
pagenum = pb.pages
}
if pic.Text != "" {
pb.AddText(ctx, pagenum, pic)
pb.pages += 1
pagenum = pb.pages
pb.AddBlankPage(ctx, pagenum)
pb.pages += 1
pagenum = pb.pages
}
err = pb.AddPicture(ctx, pagenum, pic)
} else {
if pic.Text != "" {
pb.AddText(ctx, pagenum, pic)
pb.pages += 1
pagenum = pb.pages
}
err = pb.AddPicture(ctx, pagenum, pic)
}
if err != nil {
slog.Debug("Failed to add picture", "path", pic.Path, "error", err)
}
}
err = pb.Options.Monitor.Clear()
if err != nil {
slog.Warn("Failed to clear progress monitor", "error", err)
}
return nil
}
// GatherPictures collects all the images in one or more folders defined by 'paths' and returns a list of `picture.PictureBookPicture` instances.
func (pb *PictureBook) GatherPictures(ctx context.Context, paths []string) ([]*picture.PictureBookPicture, error) {
pictures := make([]*picture.PictureBookPicture, 0)
var err error
i := 0
for path, p_err := range pb.Options.Source.GatherPictures(ctx, paths...) {
if err != nil {
err = p_err
break
}
i += 1
ev := progress.NewEvent(i, -1)
ev.Message = "Gathering items"
pb.Options.Monitor.Signal(ctx, ev)
pic, pic_err := pb.ProcessFunc(ctx, path)
if err != nil {
err = pic_err
break
}
if pic != nil {
pictures = append(pictures, pic)
}
}
err = pb.Options.Monitor.Clear()
if err != nil {
slog.Warn("Failed to clear monitor", "error", err)
}
return pictures, err
}
// AddBlankPage add a blank page the final PDF document at page 'pagenum'.
func (pb *PictureBook) AddBlankPage(ctx context.Context, pagenum int) error {
pb.PDF.AddPage()
return nil
}
// AddText add the value of `pic.Text` on the adjacent page to `pic`.
func (pb *PictureBook) AddText(ctx context.Context, pagenum int, pic *picture.PictureBookPicture) error {
pb.Mutex.Lock()
defer pb.Mutex.Unlock()
pb.PDF.AddPage()
_, line_h := pb.PDF.GetFontSize()
max_w := pb.Canvas.Width
// max_h := pb.Canvas.Height - (pb.Text.Margin + line_h)
/*
w := max_w
h := max_h
*/
margins := pb.Margins
current_x := margins.Left
current_y := margins.Top
// START OF reconcile me with code for rendering captions...
prepped := text.PrepareText(pb.PDF, pb.Options.DPI, max_w, pic.Text)
for _, txt := range prepped {
txt = strings.TrimSpace(txt)
// txt_w := pb.PDF.GetStringWidth(txt)
txt_h := line_h
/*
txt_w = txt_w + pb.Text.Margin
*/
txt_h = txt_h + pb.Text.Margin
// log.Printf("DEBUG %d max: %f03 w: %f03 %s\n", len(txt), max_w, txt_w*pb.Options.DPI, txt)
// please do this in the constructor...
// (20171128/thisisaaronland)
font_sz, _ := pb.PDF.GetFontSize()
pb.PDF.SetFontSize(font_sz + 2)
_, line_h := pb.PDF.GetFontSize()
pb.PDF.SetFontSize(font_sz)
txt_x := current_x / pb.Options.DPI
txt_y := (current_y / pb.Options.DPI)
// slog.Debug("[%d][%s] text at %0.2f x %0.2f (- x %0.2f)\n", pagenum, pic.Path, txt_x, txt_y, txt_h)
pb.PDF.SetXY(txt_x, txt_y)
html := pb.PDF.HTMLBasicNew()
html.Write(line_h, txt)
current_y += ((txt_h * pb.Options.DPI) * .65)
}
// END OF reconcile me with code for rendering captions...
return nil
}
func (pb *PictureBook) AddPicture(ctx context.Context, pagenum int, pic *picture.PictureBookPicture) error {
pb.Mutex.Lock()
defer pb.Mutex.Unlock()
abs_path := pic.Path
caption := pic.Caption
is_tempfile := false
picture_bucket := pb.Options.Source
if pic.Bucket != nil {
picture_bucket = pic.Bucket
}
logger := slog.Default()
logger = logger.With("path", abs_path, "page_number", pagenum)
im_r, err := picture_bucket.NewReader(ctx, abs_path, nil)
if err != nil {
return fmt.Errorf("Failed to create new bucket for %s, %w", abs_path, err)
}
defer im_r.Close()
dec, err := decode.NewDecoder(ctx, abs_path)
if err != nil {
return fmt.Errorf("Failed to create new decoder for %s, %w", abs_path, err)
}
im, format, err := dec.Decode(ctx, im_r)
if err != nil {
return fmt.Errorf("Failed to decode image for %s, %w", abs_path, err)
}
// START OF put me somewhere in aaronland/go-image ... maybe?
// trap fpdf "16-bit depth not supported in PNG file" errors
if format == "png" {
buf := new(bytes.Buffer)
err = png.Encode(buf, im)
if err != nil {
return fmt.Errorf("Failed to encode PNG image for %s, %w", abs_path, err)
}
// this bit is cribbed from https://github.com/jung-kurt/gofpdf/blob/7d57599b9d9c5fb48ea733596cbb812d7f84a8d6/png.go
// (20181231/thisisaaronland)
_ = buf.Next(12)
var bpc int32
err := binary.Read(buf, binary.BigEndian, &bpc)
if err != nil {
return err
}
if bpc > 8 {
tmpfile_path, tmpfile_format, err := tempfile.TempFileWithImage(ctx, pb.Options.Temporary, im)
if err != nil {
return fmt.Errorf("Failed to generate tempfile for %s, %w", abs_path, err)
}
logger.Debug("PNG converted to a JPG", "tmpfile_path", tmpfile_path)
pb.tmpfiles = append(pb.tmpfiles, tmpfile_path)
abs_path = tmpfile_path
format = tmpfile_format
is_tempfile = true
}
}
// END OF put me somewhere in aaronland/go-image ... maybe?
dims := im.Bounds()
w := float64(dims.Max.X)
h := float64(dims.Max.Y)
logger.Debug("Dimensions", slog.Float64("width", w), slog.Float64("height", h))
if pb.Options.FillPage {
image_orientation := "U" // unknown
if dims.Max.Y > dims.Max.X {
image_orientation = "P"
} else if dims.Max.X > dims.Max.Y {
image_orientation = "L"
} else {
// pass
}
_, line_h := pb.PDF.GetFontSize()
max_w := pb.Canvas.Width
max_h := pb.Canvas.Height - (pb.Text.Margin + line_h)
rotate_to_fill := false
if pb.Options.Orientation == "P" && image_orientation == "L" && w > max_w {
rotate_to_fill = true
}
if pb.Options.Orientation == "L" && image_orientation == "P" && h > max_h {
rotate_to_fill = true
}
if rotate_to_fill {
slog.Debug("Rotate image to fill path", "path", abs_path)
new_im, err := rotate.RotateImageWithDegrees(ctx, im, 90.0)
if err != nil {
return err
}
im = new_im
dims = im.Bounds()
w = float64(dims.Max.X)
h = float64(dims.Max.Y)
// now save to disk...
tmpfile_path, tmpfile_format, err := tempfile.TempFileWithImage(ctx, pb.Options.Temporary, im)
if err != nil {
return fmt.Errorf("Failed to create temporary file (rotate to fill) for %s, %w", abs_path, err)
}
if pb.Options.RotateToFillPostProcess != nil {
tmpfile_path, err = pb.Options.RotateToFillPostProcess.Transform(ctx, pb.Options.Temporary, pb.Options.Temporary, tmpfile_path)
if err != nil {
return fmt.Errorf("Failed to apply colour space transformations to temporary file (rotate to fill), %w", err)
}
}
pb.tmpfiles = append(pb.tmpfiles, tmpfile_path)
logger.Debug("Append rotated image", "tmpfile_path", tmpfile_path)
abs_path = tmpfile_path
format = tmpfile_format
is_tempfile = true
}
}
// START OF adjust height relative to caption so that
// it (the caption) doesn't spill in to the margin
caption_h := 0.0
if caption != "" {
lines := strings.Split(caption, "\n")
count := len(lines)
font_sz, _ := pb.PDF.GetFontSize()
// pb.PDF.SetFontSize(font_sz + 2)
line_h := font_sz + 2 // pb.PDF.GetFontSize()
caption_h = (float64(line_h) + pb.Text.Margin) * float64(count)
// slog.Info("CAPTION H", "l", line_h, "h", h, "caption", caption_h, "new", h - caption_h)
}
// END OF adjust height relative to caption so that
opts := fpdf.ImageOptions{
ReadDpi: false,
ImageType: format,
}
var r io.ReadCloser
if is_tempfile {
r, err = pb.Options.Temporary.NewReader(ctx, abs_path, nil)
} else {
r, err = picture_bucket.NewReader(ctx, abs_path, nil)
}
if err != nil {
return fmt.Errorf("Failed to create new reader (info) for %s, %v", abs_path, err)
}
defer r.Close()
info := pb.PDF.RegisterImageOptionsReader(abs_path, opts, r)
if info == nil {
return fmt.Errorf("unable to determine info for %s", abs_path)
}
info.SetDpi(pb.Options.DPI)
logger.Debug("Dimensions", slog.Float64("width", w), slog.Float64("height", h))
if w == 0.0 || h == 0.0 {
return fmt.Errorf("[%d] %s has zero-sized dimension", pagenum, abs_path)
}
// Remember: margins have been calculated inclusive of page bleeds
margins := pb.Margins
x := margins.Left
y := margins.Top
_, line_h := pb.PDF.GetFontSize()
logger.Debug("margins", slog.Float64("left_and_right", (margins.Left+margins.Right)))
logger.Debug("margins", slog.Float64("top_and_bottom", (margins.Top+margins.Bottom)))
logger.Debug("margins", slog.Float64("caption", (pb.Text.Margin+line_h)))
max_w := pb.Canvas.Width
max_h := pb.Canvas.Height
// START OF adjust height relative to caption
// so that it (the caption) doesn't spill in to the margin
if caption != "" {
lines := strings.Split(caption, "\n")
count := len(lines)
font_sz, _ := pb.PDF.GetFontSize()
line_h := font_sz + 2 // pb.PDF.GetFontSize()
caption_h := (float64(line_h) + pb.Text.Margin) * float64(count)
max_h = max_h - caption_h
}
// END OF adjust height relative to caption
logger.Debug("max dimensions", slog.Float64("max_width", max_w), slog.Float64("width", w), slog.Float64("max_height", max_h), slog.Float64("height", h))
for {
if w >= max_w || h >= max_h {
if w > max_w {
ratio := max_w / w
w = max_w
h = h * ratio
}
// slog.Info("CALC", "h", h, "max_h", max_h, "caption_h", caption_h)
if (h + caption_h) > max_h {
ratio := max_h / (h + caption_h)
w = w * ratio
h = max_h
}
}
// TO DO: ENSURE ! h < max_h && ! w < max_w
if w <= max_w && h <= max_h {
break
}
}