Invoices, tickets, reports, signed forms and statements end up as PDF files sooner or later. An app either produces them, often on the server where the data lives, or shows ones it received. Codename One does both in Java, without a native PDF library or a platform viewer:

  • com.codename1.pdf writes and reads PDF files. It has no dependency on the UI, so the same code runs in an app, in a test and in a Codename One backend.

  • com.codename1.pdf.ui.PdfViewer displays a PDF in your UI. It renders pages with a pure-Java renderer, so a document looks the same on iOS, Android, desktop, the web and the simulator, and the viewer doesn’t depend on a browser or an operating system component.

Drawing a page

PdfDocument holds the pages. Each PdfPage has a PdfCanvas measured in points (1/72 inch), with the origin at the top left corner and y growing downwards, like Graphics:

PdfDocument doc = new PdfDocument().setTitle("Ticket");
PdfPage page = doc.addPage(PdfPageSize.A5);
PdfCanvas c = page.getCanvas();
c.setFillColor(0x1565c0).fillRect(0, 0, page.getWidth(), 60);
c.setFillColor(0xffffff).setFont(PdfFont.HELVETICA_BOLD, 20).drawText("Boarding pass", 16, 38);
c.setStrokeColor(0x9e9e9e).setDash(new float[] {4, 3}, 0).drawLine(16, 120, page.getWidth() - 16, 120);
c.setFillColor(0x212121).setFont(PdfFont.HELVETICA, 12).drawText("Gate B12, seat 14C", 16, 150);
byte[] pdf = doc.toByteArray();

The canvas covers what a page needs: paths with lines, curves, rectangles, rounded rectangles and ellipses, filled, stroked, dashed or used as clip; transforms; RGB colors with alpha; text in a font; and images. PdfImage.create(byte[]) takes encoded JPEG or PNG data, and PdfImage.create(int[], int, int) takes ARGB pixels, so anything drawn on a mutable Image can go into a document. PdfPage.addLink makes a rectangle a link to a URL or to another page, and PdfDocument.addBookmark adds an entry to the reader’s outline.

Fonts

The 14 standard PDF fonts (Helvetica, Times, Courier with their bold and italic variants, Symbol and Zapf Dingbats) are constants of PdfFont. They cost nothing to use, since every PDF reader has them, but they cover only Western European characters: any other character drawn in one of them comes out as a question mark.

For any other text, load a TrueType or OpenType font with PdfFont.loadTrueType(byte[]). Only the glyphs the document uses are embedded, together with a map from each glyph back to its text, so readers can search and copy the text.

Right-to-left text

Text is given in reading order. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm, so numbers and Latin words inside them keep their own order, and brackets mirror. Arabic letters take their joined forms, from the font’s own substitution tables when it has them. A paragraph whose first strong character is right to left starts at the right margin:

PdfFont hebrewAndArabic = PdfFont.loadTrueType(
        Util.readInputStream(CN.getResourceAsStream("/NotoSansHebrewArabic.ttf")));
PdfLayout layout = new PdfLayout(new PdfDocument(), PdfPageSize.A4, 48);
layout.add(new PdfParagraph("\u05e9\u05dc\u05d5\u05dd \u05e2\u05d5\u05dc\u05dd (Hello world)",
        hebrewAndArabic, 14));
layout.add(new PdfParagraph("\u0645\u0631\u062d\u0628\u0627 \u0628\u0627\u0644\u0639\u0627\u0644\u0645",
        hebrewAndArabic, 14).setAlignment(PdfParagraph.ALIGN_JUSTIFY));

PdfParagraph.setDirection and the direction argument of PdfCanvas.drawText override that choice.

Flowing content across pages

Positioning every line by hand suits a ticket. A report or an invoice needs text that wraps and tables that run onto the next page. PdfLayout places paragraphs, tables, images, rules and spaces one under another and starts a new page when the current one is full:

