Installation
Maven
<dependency>
<groupId>com.seaglassfoundry</groupId>
<artifactId>swingtopdf</artifactId>
<version>1.0.1</version>
</dependency>
Gradle (Kotlin DSL)
implementation("com.seaglassfoundry:swingtopdf:1.0.1")
Gradle (Groovy DSL)
implementation 'com.seaglassfoundry:swingtopdf:1.0.1'
JVM Flags
SwingToPDF uses --add-opens to access Swing internals for accurate font resolution and rendering. Add these flags to your application's JVM arguments:
--add-opens java.desktop/javax.swing=com.seaglassfoundry.swingtopdf
--add-opens java.desktop/java.awt=com.seaglassfoundry.swingtopdf
--add-opens java.desktop/sun.font=com.seaglassfoundry.swingtopdf
--add-opens java.desktop/javax.swing=ALL-UNNAMED
--add-opens java.desktop/java.awt=ALL-UNNAMED
--add-opens java.desktop/sun.font=ALL-UNNAMED
Font.createFont().
Basic Usage
Export any JComponent to a PDF file with just a few lines:
import com.seaglassfoundry.swingtopdf.SwingPdfExporter;
import com.seaglassfoundry.swingtopdf.api.PageSize;
import com.seaglassfoundry.swingtopdf.api.Orientation;
// Any JComponent — a JPanel, JTable, JTabbedPane, etc.
JPanel panel = buildYourUI();
SwingPdfExporter.from(panel)
.pageSize(PageSize.A4)
.orientation(Orientation.PORTRAIT)
.margins(36, 36, 36, 36) // 0.5 inch on all sides
.title("My First PDF")
.export(Path.of("output.pdf"));
Exporting to a Stream
Write the PDF to a network response, byte array, or any other OutputStream:
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
SwingPdfExporter.from(panel)
.pageSize(PageSize.LETTER)
.export(baos);
byte[] pdfBytes = baos.toByteArray();
// send to HTTP response, save to database, etc.
}
Fillable Form Fields (AcroForm)
Produce a PDF with interactive form fields — text inputs, checkboxes, dropdowns — with a single method call:
SwingPdfExporter.from(myForm)
.pageSize(PageSize.LETTER)
.enableAcroForm()
.export(Path.of("form.pdf"));
Supported components: JTextField, JCheckBox, JRadioButton, JComboBox, JTextArea, and JPasswordField.
Export Modes
SwingToPDF offers two export modes:
- DATA_REPORT (default) — exports all data: every table row, every tab, the full scroll content. Automatically paginates.
- UI_SNAPSHOT — captures only what is currently visible on screen.
import com.seaglassfoundry.swingtopdf.api.ExportMode;
SwingPdfExporter.from(panel)
.exportMode(ExportMode.UI_SNAPSHOT)
.export(Path.of("screenshot.pdf"));
Headless / CI Environments
SwingToPDF works in headless environments. Make sure your component has been sized before exporting:
// Option 1: explicit size
panel.setSize(800, 600);
// Option 2: pack a frame (triggers layout)
JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.pack();
Requirements
- Java 17 or later
- Apache PDFBox 3.x (included as transitive dependency)
Javadoc & Full Reference
Javadoc is published alongside the artifact on Maven Central. Comprehensive documentation covering pagination, headers/footers, font embedding, and the full component reference is coming soon.