-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path141.java
More file actions
193 lines (169 loc) · 7.24 KB
/
Copy path141.java
File metadata and controls
193 lines (169 loc) · 7.24 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
/*
* Copyright (c) 2018 Pavel Uvarov <pauknone@yahoo.com>
*
* This file is part of Ukase.
*
* Ukase is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.ukase.toolkit;
import com.github.jknack.handlebars.Handlebars;
import com.github.ukase.config.UkaseSettings;
import com.github.ukase.toolkit.helpers.AbstractHelper;
import com.github.ukase.toolkit.pdf.PdfSaucerRenderer;
import com.github.ukase.toolkit.render.RenderException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.util.XRRuntimeException;
import org.xml.sax.SAXParseException;
import javax.xml.transform.SourceLocator;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;
import java.util.regex.Pattern;
@Service
@Log4j
public class ResourceProvider {
private static final String COMMON_DOCTYPE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" " +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
private static final String DOCTYPE_HTML5 = "<!DOCTYPE html>";
private static final Pattern HTML_TAG = Pattern.compile("<html([^>]*)lang=\"([^\"]+)\"([^>]*)>");
private static final String HTML_TAG_REPLACEMENT =
"<html$1lang=\"$2\" xml:lang=\"$2\" xmlns=\"http://www.w3.org/1999/xhtml\"$3>";
private static final String ENTITY_EQUAL = "=";
private static final String ENTITY_EQUAL_ = "=";
private static final String ENTITY_QUOTE = "'";
private static final String SYMBOL_QUOTE = "'";
private static final String SYMBOL_EQUAL = "=";
private final ApplicationContext context;
private final CompoundSource source;
private final CompoundTemplateLoader templateLoader;
private final String defaultFont;
private final String resourcesPath;
@Autowired
public ResourceProvider(ApplicationContext context,
CompoundSource source,
CompoundTemplateLoader templateLoader,
UkaseSettings settings) {
this.context = context;
this.source = source;
this.templateLoader = templateLoader;
this.resourcesPath = resolvePath(settings.getResources());
this.defaultFont = this.source.getDefaultFontUrl();
}
@Bean
public Handlebars getEngine() {
Handlebars engine = new Handlebars(templateLoader);
source.getHelpers().forEach(engine::registerHelper);
for (AbstractHelper<?> helper: context.getBeansOfType(AbstractHelper.class).values()) {
engine.registerHelper(helper.getName(), helper);
}
return engine;
}
public PdfSaucerRenderer getRenderer(String htmlDocument) {
PdfSaucerRenderer renderer = new PdfSaucerRenderer(source);
try {
initFonts(renderer.getFontResolver());
htmlDocument = filterHtml5Document(htmlDocument);
renderer.setDocumentFromString(htmlDocument, resourcesPath);
renderer.layout();
} catch (IOException | DocumentException e) {
log.error("Some problem in font loading");
} catch (XRRuntimeException e) {
logErrorInLine(htmlDocument, e);
throw new RenderException("Error in xhtml file processing", e, "pdf");
}
return renderer;
}
public String getDefaultFont() {
return defaultFont;
}
private void initFonts(ITextFontResolver fontResolver) throws IOException, DocumentException {
for (String font: source.getFontsUrls()) {
fontResolver.addFont(font, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}
}
private String filterHtml5Document(String html5PossibleDocument) {
String document = html5PossibleDocument;
if (html5PossibleDocument.contains(DOCTYPE_HTML5)) {
document = document.replace(DOCTYPE_HTML5, COMMON_DOCTYPE);
document = HTML_TAG.matcher(document).replaceAll(HTML_TAG_REPLACEMENT);
}
return filterKnownEntities(document);
}
private String filterKnownEntities(String html) {
return html.replace(ENTITY_QUOTE, SYMBOL_QUOTE)
.replace(ENTITY_EQUAL_, SYMBOL_EQUAL)
.replace(ENTITY_EQUAL, SYMBOL_EQUAL);
}
private String resolvePath(File resources) {
if (resources != null && resources.isDirectory()) {
return resources.toURI().toString();
}
return null;
}
private void logErrorInLine(String htmlDocument, XRRuntimeException e) {
SAXParseException parseCause = getCause(e, SAXParseException.class);
if (parseCause != null) {
logErrorInLine(htmlDocument, parseCause.getLineNumber(), parseCause.getColumnNumber(), parseCause);
return;
}
TransformerException transformCause = getCause(e, TransformerException.class);
if (transformCause != null) {
SourceLocator locator = transformCause.getLocator();
logErrorInLine(htmlDocument, locator.getLineNumber(), locator.getColumnNumber(), transformCause);
}
}
private <T extends Exception> T getCause(Throwable e, Class<T> tClass) {
if (e == null) {
return null;
}
Throwable cause = e.getCause();
if (tClass.isInstance(cause)) {
return tClass.cast(cause);
}
return getCause(cause, tClass);
}
private void logErrorInLine(String htmlDocument, int lineNumber, int columnNumber, Exception e) {
if (lineNumber < 0) {
log.error("Thrown xml parse exception, but no line were defined", e);
return;
}
StringBuilder sb = new StringBuilder("Generated html parsing error in line ")
.append(lineNumber)
.append(" at character ")
.append(columnNumber)
.append(":\n")
.append(getLine(htmlDocument, lineNumber))
.append("\n");
for (int i = 0 ; i < columnNumber - 1 ; i++) {
sb.append(" ");
}
sb.append("^")
.append("\n");
log.error(sb.toString(), e);
}
private String getLine(String htmlDocument, int lineNumber) {
String[] lines = htmlDocument.split("\r\n|\r|\n");
if (lineNumber <= lines.length) {
return lines[lineNumber - 1];
}
return null;
}
}