-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDocumentationExamplesTest.java
More file actions
418 lines (361 loc) · 17.9 KB
/
DocumentationExamplesTest.java
File metadata and controls
418 lines (361 loc) · 17.9 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
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
package com.demcha.documentation;
import com.demcha.compose.GraphCompose;
import com.demcha.compose.document.api.DocumentPageSize;
import com.demcha.compose.document.api.DocumentSession;
import com.demcha.compose.document.image.DocumentImageFitMode;
import com.demcha.compose.document.templates.api.InvoiceTemplate;
import com.demcha.compose.document.templates.builtins.InvoiceTemplateV1;
import com.demcha.compose.document.templates.data.invoice.InvoiceDocumentSpec;
import com.demcha.compose.document.style.DocumentColor;
import com.demcha.compose.document.style.DocumentInsets;
import com.demcha.compose.document.style.DocumentStroke;
import com.demcha.compose.document.style.DocumentTextStyle;
import com.demcha.compose.document.table.DocumentTableColumn;
import com.demcha.compose.document.table.DocumentTableStyle;
import com.demcha.compose.font.FontName;
import com.demcha.testing.VisualTestOutputs;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.junit.jupiter.api.Test;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import static org.assertj.core.api.Assertions.assertThat;
class DocumentationExamplesTest {
private static final String LEGACY_RENDER_CALL = ".render(";
private static final String LEGACY_PDF_ENTRYPOINT = "GraphCompose" + ".pdf(";
private static final String LEGACY_PDF_COMPOSER = "Pdf" + "Composer";
private static final String LEGACY_TEMPLATE_BUILDER = "Template" + "Builder";
private static final String LEGACY_TEMPLATE_NAMESPACE = "com.demcha." + "templates";
private static final String LEGACY_V2_NAMESPACE = "com.demcha.compose." + "v2";
private static final String FIELD_BASED_CV = "MainPage" + "CV";
private static final String FIELD_BASED_CV_REWRITE = "MainPage" + "CvDTO";
private static final String FIELD_BASED_CV_MODULE = "Module" + "Yml";
@Test
void shouldRenderQuickStartExampleToFile() throws Exception {
Path outputFile = VisualTestOutputs.preparePdf("quick-start", "clean", "documentation");
try (DocumentSession document = GraphCompose.document(outputFile)
.pageSize(DocumentPageSize.A4)
.margin(24, 24, 24, 24)
.create()) {
document.pageFlow(page -> page
.module("Summary", module -> module.paragraph("Hello GraphCompose")));
document.buildPdf();
}
assertPdfFileLooksValid(outputFile);
}
@Test
void shouldRenderInMemoryQuickStartExampleToBytes() throws Exception {
byte[] pdfBytes;
Path outputFile = VisualTestOutputs.preparePdf("quick-start-bytes", "clean", "documentation");
try (DocumentSession document = GraphCompose.document()
.pageSize(DocumentPageSize.A4)
.margin(24, 24, 24, 24)
.create()) {
document.pageFlow(page -> page
.module("Summary", module -> module.paragraph("In-memory PDF")));
pdfBytes = document.toPdfBytes();
}
assertPdfBytesLookValid(pdfBytes, outputFile);
}
@Test
void shouldRenderSectionDslExampleToBytes() throws Exception {
byte[] pdfBytes;
Path outputFile = VisualTestOutputs.preparePdf("section-dsl-bytes", "clean", "documentation");
try (DocumentSession document = GraphCompose.document()
.pageSize(DocumentPageSize.A4)
.margin(24, 24, 24, 24)
.create()) {
document.compose(dsl -> dsl.pageFlow(flow -> flow
.name("TemplateStyleFlow")
.spacing(12)
.addSection("Profile", section -> section
.spacing(6)
.addParagraph("Profile")
.addParagraph(paragraph -> paragraph
.text("Analytical engineer focused on reliable platform design.")
.padding(DocumentInsets.of(4))))));
pdfBytes = document.toPdfBytes();
}
assertPdfBytesLookValid(pdfBytes, outputFile);
}
@Test
void shouldRenderRoundedCardRecipeToFile() throws Exception {
Path outputFile = VisualTestOutputs.preparePdf("rounded-card", "clean", "documentation");
try (DocumentSession document = GraphCompose.document(outputFile)
.pageSize(DocumentPageSize.A4)
.margin(24, 24, 24, 24)
.create()) {
document.pageFlow(page -> page
.spacing(12)
.addSection("InfoCard", card -> card
.fillColor(DocumentColor.rgb(245, 248, 255))
.stroke(DocumentStroke.of(DocumentColor.ROYAL_BLUE, 0.8))
.cornerRadius(10)
.padding(DocumentInsets.of(12))
.margin(DocumentInsets.bottom(10))
.addParagraph(paragraph -> paragraph
.text("Block text inside a filled rounded card.")
.textStyle(DocumentTextStyle.DEFAULT)
.lineSpacing(2))));
document.buildPdf();
}
assertPdfFileLooksValid(outputFile);
}
@Test
void shouldRenderModuleFirstDslExampleToFile() throws Exception {
Path outputFile = VisualTestOutputs.preparePdf("module-first-dsl", "clean", "documentation");
try (DocumentSession document = GraphCompose.document(outputFile)
.pageSize(DocumentPageSize.A4)
.margin(24, 24, 24, 24)
.create()) {
document.pageFlow()
.name("CandidateProfile")
.spacing(12)
.module("Professional Summary", module -> module.paragraph(
"Platform engineer focused on clean document APIs and stable render output."))
.module("Technical Skills", module -> module.bullets(
"Java 21",
"Spring Boot",
"PDFBox",
"Testing and visual regression"))
.module("Projects", module -> module.rows(
"GraphCompose - Canonical document engine migration and template architecture.",
"Template Studio - Internal tooling for invoice, CV, and proposal design."))
.build();
document.buildPdf();
}
assertPdfFileLooksValid(outputFile);
}
@Test
void shouldRenderComposeFirstBuiltInTemplateExampleToFile() throws Exception {
Path outputFile = VisualTestOutputs.preparePdf("compose-first-invoice-template", "clean", "documentation");
InvoiceTemplate template = new InvoiceTemplateV1();
try (DocumentSession document = GraphCompose.document(outputFile)
.pageSize(DocumentPageSize.A4)
.margin(22, 22, 22, 22)
.create()) {
template.compose(document, sampleInvoice());
document.buildPdf();
}
assertPdfFileLooksValid(outputFile);
}
@Test
void runnableExamplesShouldUseCanonicalDocumentTemplates() throws IOException {
Path examplesRoot = Path.of("examples/src/main/java/com/demcha/examples").toAbsolutePath().normalize();
try (var paths = Files.walk(examplesRoot)) {
List<String> violations = new TreeSet<>(paths
.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".java"))
.filter(this::containsLegacyTemplateOrPdfApi)
.map(path -> examplesRoot.relativize(path).toString().replace('\\', '/'))
.collect(Collectors.toList()))
.stream()
.toList();
assertThat(violations).isEmpty();
}
}
@Test
void shouldRenderAvailableFontsPreviewExample() throws Exception {
Path outputFile = VisualTestOutputs.preparePdf("available-fonts-preview", "clean", "documentation");
GraphCompose.renderAvailableFontsPreview(outputFile);
assertThat(GraphCompose.availableFonts())
.contains(FontName.HELVETICA, FontName.LATO, FontName.SPECTRAL);
assertPdfFileLooksValid(outputFile);
}
@Test
void shouldRenderLinePrimitiveExampleToFile() throws Exception {
Path outputFile = VisualTestOutputs.preparePdf("line-primitive", "clean", "documentation");
try (DocumentSession document = GraphCompose.document(outputFile)
.pageSize(DocumentPageSize.A4)
.margin(24, 24, 24, 24)
.create()) {
document.pageFlow()
.name("LinePrimitives")
.spacing(12)
.margin(DocumentInsets.of(8))
.addDivider(divider -> divider
.name("HorizontalRule")
.width(220)
.thickness(3)
.color(DocumentColor.ROYAL_BLUE)
.padding(DocumentInsets.of(6)))
.addShape(shape -> shape
.name("VerticalAccent")
.size(3, 90)
.fillColor(DocumentColor.ORANGE)
.padding(DocumentInsets.of(6)))
.build();
document.buildPdf();
}
assertPdfFileLooksValid(outputFile);
}
@Test
void shouldRenderSpacerLineAndCircleRecipeToFile() throws Exception {
Path outputFile = VisualTestOutputs.preparePdf("spacer-line-circle", "clean", "documentation");
try (DocumentSession document = GraphCompose.document(outputFile)
.pageSize(DocumentPageSize.A4)
.margin(24, 24, 24, 24)
.create()) {
document.pageFlow(page -> page
.name("VisualPrimitives")
.spacing(8)
.addSpacer(spacer -> spacer.name("Gap").height(12))
.addLine(line -> line
.name("Rule")
.horizontal(180)
.thickness(2)
.color(DocumentColor.ROYAL_BLUE))
.addEllipse(ellipse -> ellipse
.name("Badge")
.circle(24)
.fillColor(DocumentColor.ORANGE)
.stroke(DocumentStroke.of(DocumentColor.BLACK, 0.5))));
document.buildPdf();
}
assertPdfFileLooksValid(outputFile);
}
@Test
void shouldRenderImageFitRecipeToFile() throws Exception {
Path outputFile = VisualTestOutputs.preparePdf("image-fit", "clean", "documentation");
byte[] logo = testPng(96, 32);
byte[] avatar = testPng(48, 72);
try (DocumentSession document = GraphCompose.document(outputFile)
.pageSize(DocumentPageSize.A4)
.margin(24, 24, 24, 24)
.create()) {
document.pageFlow(page -> page
.name("ImageFit")
.addImage(image -> image
.name("Logo")
.source(logo)
.fitToBounds(96, 48)
.fitMode(DocumentImageFitMode.CONTAIN))
.addImage(image -> image
.name("Avatar")
.source(avatar)
.fitToBounds(48, 48)
.fitMode(DocumentImageFitMode.COVER)));
document.buildPdf();
}
assertPdfFileLooksValid(outputFile);
}
@Test
void shouldRenderCanonicalTableExampleToFile() throws Exception {
Path outputFile = VisualTestOutputs.preparePdf("table-component", "clean", "documentation");
try (DocumentSession document = GraphCompose.document(outputFile)
.pageSize(DocumentPageSize.A4)
.margin(24, 24, 24, 24)
.create()) {
document.pageFlow()
.name("StatusSection")
.spacing(12)
.addTable(table -> table
.name("StatusTable")
.columns(
DocumentTableColumn.fixed(90),
DocumentTableColumn.auto(),
DocumentTableColumn.auto())
.width(520)
.defaultCellStyle(DocumentTableStyle.builder()
.padding(DocumentInsets.of(6))
.build())
.headerStyle(DocumentTableStyle.builder()
.fillColor(DocumentColor.LIGHT_GRAY)
.padding(DocumentInsets.of(6))
.build())
.header("Role", "Owner", "Status")
.rows(
new String[]{"Engine", "GraphCompose", "Stable"},
new String[]{"Feature", "Table Builder", "Canonical"}))
.build();
document.buildPdf();
}
assertPdfFileLooksValid(outputFile);
}
private void assertPdfBytesLookValid(byte[] pdfBytes, Path outputFile) throws Exception {
assertThat(pdfBytes).isNotEmpty();
assertThat(pdfBytes.length).isGreaterThan(4);
assertThat(new String(pdfBytes, 0, 4, StandardCharsets.US_ASCII)).isEqualTo("%PDF");
Files.write(outputFile, pdfBytes);
assertPdfFileLooksValid(outputFile);
}
private void assertPdfFileLooksValid(Path outputFile) throws Exception {
assertThat(outputFile).exists();
assertThat(outputFile).isRegularFile();
assertThat(outputFile).isNotEmptyFile();
try (PDDocument saved = Loader.loadPDF(outputFile.toFile())) {
assertThat(saved.getNumberOfPages()).isGreaterThan(0);
}
}
private boolean containsLegacyTemplateOrPdfApi(Path path) {
try {
String source = Files.readString(path);
return source.contains(LEGACY_RENDER_CALL)
|| source.contains(LEGACY_PDF_ENTRYPOINT)
|| source.contains(LEGACY_PDF_COMPOSER)
|| source.contains(LEGACY_TEMPLATE_BUILDER)
|| source.contains(LEGACY_TEMPLATE_NAMESPACE)
|| source.contains(LEGACY_V2_NAMESPACE)
|| source.contains(FIELD_BASED_CV)
|| source.contains(FIELD_BASED_CV_REWRITE)
|| source.contains(FIELD_BASED_CV_MODULE);
} catch (IOException e) {
throw new RuntimeException("Failed to inspect " + path, e);
}
}
private byte[] testPng(int width, int height) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
image.setRGB(x, y, x < width / 2 ? Color.RED.getRGB() : Color.BLUE.getRGB());
}
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(image, "png", output);
return output.toByteArray();
}
private InvoiceDocumentSpec sampleInvoice() {
return InvoiceDocumentSpec.builder()
.title("Invoice")
.invoiceNumber("GC-2026-041")
.issueDate("02 Apr 2026")
.dueDate("16 Apr 2026")
.reference("Platform Refresh Sprint")
.status("Pending")
.fromParty(party -> party
.name("GraphCompose Studio")
.addressLines("18 Layout Street", "London, UK", "EC1A 4GC")
.email("billing@graphcompose.dev")
.phone("+44 20 5555 1000")
.taxId("GB-99887766"))
.billToParty(party -> party
.name("Northwind Systems")
.addressLines("Attn: Finance Team", "410 Market Avenue", "Manchester, UK")
.email("ap@northwind.example")
.phone("+44 161 555 2200")
.taxId("NW-2026-01"))
.lineItem("Discovery workshop", "Stakeholder interviews and current-state review", "1", "GBP 1,450", "GBP 1,450")
.lineItem("Template architecture", "Reusable document flows for invoice and proposal output", "2", "GBP 980", "GBP 1,960")
.lineItem("Render QA", "Visual validation and guideline passes", "3", "GBP 320", "GBP 960")
.lineItem("Developer enablement", "Examples module and onboarding notes", "1", "GBP 780", "GBP 780")
.summaryRow("Subtotal", "GBP 5,150")
.summaryRow("VAT (20%)", "GBP 1,030")
.totalRow("Total", "GBP 6,180")
.note("Please include the invoice number on your remittance advice.")
.note("All work was delivered as agreed during the April implementation window.")
.paymentTerm("Payment due within 14 calendar days.")
.paymentTerm("Bank transfer preferred; contact billing@graphcompose.dev for remittance details.")
.paymentTerm("Late payments may delay additional template customization work.")
.footerNote("Thank you for choosing GraphCompose for production document rendering.")
.build();
}
}