byte[] fontTtf = Util.readInputStream(CN.getResourceAsStream("/NotoSans-Regular.ttf"));
byte[] logoPng = Util.readInputStream(CN.getResourceAsStream("/logo.png"));
PdfFont body = PdfFont.loadTrueType(fontTtf);
PdfDocument doc = new PdfDocument().setTitle("Invoice 1042");
PdfLayout layout = new PdfLayout(doc, PdfPageSize.A4, 48);
layout.setPageDecorator(new PdfLayout.PageDecorator() {
    public void decorate(PdfPage page, int number, int count) {
        page.getCanvas().setFont(PdfFont.HELVETICA, 9).setFillColor(0x757575)
                .drawText("Page " + number + " of " + count, 48, page.getHeight() - 24);
    }
});
layout.addImage(PdfImage.create(logoPng), 120, PdfParagraph.ALIGN_LEFT);
layout.add(new PdfParagraph("Invoice 1042", PdfFont.HELVETICA_BOLD, 22).setSpaceAfter(12));
layout.add(new PdfParagraph("Thank you for your order. Payment is due within ", body, 11)
        .append("30 days", PdfFont.HELVETICA_BOLD, 11)
        .append(". Questions? ", body, 11)
        .appendLink("Contact us", "mailto:billing@example.com", body, 11, 0x1565c0)
        .setAlignment(PdfParagraph.ALIGN_JUSTIFY));
PdfTable items = new PdfTable(4, 1, 1.5f).setHeaderRows(1).setFont(body, 10).setBorder(0.5f, 0xbdbdbd);
items.addCell("Item").addCell("Qty").addCell("Price");
for (int i = 1; i <= 60; i++) {
    items.addCell("Widget " + i).addCell("1").addCell("$9.90");
}
layout.add(items);
layout.finish();
String path = FileSystemStorage.getInstance().getAppHomePath() + "invoice-1042.pdf";
OutputStream out = FileSystemStorage.getInstance().openOutputStream(path);
try {
    doc.save(out);
} finally {
    Util.cleanup(out);
}
  • A PdfParagraph is made of runs, each with its own font, size and color, or a link. It wraps at word boundaries and aligns left, right, centered, justified, or to the start side of its direction.

  • A PdfTable divides the content width between its columns by weight. Cells hold text or paragraphs, can span columns and have backgrounds. A row that doesn’t fit on the page carries over to the next one, and the header rows repeat at the top of each page.

  • The PageDecorator runs once per page after finish(), when the page count is known, which is what a "Page 3 of 7" footer needs.

On the server

Nothing in com.codename1.pdf touches the UI, so a Codename One backend generates documents with the same classes. A typical use is an endpoint that returns doc.toByteArray() with the application/pdf content type, or a scheduled job that mails monthly statements. The app and the server can share the code that lays out a document.

Signing a PDF

A certificate of completion, a contract or a statement often has to prove where it came from and that nobody changed it afterward. PdfDocument.sign embeds a digital signature when the document is saved. It’s a PAdES baseline signature: a detached CMS signature over the whole file, using SHA-256 and carrying the signer’s certificate. Acrobat, Preview and Poppler’s pdfsig show it as signed:

// The signer's key and certificate, shipped with the app or fetched
// from your server.
PrivateKey key = PrivateKey.fromPem(new String(
        Util.readInputStream(CN.getResourceAsStream("/signer-key.pem")), "UTF-8"));
byte[] certificateDer = Util.readInputStream(CN.getResourceAsStream("/signer.der"));
PdfDocument doc = new PdfDocument().setTitle("Certificate of completion");
PdfPage page = doc.addPage(PdfPageSize.A4);
doc.sign(new PdfSignature(PdfSigner.provider(key, certificateDer))
        .setReason("Certificate of completion")
        .setLocation("Lingo Academy")
        .setVisible(page, 380, 760, 180, 50));
byte[] signed = doc.toByteArray();

PdfSignature holds what the reader sees: the reason, the location, the contact details and the signing time, plus an optional visible box on a page. Without setVisible the signature is invisible. The key itself stays behind a PdfSignatureProvider, which returns the certificate chain and signs one block of bytes when asked. PdfSigner.provider builds one over a PrivateKey and the platform crypto bridge. On a Codename One server, implement the interface over com.codename1.backend.Crypto.sign, or over a hardware security module, and the private key never has to be handed to the PDF code.

