-
Notifications
You must be signed in to change notification settings - Fork 12
/
output.go
104 lines (91 loc) · 2.61 KB
/
output.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
package main
// Copyright 2021 Matthew R. Wilson <mwilson@mattwilson.org>
//
// This file is part of virtual1403
// <https://github.com/racingmars/virtual1403>.
//
// virtual1403 is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// virtual1403 is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with virtual1403. If not, see <https://www.gnu.org/licenses/>.
import (
"fmt"
"log"
"os"
"path/filepath"
"time"
"github.com/racingmars/virtual1403/scanner"
"github.com/racingmars/virtual1403/vprinter"
)
type pdfOutputHandler struct {
job vprinter.Job
outputDir string
font []byte
inputName string
profile string
}
func newPDFOutputHandler(outputDir, profile string, fontOverride []byte,
inputName string) (scanner.PrinterHandler, error) {
o := &pdfOutputHandler{
outputDir: outputDir,
font: fontOverride,
inputName: inputName,
profile: profile,
}
var err error
o.job, err = vprinter.NewProfile(profile, fontOverride, 11.4)
if err != nil {
return nil, err
}
return o, nil
}
func (o *pdfOutputHandler) AddLine(line string, linefeed bool) {
o.job.AddLine(line, linefeed)
}
func (o *pdfOutputHandler) PageBreak() {
o.job.NewPage()
}
func (o *pdfOutputHandler) EndOfJob(jobinfo string) {
// No matter what happens, we always want to reset our state to a fresh
// new job.
defer func() {
var err error
o.job, err = vprinter.NewProfile(o.profile, o.font, 11.4)
if err != nil {
log.Printf("ERROR: [%s] couldn't re-initialize virtual 1403: %v",
o.inputName, err)
log.Printf(
"ERROR: [%s] application is probably in a bad state, "+
"please restart.", o.inputName)
}
}()
if jobinfo != "" {
jobinfo = jobinfo + "-"
}
jobfilename := fmt.Sprintf("v1403-%s%s.pdf", jobinfo,
time.Now().UTC().Format("20060102T030405"))
filename := filepath.Join(o.outputDir, jobfilename)
f, err := os.Create(filename)
if err != nil {
log.Printf("ERROR: [%s] couldn't create output file: %v",
o.inputName, err)
return
}
defer f.Close()
n, err := o.job.EndJob(f)
if err != nil {
log.Printf("ERROR: [%s] couldn't write PDF output: %v", o.inputName,
err)
return
}
log.Printf("INFO: [%s] wrote %d page PDF to %s", o.inputName, n,
filename)
}