Skip to Content
NexPDF

Getting started

Activate a license, open a PDF, count its pages, render a page to PNG and extract its text with NexPDF for Java.

English

This example opens a PDF, prints the page count, renders the first page to a PNG file and prints the text of every page. It runs without a license key too: viewing is always allowed, and rendered pages then carry a watermark.

Add the SDK

Add com.nexdevit:nexpdf:1.1.0 and make the native library available as described in Installation.

Write the program

QuickStart.java
import com.nexdevit.nexpdf.NexPdf;
import com.nexdevit.nexpdf.NexPdfDocument;
import java.nio.file.Files;
import java.nio.file.Path;

public class QuickStart {
    public static void main(String[] args) throws Exception {
        // 1. Activate the license once per process (optional for viewing).
        String licenseFile = System.getenv("NEXPDF_LICENSE");
        if (licenseFile != null) {
            NexPdf.activateLicense(Files.readString(Path.of(licenseFile)), "server", "com.acme.quickstart");
        }

        // 2. Open the document.
        Path path = Path.of(args.length > 0 ? args[0] : "sample.pdf");
        try (NexPdfDocument doc = NexPdfDocument.open(path)) {
            // 3. Page count and size.
            int count = doc.pageCount();
            System.out.printf("%s: %d pages, first page %.0f x %.0f pt%n",
                    path, count, doc.pageWidth(0), doc.pageHeight(0));

            // 4. Render the first page at 144 dpi.
            Files.write(Path.of("page1.png"), doc.renderPagePng(0, 144));

            // 5. Extract the text of every page.
            for (int i = 0; i < count; i++) {
                System.out.println("--- page " + (i + 1) + " ---");
                System.out.println(doc.extractPageText(i));
            }
        }
    }
}

Run it

java -Dnexpdf.library.path=/opt/nexpdf/lib/libnexpdf_ffi.so QuickStart.java contract.pdf

page1.png is written to the working directory.

What the code does

  • NexPdf.activateLicense(keyOrXml, platform, appId) accepts the license XML or the bare key. The app id must be one the key was issued for. See License.
  • NexPdfDocument.open(path) opens a PDF; open(path, password) opens an encrypted one. Word, Excel and PowerPoint files are converted when the license includes conversion; JPEG, PNG and TIFF pictures become one page each. openBytes(byte[]) opens from memory.
  • pageWidth(i) and pageHeight(i) are the displayed size in points: crop box, rotation and /UserUnit applied.
  • renderPagePng(i, dpi) returns PNG bytes. 72 dpi is one pixel per point.
  • extractPageText(i) returns the page text in reading order.

Next steps

On this page