Skip to main content

PDF Reports: From Button Click to PDF Bytes

This guide follows one click on Export PDF (HR Analytics page) through every method that runs, from the React button to the PDF that opens in a new tab. It then covers the other three ways the backend makes PDFs: tabular reports, the payslip, and the automatic archive. It ends with how JasperReports works inside.

Each step names the method and file, with line numbers as of October 2026. Open the files next to this guide and follow along.

Related: README.md (backend package map and a general request walkthrough), ../security/request-pipeline.md (the security filters in depth).


0. The whole trip in one picture​


1. Frontend: the click​

1.1 HrAnalytics.handleExport()​

frontend/src/pages/hr/HrAnalytics.tsx, line 31

await openReport(() => fetchReport('hr-analytics', {
months: filters.months,
department: filters.department ?? undefined,
}, 'pdf'), true);
  • filters comes from useHrAnalyticsFilters(), the same period and department pickers the page uses.
  • It passes a function (() => fetchReport(...)) rather than a promise. That lets openReport open the new tab first and then start the request (see 1.2).
  • true means "preview": show the PDF in a tab instead of downloading it.

1.2 openReport(load, preview)​

frontend/src/components/reports/openReportFile.ts, line 9

  1. window.open('', '_blank') opens a blank tab right away. Browsers only allow pop-ups during the click itself. If you waited for the server to answer first, the browser would block the tab.
  2. await load() runs fetchReport(...) and waits for the file.
  3. If the result is a PDF: URL.createObjectURL(file.blob) turns the bytes into a temporary blob:http://localhost:5173/… URL, and tab.location.href = url points the blank tab at it. The browser's own PDF viewer shows it.
  4. setTimeout(() => URL.revokeObjectURL(url), 60_000) frees the memory after a minute.
  5. For anything else (Excel, CSV, or when the tab could not be opened), it closes the tab and calls triggerBlobDownload(filename, blob).

1.3 fetchReport(code, params, format) and getFile(...)​

frontend/src/api/payrollReports.ts, lines 43 and 53

export const fetchReport = (code, params, format) =>
getFile(`/api/payroll-reports/${code}`, { ...params, format }, `${code}.${format}`);

const getFile = async (url, params, fallbackName) => {
const response = await apiClient.get<Blob>(url, { params, responseType: 'blob' });
return { blob: response.data, filename: filenameFrom(response.headers['content-disposition'], fallbackName) };
};
  • axios turns params into the query string: /api/payroll-reports/hr-analytics?months=12&format=pdf. Axios leaves out undefined values, so "All departments" sends no department.
  • responseType: 'blob' tells axios to keep the body as raw bytes and not parse it as JSON.
  • filenameFrom(...) (line 18) reads the file name from the server's Content-Disposition header (filename*=UTF-8''hr-analytics-12m.pdf).

1.4 The axios interceptor adds the token​

frontend/src/api/client.ts, line 25