A viewer trusts a signature only when it trusts the certificate. A self-signed certificate produces a valid signature, but an untrusted one. To be trusted by every reader, a document must be signed with a certificate from a CA in the Adobe Approved Trust List. Within your own system, comparing the signer’s certificate with the one you expect is enough.

Reading a signature back doesn’t need a viewer. PdfSignatureInfo.find returns every signature in a file, and the checks are split by what they need:

  • isDigestValid() says whether the signed bytes still hash to the value the signature commits to.

  • coversWholeDocument() says whether anything was appended after signing.

  • isCertificateBound() says whether the embedded certificate is the one the signature names.

  • PdfSigner.verify adds the public-key check.

byte[] pdf = Util.readInputStream(CN.getResourceAsStream("/certificate.pdf"));
byte[] expected = Util.readInputStream(CN.getResourceAsStream("/signer.der"));
boolean trusted = false;
for (PdfSignatureInfo info : PdfSignatureInfo.find(pdf)) {
    boolean intact = PdfSigner.verify(info) && info.coversWholeDocument();
    boolean ours = java.util.Arrays.equals(info.getSignerCertificate(), expected);
    trusted = trusted || intact && ours;
}
Log.p(trusted ? "Signed by us and unchanged" : "Not our signature, or altered");

Reading a PDF

PdfReader opens an existing file to read its page count, page sizes, metadata and text:

String path = FileSystemStorage.getInstance().getAppHomePath() + "invoice-1042.pdf";
PdfReader reader = PdfReader.open(FileSystemStorage.getInstance().openInputStream(path));
Log.p(reader.getTitle() + ": " + reader.getPageCount() + " pages");
String firstPage = reader.extractText(0);

The reader handles the structures real files use: cross-reference tables and streams, object streams, incremental updates, and files with broken cross-references, which it rebuilds by scanning. Encrypted files open with PdfReader.open(data, password), using RC4 or AES (128 and 256 bit) as the standard security handler defines them. Either the user or the owner password works.

Text comes out in reading order, line by line, with right-to-left lines reordered. Text in fonts without a map to Unicode is recovered from the font’s encoding, or, for Chinese, Japanese and Korean fonts, from Adobe’s character collections.

Showing a PDF

PdfViewer is a component that shows the pages one under another, fitted to its width. The user scrolls through them, zooms with a pinch or a double tap, and pans a zoomed page:

String path = FileSystemStorage.getInstance().getAppHomePath() + "invoice-1042.pdf";
byte[] pdf = Util.readInputStream(FileSystemStorage.getInstance().openInputStream(path));
PdfViewer viewer = new PdfViewer(pdf);
Form form = new Form("Invoice", new BorderLayout());
form.add(BorderLayout.CENTER, viewer);
form.show();
viewer.setPage(2);

Pages are drawn on the EDT one at a time, between other events, and only the pages near the view are kept in memory. A heavy page, such as a detailed map, holds input until it’s done. renderPage(index, scale) draws a single page to an Image, for a thumbnail or a share sheet, without showing the viewer.

The renderer draws what the PDF specification defines: vector graphics with dashes, clipping and every blend mode; transparency groups, knockout groups and soft masks; axial, radial, function-based and mesh shadings; tiling patterns; embedded TrueType, OpenType, CFF, Type 1 and Type 3 fonts, including vertical writing; and images in every format PDF defines, among them JPEG, JPEG 2000, JBIG2 and CCITT fax, with their masks. Form fields and annotations are drawn from their appearances.

A font that isn’t embedded in the file is drawn with a platform font of the same family, so its letters can differ in shape from what the author saw. PDF generators embed fonts by default, so this mostly affects old files.

Printing a PDF

The printing API takes PDF files directly. Save the document to FileSystemStorage and pass its path:

String path = FileSystemStorage.getInstance().getAppHomePath() + "invoice-1042.pdf";
if (Printer.isPrintingSupported()) {
    Printer.printPDF(path, null);
}

See the Printing chapter for the details of the print dialog and its result.