Library mode

Use Java libraries in JavaScript

Library mode allows you to directly use Java methods, objects, and arrays from JavaScript. This API has been designed to take advantage of async/await to feel more natural to use, without sacrificing any flexibility.

Loading a library is as simple as calling cheerpjRunLibrary.

async function libraryModeTour() {
await cheerpjInit();
// Create a library mode object
const lib = await cheerpjRunLibrary(""); // "" means standard library only
// Resolve the Java classes we are going to use
const ArrayList = await;
const Point = await;
const System = await;
// Create a new list object
const points = await new ArrayList();
// Create 4 point objects
for (let i = 0; i < 4; i++) {
// Allocate the point
const p = await new Point(i, 0);
// Add the point to the list
await points.add(p);
// Convert to list to an Object[] array
const a = await points.toArray();
// Iterate on the array and set y = x
for (let i = 0; i < a.length; i++) {
// Fields can be read and written directly
a[i].y = a[i].x;
// Convert all the elements to Strings
for (let i = 0; i < a.length; i++) {
// Java arrays can be read and written directly
a[i] = await a[i].toString();
// Print them out
for (let i = 0; i < a.length; i++) {
// Static fields can be accessed too
await System.out.println(a[i]);

Library mode can be used to integrate powerful Java libraries into your Web application. As a practical example, these few lines of code make it possible to generate a PDF from JavaScript using the popular iText library:

async function iTextExample() {
await cheerpjInit();
const lib = await cheerpjRunLibrary("/app/itextpdf-");
try {
const Document = await;
const Paragraph = await;
const PdfWriter = await;
const FileOutputStream = await;
const document = await new Document();
const writer = await PdfWriter.getInstance(
await new FileOutputStream("/files/HelloIText.pdf"),
await document.add(await new Paragraph("Hello World!"));
await document.close();
await writer.close();
const blob = await cjFileBlob("/files/HelloIText.pdf");
const url = URL.createObjectURL(blob); = url;
} catch (e) {
const IOException = await;
if (e instanceof IOException) console.log("I/O error");
else console.log("Unknown error: " + (await e.getMessage()));

See also

Library mode is also used for native methods implemented in JavaScript. A native is effectively just a shorter library mode session.

Was this page helpful?
Suggest changes