PDF Merge — Java source
Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.
This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.
// pdf-merge — merge many PDFs into one with Apache PDFBox
// (Loader.loadPDF + PDFMergerUtility, pdfbox.apache.org).
//
// Language: Java (17+), Apache PDFBox for the PDF I/O (display-only
// dependency — the pure helpers below compile and run standalone).
// CosmoDev polyglot showcase port of the `pdf-merge` tool.
// Ported from src/lib/pdf-merge.ts — display source, part of CosmoDev's
// polyglot tool pages.
//
// Same contract: empty input rejected, encrypted vs invalid classified from
// the raw load-error message, page count returned for UI display.
import java.io.ByteArrayOutputStream;
import java.util.List;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
public final class PdfMerge {
/** Load failure kind: ENCRYPTED (password-protected) or INVALID (unparseable). */
public enum ErrorKind { ENCRYPTED, INVALID }
/** The Java twin of the TS PdfToolError class. */
public static final class PdfToolError extends RuntimeException {
public final ErrorKind kind;
public PdfToolError(ErrorKind kind, String message) {
super(message);
this.kind = kind;
}
}
/** Pure classifier — encrypted vs invalid, from the raw error message.
* Same /encrypt|password/i heuristic the TS lib applies. */
public static ErrorKind classifyLoadError(String msg) {
if (msg != null) {
String lower = msg.toLowerCase();
if (lower.contains("encrypt") || lower.contains("password")) {
return ErrorKind.ENCRYPTED;
}
}
return ErrorKind.INVALID;
}
/** Map a thrown load/parse error to a user-facing PdfToolError. */
public static PdfToolError mapError(Exception e) {
ErrorKind kind = classifyLoadError(e.getMessage());
return new PdfToolError(kind, kind == ErrorKind.ENCRYPTED
? "This PDF is password-protected. Unlock it first."
: "Not a readable PDF file.");
}
/** The merge outcome: output bytes plus the page count for UI display. */
public record MergeResult(byte[] bytes, int pageCount) {}
/** Copy every page of every input, in order, into one fresh PDDocument. */
public static MergeResult mergePdfs(List<byte[]> docs) throws Exception {
if (docs.isEmpty()) {
throw new PdfToolError(ErrorKind.INVALID, "Nothing to merge.");
}
try (PDDocument out = new PDDocument()) {
PDFMergerUtility merge = new PDFMergerUtility();
try {
for (byte[] bytes : docs) {
try (PDDocument src = Loader.loadPDF(bytes)) {
// the TS ignoreEncryption: false path, explicit in PDFBox
if (src.isAllContentEncrypted()) {
throw new PdfToolError(
ErrorKind.ENCRYPTED, "This PDF is password-protected. Unlock it first.");
}
merge.appendDocument(out, src);
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
out.save(baos);
return new MergeResult(baos.toByteArray(), out.getNumberOfPages());
} catch (Exception e) {
if (e instanceof PdfToolError t) {
throw t; // classification failures surface as themselves
}
// parse failures -> the shared error mapping (PDFBox's "encrypted"
// InvalidPasswordException carries the keyword in its message)
throw mapError(e);
}
}
}
/** Page count for UI display — the tool's only other PDFBox need. */
public static int countPages(byte[] bytes) throws Exception {
try (PDDocument doc = Loader.loadPDF(bytes)) {
if (doc.isAllContentEncrypted()) {
throw new PdfToolError(
ErrorKind.ENCRYPTED, "This PDF is password-protected. Unlock it first.");
}
return doc.getNumberOfPages();
} catch (PdfToolError e) {
throw e;
} catch (Exception e) {
throw mapError(e);
}
}
public static void main(String[] args) {
// classifyLoadError — the src/lib/pdf-merge.test.ts vectors.
String[][] classifyCases = {
{"Input document to PDFDocument.load is encrypted", "encrypted"},
{"wrong password for this document", "password"},
{"Failed to parse PDF", "parse"},
{null, "null"},
};
for (String[] c : classifyCases) {
System.out.printf("%s-msg -> %s%n", c[1],
classifyLoadError(c[0]) == ErrorKind.ENCRYPTED ? "encrypted" : "invalid");
}
// empty input throws invalid
try {
mergePdfs(List.of());
} catch (Exception e) {
PdfToolError t = (PdfToolError) e;
System.out.printf("empty-input -> %s: %s%n",
t.kind == ErrorKind.ENCRYPTED ? "encrypted" : "invalid", t.getMessage());
}
// mapError — encrypted classification propagates, message per kind
PdfToolError enc = mapError(new Exception("Input document to PDFDocument.load is encrypted"));
System.out.printf("map-encrypted -> %s: %s%n",
enc.kind == ErrorKind.ENCRYPTED ? "encrypted" : "invalid", enc.getMessage());
PdfToolError inv = mapError(new Exception("Failed to parse PDF"));
System.out.printf("map-invalid -> %s: %s%n",
inv.kind == ErrorKind.ENCRYPTED ? "encrypted" : "invalid", inv.getMessage());
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →