-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
276 lines (240 loc) · 8 KB
/
main.go
File metadata and controls
276 lines (240 loc) · 8 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
package main
import (
"bytes"
"encoding/json"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"time"
"strings"
docs "github.com/GEWIS/pdf-compiler/docs"
"github.com/go-chi/chi/v5"
"github.com/pdfcpu/pdfcpu/pkg/api"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
httpSwagger "github.com/swaggo/http-swagger/v2"
)
var (
basePath = String("BASE_PATH", "/api/v1")
port = String("PORT", ":8080")
templateDir = String("TEMPLATE_DIR", "templates")
logLevel = String("LOG_LEVEL", "info")
chromeBin = String("PATH_TO_CHROME_BIN", "google-chrome-stable")
)
// @title PDF Compiler
// @version 1.0
// @description A simple API to compile LaTeX templates and HTML documents to PDF
// @servers.url http://localhost:8080/api/v1
func main() {
r := chi.NewRouter()
docs.SwaggerInfo.BasePath = basePath
l, err := zerolog.ParseLevel(logLevel)
if err != nil {
log.Fatal().Err(err).Msg("could not parse level")
}
zerolog.SetGlobalLevel(l)
r.Use(requestLogger)
r.Route(basePath, func(r chi.Router) {
r.Post("/compile", Compile)
r.Post("/compile-html", CompileHTML)
r.Get("/health", HealthCheck)
})
r.Get("/swagger/*", httpSwagger.WrapHandler)
r.Get("/swagger/doc.json", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write([]byte(docs.SwaggerInfo.ReadDoc()))
})
log.Info().Msgf("Starting pdf-compiler server %s on port %s", basePath, port)
log.Fatal().Err(http.ListenAndServe(port, r)).Msg("Server stopped")
}
// HealthCheck returns 200 OK
//
// @Summary Health check
// @Description Returns 200 OK
// @Tags Health
// @Success 200
// @Router /health [get]
func HealthCheck(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
type CompileRequest struct {
Tex string `json:"tex" example:"\\documentclass{article}\n\\begin{document}\nHello, world!\n\\end{document}"`
}
type ErrorResponse struct {
Error string `json:"error" example:"Invalid request, must provide LaTeX template"`
}
// Compile compiles a LaTeX template to PDF
//
// @Summary Compile LaTeX template
// @Description Compiles a LaTeX template and returns a PDF
// @Tags Compile
// @Accept json
// @Produce application/pdf
// @Param request body CompileRequest true "LaTeX template"
// @Success 200 {string} file "PDF file"
// @Failure 400 {object} main.ErrorResponse "Invalid request"
// @Failure 500 {object} main.ErrorResponse "Compilation error"
// @Router /compile [post]
func Compile(w http.ResponseWriter, r *http.Request) {
var req CompileRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Tex == "" {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "Invalid request, must provide LaTeX template"})
return
}
defer r.Body.Close()
// Write LaTeX to a temp file
dir, err := os.MkdirTemp("", "latex")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "Failed to create temp directory"})
return
}
defer os.RemoveAll(dir) // Clean up temp files
texPath := filepath.Join(dir, "input.tex")
if err := os.WriteFile(texPath, []byte(req.Tex), 0644); err != nil {
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "Failed to write template file"})
return
}
// Compile LaTeX to PDF using pdflatex (ensure installed!)
cmd := exec.Command("pdflatex", "-output-directory", dir, "-interaction=nonstopmode", texPath)
env := os.Environ()
env = append(env, "TEXINPUTS="+templateDir+string(os.PathListSeparator))
cmd.Env = env
var compileLog bytes.Buffer
cmd.Stdout = &compileLog
cmd.Stderr = &compileLog
if err := cmd.Run(); err != nil {
log.Error().Err(err).Str("log", compileLog.String()).Msg("pdflatex error")
errorMsg := extractLatexError(compileLog.String())
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(ErrorResponse{Error: errorMsg})
return
}
pdfPath := filepath.Join(dir, "input.pdf")
pdfFile, err := os.Open(pdfPath)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "PDF not generated"})
return
}
defer pdfFile.Close()
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition", "attachment; filename=output.pdf")
if _, err := io.Copy(w, pdfFile); err != nil {
log.Error().Err(err).Msg("failed to write PDF to response")
}
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
func requestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
log.Info().
Str("method", r.Method).
Str("path", r.URL.Path).
Msg("incoming request")
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
log.Info().
Str("method", r.Method).
Str("path", r.URL.Path).
Int("status", rec.status).
Dur("duration", time.Since(start)).
Msg("request")
})
}
func extractLatexError(log string) string {
for _, line := range strings.Split(log, "\n") {
if strings.HasPrefix(line, "! ") {
return line
}
}
// fallback...
return "Unknown LaTeX error"
}
type CompileHTMLRequest struct {
HTML string `json:"html" example:"<html><body><h1>Hello, world!</h1></body></html>"`
}
// CompileHTML compiles an HTML document to PDF using headless Chrome
//
// @Summary Compile HTML to PDF
// @Description Compiles an HTML document and returns a PDF using headless Chrome
// @Tags Compile
// @Accept json
// @Produce application/pdf
// @Param request body CompileHTMLRequest true "HTML document"
// @Success 200 {string} file "PDF file"
// @Failure 400 {object} main.ErrorResponse "Invalid request"
// @Failure 500 {object} main.ErrorResponse "Compilation error"
// @Router /compile-html [post]
func CompileHTML(w http.ResponseWriter, r *http.Request) {
var req CompileHTMLRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.HTML == "" {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "Invalid request, must provide HTML document"})
return
}
defer r.Body.Close()
// Write HTML to a temp file
dir, err := os.MkdirTemp("", "html")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "Failed to create temp directory"})
return
}
defer os.RemoveAll(dir)
htmlPath := filepath.Join(dir, "input.html")
if err := os.WriteFile(htmlPath, []byte(req.HTML), 0600); err != nil {
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "Failed to write HTML file"})
return
}
pdfPath := filepath.Join(dir, "output.pdf")
cmd := exec.Command(chromeBin,
"--headless",
"--disable-gpu",
"--no-sandbox",
"--disable-dev-shm-usage",
"--run-all-compositor-stages-before-draw",
"--no-pdf-header-footer",
"--print-to-pdf-no-header",
"--print-to-pdf="+pdfPath,
"file://"+htmlPath,
)
var compileLog bytes.Buffer
cmd.Stdout = &compileLog
cmd.Stderr = &compileLog
if err := cmd.Run(); err != nil {
log.Error().Err(err).Str("log", compileLog.String()).Msg("chrome error")
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "Failed to generate PDF: " + compileLog.String()})
return
}
// Strip the /Title metadata from the PDF
if err := api.RemovePropertiesFile(pdfPath, "", []string{"Title"}, nil); err != nil {
log.Error().Err(err).Msg("failed to remove PDF properties")
}
pdfFile, err := os.Open(pdfPath)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "PDF not generated"})
return
}
defer pdfFile.Close()
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition", "attachment; filename=output.pdf")
if _, err := io.Copy(w, pdfFile); err != nil {
log.Error().Err(err).Msg("failed to write PDF to response")
}
}