apiClient.interceptors.request.use(config => {
...
config.headers.set('Authorization', `Bearer ${token}`);

Every apiClient request passes through here, so no report code handles login itself. If the server answers 401, the response interceptor (line 77) calls refreshAccessToken() once, retries the request, and logs out if that fails too.

1.5 When it fails: reportErrorMessage(error, fallback)​

payrollReports.ts, line 27

Because we asked for responseType: 'blob', an error body also arrives as a Blob, not JSON. This helper calls await blob.text(), then JSON.parse, and pulls out the backend's message for the toast. That's why it's async.


2. Backend: getting through security​

The request reaches Spring Boot. Before any controller runs, it passes through the filter chain set up in SecurityConfiguration (lines 146–154). For this request, the filters that matter run in this order:

2.1 TenantContextFilter.doFilterInternal(...)​

tenancy/TenantContextFilter.java, line 34

  • Runs first and sets TenantContext.set(TenantContext.GLOBAL).
  • Calls the rest of the chain.
  • Calls TenantContext.clear() in a finally block, so the thread never keeps one company's tenant into the next request.

2.2 JwtAuthenticationFilter.doFilterInternal(...)​

security/jwt/JwtAuthenticationFilter.java, line 26

  1. Reads the Authorization: Bearer … header.
  2. jwtTokenManager.validateToken(token) (line 38) checks the signature and expiry.
  3. userDetailsService.loadUserByUsername(username) (line 40) loads the user and their authorities (permissions such as hr.dashboard.view).
  4. SecurityContextHolder.getContext().setAuthentication(...) (line 46). The user is now "logged in" for the rest of this request.
  5. TenantContextFilter.narrowToPrincipal() (line 51) changes the tenant from GLOBAL to this user's company (user.getTenantId()).
  6. filterChain.doFilter(...) (line 55) moves on to the next filter.

2.3 The class-level @PreAuthorize​

controller/PayrollReportController.java, line 41

Before the method runs, Spring checks the class annotation: the user must hold one of payroll.dashboard.view, payroll.manage, payroll.approve, hr.employees.view or hr.dashboard.view. This first, broad gate keeps out people with no report access at all. The exact per-report check comes later (step 3.2).

2.4 Where the tenant reaches the database​

tenancy/TenantAwareDataSource.java, lines 35 and 44

This doesn't run yet. It runs later, each time the code borrows a database connection:

public Connection getConnection() { return applyScope(super.getConnection()); }
// applyScope runs: SELECT set_config('app.tenant_id', ?, false), set_config('app.bypass_rls', ?, false)

Postgres row-level security policies compare every row's tenant_id with app.tenant_id. So the SQL in step 4 only sees this company's employees, even though the query has no WHERE tenant_id = ….

Security lesson learned here. A SQL view must be created with security_invoker = true, or it reads the tables as the view's owner and skips RLS. CREATE OR REPLACE VIEW silently drops that option. db/migration/afterMigrate.sql sets it again on every view after each Flyway run, and config/RowLevelSecurityCheck logs an error at startup for any view that is missing it.


3. Controller and service: which report, and is this user allowed?​

3.1 PayrollReportController.render(...)​

controller/PayrollReportController.java, line 61

@GetMapping("/{code}")
public ResponseEntity<byte[]> render(@PathVariable String code,
@RequestParam(required = false) String format, ... Integer months, String department,
@AuthenticationPrincipal AuthenticatedUser currentUser, Authentication authentication) {
RenderedReport report = reportService.render(ReportDefinition.fromSlug(code),
new ReportRequest(payrollId, year, month, from, to, months, department), ReportFormat.parse(format),
currentUser.getUsername(), authorities(authentication));
return file(report);
}

Every report shares this one endpoint, and the controller does three small conversions:

CallFileWhat it does
ReportDefinition.fromSlug("hr-analytics")report/ReportDefinition.java line 118Finds the enum entry whose slug matches (HR_ANALYTICS → hr-analytics). Unknown slug → IllegalArgumentException → 400.
new ReportRequest(...)report/ReportRequest.javaA record that holds every filter a report might use. Each report reads only the fields it needs.
ReportFormat.parse("pdf")report/ReportFormat.java line 27"pdf" → ReportFormat.PDF (which also knows its content type and extension).

3.2 PayrollReportService.render(...): the per-report permission check​

report/PayrollReportService.java, line 64

if (!definition.allowedFor(authorities)) {
throw new AccessDeniedException("You do not have permission to run the " + definition.title());
}
return renderUnchecked(definition, request, format, username);

ReportDefinition.allowedFor (line 110) checks the user's authorities against that report's access set. For HR_ANALYTICS that set is just hr.dashboard.view. A payroll clerk passes the controller gate (2.3) but fails here. GlobalControllerAdvice.handleAccessDenied turns the exception into a 403.

3.3 PayrollReportService.renderUnchecked(...): the dispatcher​

Same file, line 73

if (!definition.formats().contains(format)) throw new IllegalArgumentException(...); // HR Analytics is PDF-only → 400 for xlsx
if (definition == PAYSLIPS) return payslipRenderer.renderRun(...); // path C
if (definition == PAYROLL_ANALYTICS) return analyticsReport.render(...); // path A (kit)
if (definition == HR_ANALYTICS) return hrAnalyticsReport.render(request.months(), request.department(), username); // ← we go here
TabularReport builder = builders.get(definition);
return renderer.render(builder.build(definition, request, username), format); // path B

This method is the fork in the road. There are three ways to make a PDF:

PathUsed byHow the layout is defined
A. Report Kit documentHR Analytics, Payroll AnalyticsJava code adds "blocks" (KPIs, charts, tables) to one shared master design
B. Tabular reportthe 11 table reports (register, SSS, BIR, 13th month…)A column list (ReportLayout) that Java turns into a Jasper design
C. JRXML templatePayslipsA hand-written .jrxml file

It's called renderUnchecked because it skips the permission check. Only trusted internal code may call it directly: the archiver (section 8).


4. Path A: building the HR Analytics document​

4.1 HrAnalyticsReport.render(requestedMonths, department, username)​

report/analytics/HrAnalyticsReport.java, line 69

Reading it top to bottom:

  1. Clean the inputs. months is clamped to 1–24 (default 12). A blank department becomes null (all departments).

  2. Fetch data, using the same services the HR Analytics page's charts call, so the PDF and the screen always agree:

    MethodReads from (SQL view)
    hr.getSummary()vw_hr_workforce_snapshot, vw_hr_compliance_snapshot
    hr.getAttendanceMonthly(months)vw_hr_attendance_monthly
    hr.getHeadcountMovement(months) or getHeadcountMovementByDepartment(months, dept)vw_hr_headcount_movement or vw_hr_headcount_by_dept_month
    hr.getWorkforceDistributions()vw_hr_age_distribution, _tenure_, _salary_
    hr.getLeaveAnalytics(), hr.getLeaveMonthly(months)vw_hr_leave_type_summary, vw_hr_leave_balance_summary, vw_hr_leave_monthly
    reporting.getHeadcountByDepartment(), getLeaveByStatus(), getOvertimeMonthlySummary(months)vw_headcount_by_department, vw_leave_by_status, vw_overtime_monthly_summary

    hr is HrAnalyticsServiceImpl and reporting is ReportingServiceImpl. Both use JdbcTemplate.query(sql, rowMapper), which borrows a connection (step 2.4 sets the tenant), runs the SELECT, and maps each row to a DTO record. ascending(...) re-sorts monthly lists oldest-first so charts read left to right.

  3. Start a document: kit.document("HR Analytics", subtitle, filters, username) (see 4.2).

  4. Add blocks, in reading order:

    doc.kpis(...4 workforce tiles...);
    doc.kpis(...4 compliance tiles...);
    workforce(doc, wf); doc.pageBreak(); // § 1
    movement(doc, ...); doc.pageBreak(); // § 2
    attendance(doc, ...); doc.pageBreak(); // § 3
    leave(doc, months); doc.pageBreak(); // § 4
    overtime(doc, ...); // § 5

    Each private section method (workforce at line 112, movement at 143, …) calls doc.section(...), then doc.chart(...) / doc.chartPair(...) / doc.table(...).

  5. Render: return doc.pdf("hr-analytics-12m") (see 5.3). The department is appended to the file name when one is set.

4.2 ReportKit.document(title, subtitle, filters, username)​

report/kit/ReportKit.java, line 65

  • context.header(subtitle, filters, username) (ReportContext.java line 103) reads the company profile (registered name, TIN, address, SSS, PhilHealth and Pag-IBIG employer numbers) and stamps the current time.
  • These go into a params map: CompanyName, CompanyDetails, ReportTitle, Subtitle, Filters, GeneratedLine. In Jasper, parameters are values that stay the same for the whole document, such as the header and footer text.
  • It returns new ReportDocument(this, params), an empty document waiting for blocks.

4.3 ReportDocument: a list of rows, one row per block​

report/kit/ReportDocument.java

This is the key idea of the Report Kit. Each doc.xxx(...) call adds one Map (a row) to blocks. Each row has a kind plus whatever fields that kind needs:

Method (line)Row it adds
kpis(Kpi...) (62)kind=KPI, k1l/k1v/k1h … k4l/k4v/k4h (label, value, hint for up to 4 tiles)
section(no, title, desc) (72)kind=SECTION, secNo, secTitle, secDesc
chart(size, chart) (80)kind=CHART_L or CHART_M, chartTitle, chartNote, chart = an SVG image
chartPair(left, right) (89)kind=CHART_PAIR, chart + chart2 and both titles
table(title, columns, rows) (100)kind=TABLE, tableTitle, tableReport = a compiled sub-report, tableData = its rows
note(text) (108)kind=NOTE, note
pageBreak() (114)kind=BREAK

So the HR Analytics document is data: a list of about 40 maps. No layout happens yet.

4.4 Charts: KitCharts writes SVG text​

report/kit/KitCharts.java

ReportDocument.chart(...) calls chart.drawing().svg(width, height). The drawing is a lambda such as:

(w, h) -> KitCharts.hBars(bars, KitCharts::integer, NAVY, w, h)

hBars (line 38), vBars (84), groupedBars (91), stackedBars (97), line (180) and donut (254) each return an SVG string such as <svg …><rect …/><text …>:

  • niceTicks(max, count, integers) (line 320) picks round axis numbers (0, 5, 10, 15 rather than 0, 4.3, 8.6).
  • wrap(text, maxWidth, size) (line 367) breaks long labels using the real width of Inter glyphs. InterFonts.width(...) measures them with AWT.
  • escape(s) (line 389) makes &, < and " safe inside XML.
  • Colours come only from ReportTheme (NAVY, TEAL, …).

Then ReportDocument.render(svg) (line 140) wraps the bytes as SimpleDataRenderer.getInstance(svgBytes), a Jasper "image" object. Jasper sees it is SVG and draws it with Apache Batik (pulled in by jasperreports itself), so the chart stays a vector in the PDF: crisp at any zoom, and the text can be selected.

4.5 Tables: KitTables.table(columns, width) builds a sub-report​

report/kit/KitTables.java, line 42

  • Builds a cache key from the columns (header, key, type, weight, total).

  • cache.computeIfAbsent(key, k -> compile(columns, width)). The first time a layout is seen, design(columns, width) builds a small Jasper report:

    • a column header band (style TH);
    • a detail band with one text field per column (style TD, zebra rows, numbers right-aligned);
    • a totals summary;
    • a "No records for this period." message.

    JasperCompileManager.compileReport(...) then compiles it. Later calls reuse the compiled report.

  • The rows (List<Map>) are wrapped in new JRMapCollectionDataSource(rows), which becomes the sub-report's own data source.


5. Path A: Jasper turns the blocks into a PDF​

5.1 ReportKit.master(): compile the master design once​

ReportKit.java, line 80

Uses double-checked locking with a volatile field: the first caller compiles, and everyone after that reuses the result.

  1. InterFonts.ensureRegistered() registers Inter with Java's GraphicsEnvironment, so Batik can draw chart text in Inter.
  2. JasperCompileManager.compileReport(design()).

5.2 ReportKit.design(): the master layout, built in Java​

Same file, line 99

JasperDesign jd = new JasperDesign();
KitFrame.page(jd, PAGE_WIDTH, PAGE_HEIGHT); // A4, margins
KitStyles.apply(jd); // named styles: Title, TH, TD, KpiValue …
KitFrame.parameters(jd); // declares CompanyName, ReportTitle, …
field(jd, "kind", String.class); … // declares the row fields (k1l, chart, tableReport …)

jd.setTitle(KitFrame.title(w)); // navy band: printed once, on page 1
jd.setPageHeader(KitFrame.pageHeader(w)); // slim navy bar: pages 2+ only
jd.setPageFooter(KitFrame.footer(w)); // "Confidential · … · Page X of Y"

detail.addBand(kpiBand(w)); // ┐
detail.addBand(sectionBand(w)); // │ ONE band per block kind.
detail.addBand(chartBand(w, "CHART_L", …)); // │ Each band has
detail.addBand(chartBand(w, "CHART_M", …)); // │ printWhenExpression:
detail.addBand(chartPairBand(w)); // │ "KPI".equals($F{kind})
detail.addBand(tableBand(w)); // │ so for each row, only the
detail.addBand(noteBand(w)); // │ matching band prints.
detail.addBand(breakBand()); // ┘

band(kind, height, split) (line 130) is where each band gets setPrintWhenExpression("\"" + kind + "\".equals($F{kind})").

What's inside the bands:

  • kpiBand (139): four tiles, each a box, a teal accent, then label, value and hint text fields bound to $F{k1l}, $F{k1v}, …
  • chartBand / chartPairBand (178/186): title, note, and an image element whose expression is $F{chart}, the SVG renderer from 4.4.
  • tableBand (199): a title, then a sub-report element with $F{tableReport} as the report to run and $F{tableData} as its rows. The band is SplitTypeEnum.STRETCH, so a long table flows onto the next page.
  • breakBand (225): a JRDesignBreak of type PAGE.

KitFrame (report/kit/KitFrame.java):

  • title(w) (line 65): navy band, company name, report title, subtitle, filters, teal rule.
  • pageHeader(w) (84): has printWhenExpression("$V{PAGE_NUMBER} > 1").
  • footer(w) (95): "Page X of Y" uses a trick. The "Y" text field has setEvaluationTime(EvaluationTimeEnum.REPORT), so Jasper leaves it blank and fills it in after the last page is laid out, when the total page count is known.

5.3 ReportDocument.pdf(fileStem): fill, then export​

ReportDocument.java, line 118

JasperPrint print = JasperFillManager.fillReport(kit.master(), new HashMap<>(params),
new JRMapCollectionDataSource(blocks));
print.setName(String.valueOf(params.get("ReportTitle")));
return new RenderedReport(JasperExportManager.exportReportToPdf(print), fileStem + ".pdf", ReportFormat.PDF);
  • Fill. Jasper walks the blocks list one row at a time. For each row it evaluates every detail band's printWhenExpression; only the band whose kind matches prints. It places the band at the current Y position. If the band doesn't fit, it ends the page (footer), starts a new one (page header), and continues. A TABLE row triggers a nested fill of the sub-report with its own rows.
  • new HashMap<>(params): Jasper adds its own entries to the parameter map during fill, so it must be a mutable copy (Map.of throws).
  • The result, JasperPrint, is a list of pages. Each page holds positioned elements ("text 'Active headcount' at x=36,y=120 in Inter 6.5pt"). It doesn't depend on any output format yet.
  • Export. JasperExportManager.exportReportToPdf(print) hands that page list to the PDF exporter (OpenPDF), which writes PDF drawing commands and embeds the fonts. The result is a byte[].

5.4 Back out through the controller: file(report)​

PayrollReportController.java, line 80

ContentDisposition disposition = (report.format() == ReportFormat.PDF ? ContentDisposition.inline() : ContentDisposition.attachment())
.filename(report.filename(), StandardCharsets.UTF_8).build();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, disposition.toString()) // inline; filename*=UTF-8''hr-analytics-12m.pdf
.header(HttpHeaders.CACHE_CONTROL, "no-store") // payroll data: never cache
.contentType(MediaType.parseMediaType(report.contentType())) // application/pdf
.body(report.content()); // the byte[]

RenderedReport (report/RenderedReport.java) is a simple record: (byte[] content, String filename, ReportFormat format). Every path (A, B, C) ends by returning one, so the controller never cares how the PDF was made.

The bytes go back to axios (1.3), which wraps them in a Blob. openReport (1.2) points the waiting tab at it.


6. Path B: tabular reports (register, SSS, BIR, 13th month …)​

Example: Payroll Register for run #139: GET /api/payroll-reports/payroll-register?payrollId=139&format=pdf. Steps 1–3 are the same as above. At 3.3 the dispatcher reaches the last line:

return renderer.render(builder.build(definition, request, username), format);

6.1 TabularReport.build(...): gather rows​

For example, report/builders/PayrollRegisterReport.java build (line 76):

  • ReportContext.sortedByName(context.runPayslips(id)) loads the run's payslips and sorts them A–Z by surname (Last, First M.).
  • Turns each payslip into a Map row keyed by column key.
  • Returns new ReportData(LAYOUT, context.header(...), rows, summary, stem). LAYOUT (line 36) is a ReportLayout: the report code, title and list of ReportColumn(header, key, type, weight, total).

Every builder implements the one-method interface TabularReport. Spring injects all of them into PayrollReportService as a List<TabularReport>.

6.2 TabularReportRenderer.render(data, format)​

report/TabularReportRenderer.java, line 59

if (format == CSV) return new RenderedReport(CsvWriter.write(data), filename, format); // no Jasper at all
JasperReport report = compiled.computeIfAbsent(data.layout().code(), code -> compile(data.layout()));
if (format == XLSX) params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE); // one long sheet
JasperPrint print = JasperFillManager.fillReport(report, params, new JRMapCollectionDataSource(rows));
return new RenderedReport(JasperExporters.export(print, format), filename, format);
  • compile(layout) → design(layout) builds a Jasper design from the column list:

    • columnWidths(...) (line 247) splits the page width by each column's weight;
    • columnHeaderBand(...) (289);
    • a detail band with one text field per column;
    • totalsBand(...) (302) with sumVariable(...) (329) for columns marked total;
    • group subtotals, footnotes and a signature block.

    It uses the same KitFrame header/footer and KitStyles as path A, so all reports look alike.

  • It's cached per report code, so it compiles only once.

  • JasperExporters.export(print, format) (line 20) uses JRPdfExporter for PDF (and sets the PDF's title metadata) or JRXlsxExporter for Excel. One filled JasperPrint can be exported to either format.


7. Path C: the payslip (a real .jrxml file)​

report/PayslipReportRenderer.java

  • renderRun(run, username) (line 51): sortedByName(runPayslips(...)), then render(...).
  • render(payslips, stem, username) (line 60):
    • loads all deduction lines in one query (findAllByPayslip_PayslipIdInOrder…) to avoid N+1;
    • builds one row Map per payslip with row(...) (line 82);
    • puts params.put("KitStyles", KitStyles.template()), then fills and exports.
  • template() (line 173) reads resources/reports/payslip.jrxml from the classpath and calls JasperCompileManager.compileReport(inputStream) once (cached).

The .jrxml contains <template>$P{KitStyles}</template>. The kit's styles are passed in as a parameter, so the hand-written payslip uses the same fonts and colours as everything else. This is also how you would build a new report visually in Jaspersoft Studio Community and still keep the house style.


8. Path D: the automatic archive (no button at all)​

When a payroll run is marked Processed, the backend freezes a copy of its reports.

  1. PayrollServiceImpl.updateStatus(...) (service/impl/PayrollServiceImpl.java line 403) publishes eventPublisher.publishEvent(new PayrollProcessedEvent(id, TenantContext.get(), username)) (line 445).
  2. PayrollReportArchiver.onProcessed(event) (report/archive/PayrollReportArchiver.java line 42) is a @TransactionalEventListener(phase = AFTER_COMMIT). It runs only after the status change is committed. If the status update rolls back, nothing is archived.
    • executor.execute(() -> archive(event)): generating about 9 PDFs takes a few seconds, so it runs on a private background thread. The user's click returns immediately.
  3. archive(event) (line 55): TenantContext.runAs(event.tenantId(), …). The background thread has no logged-in user and no tenant, so the tenant is carried in the event and set again here. Without this, RLS would show zero rows.
  4. ReportArchiveService.generateMissing(payrollId, username) (report/archive/ReportArchiveService.java line 52) loops over PACK (line 32):
    • skips items already store.isReady(...);
    • calls reportService.renderUnchecked(...), the same dispatcher as step 3.3, so archived files are identical to on-demand ones;
    • store.saveReady(...) or store.saveFailed(...). One bad report doesn't stop the rest.
  5. ArchiveStore.saveReady(...) (report/archive/ArchiveStore.java line 35):
    • runs as @Transactional(propagation = REQUIRES_NEW), so each file commits on its own;
    • stores the bytes plus a SHA-256 fingerprint (sha256(...), line 78);
    • READY rows are never overwritten.

9. How JasperReports works inside (the mental model)​

StageThink of it asIn this codeCost
DesignThe blueprint: page size, bands, text fields with expressions like $F{k1v}, stylesReportKit.design(), KitTables.design(), TabularReportRenderer.design(), payslip.jrxmlcheap
CompileTurning the blueprint into a machine. Every $F{…} / $P{…} / $V{…} expression becomes generated Java, compiled by ecj (jasperreports-jdt, needed because the Docker image is a JRE with no javac)JasperCompileManager.compileReport(...), always cached in a field or mapslow (hundreds of ms), so do it once
FillRunning the machine on data. Loop over rows, evaluate expressions, place bands, break pages, run sub-reports, compute totals and "Page X of Y"JasperFillManager.fillReport(report, params, dataSource)per request
ExportPainting the laid-out pages into a file formatJasperExportManager.exportReportToPdf, JasperExporters.exportper request

The three expression prefixes:

  • $P{Name}: a parameter, one value for the whole report (title, company name).
  • $F{name}: a field, a value from the current row (kind, k1v, chart).
  • $V{NAME}: a variable Jasper computes, such as PAGE_NUMBER, REPORT_COUNT (used for zebra rows: $V{REPORT_COUNT} % 2 == 0), or sums for totals.

Fonts. PDFs can only use fonts they embed. jasperreports_extension.properties points Jasper at fonts/jasper-fonts.xml, which maps the font names (Inter, Noto Sans) to the bundled .ttf files. Noto Sans is there because it has the ₱ sign. Separately, InterFonts registers Inter with Java AWT so Batik can draw SVG chart text and so KitCharts.wrap can measure label widths.

A JR7 gotcha. If a text field's box is shorter than about 1.36 × its font size, Jasper silently draws nothing. If text disappears, make the box taller.


10. Where to change things​

You want to…Edit
Change a colour, font or size in every reportreport/kit/ReportTheme.java, the only place colours and fonts are allowed. ThemeIsTheOnlySourceTest fails if a hex code or font name appears anywhere else under report/ or resources/reports/.
Change a named style (table header, KPI value…)report/kit/KitStyles.java
Change the header band or footerreport/kit/KitFrame.java
Add a new block kind (e.g. a gauge)Add a band in ReportKit.design() with band("GAUGE", …), declare its fields in TEXT_FIELDS/field(...), and add a ReportDocument.gauge(...) method that adds a kind=GAUGE row
Add a new chart typeA new public static String xxx(...) in KitCharts returning SVG
Lay out a form (numbered fields with values, like a BIR return)Use the form blocks: ReportDocument.field(item, label, hint, value, amount) for a line the reader types in, computed(...) for a shaded line the filing system works out, fieldGroup(label) for a sub-heading, and alert(text) for an amber call-out. report/forms/Bir1601cWorksheet.java is the example.
Add a new analytics-style report1) Add an enum entry in ReportDefinition (category, scope, access, formats). 2) Write a @Component class like HrAnalyticsReport that fetches data and calls kit.document(...) → blocks → .pdf(...). 3) Add one if line in PayrollReportService.renderUnchecked. The frontend catalogue picks it up from GET /api/payroll-reports/catalog.
Add a new table reportAdd an enum entry plus a @Component implementing TabularReport with a ReportLayout. It's auto-registered, with no change to the service.

Tests that pin this behaviour​

Under backend/src/test/java/com/motorph/payroll/report/:

  • ReportKitTest: every block kind renders (including the FIELD, FIELD_GROUP and ALERT form blocks), the frame is on every page, long tables break.
  • Bir1601cWorksheetTest: a full form-style document (BIR 1601-C) end to end.
  • KitChartsTest: ticks, escaping, empty data.
  • HrAnalyticsReportTest: KPIs and sections in order, filters passed through.
  • TabularReportRendererTest and EmployeeOrderTest: A–Z order.
  • ThemeIsTheOnlySourceTest.

A handy trick when studying: these tests render real PDFs. Set a breakpoint in ReportDocument.pdf or ReportKit.design, run HrAnalyticsReportTest in the debugger, and step through everything above line by line.