Rendering pages
Render PDF pages and thumbnails to PNG with NexPDF for Java, and map PDF coordinates to pixels.
License module
Rendering is part of the viewer module and works without a key. Unlicensed and trial renders carry
a watermark; commercial keys render without one.
Render a page to PNG
renderPagePng(pageIndex, dpi) returns the PNG bytes of a page. At 72 dpi one pixel is one PDF
point; 144 dpi is a good default for screens, 300 dpi for print.
import com.nexdevit.nexpdf.NexPdfDocument;
import java.nio.file.Files;
import java.nio.file.Path;
try (NexPdfDocument doc = NexPdfDocument.open(Path.of("report.pdf"))) {
for (int i = 0; i < doc.pageCount(); i++) {
Files.write(Path.of("page-" + (i + 1) + ".png"), doc.renderPagePng(i, 144));
}
}To get a BufferedImage, read the bytes with ImageIO.read(new ByteArrayInputStream(png)).
Render a thumbnail
renderThumbPng(pageIndex, maxDim) fits the page into a square of maxDim pixels, keeping the
aspect ratio:
byte[] thumb = doc.renderThumbPng(0, 256);Page size and orientation
pageWidth(i) and pageHeight(i) return the displayed size in points, with the crop box, /Rotate
and /UserUnit applied. pageViewJson(i) adds the rotation, the crop box and the matrix from PDF
user space to the displayed page.
The examples in these guides read JSON with Jackson
(com.fasterxml.jackson.core:jackson-databind). That is only a choice: the SDK returns plain JSON
strings and any JSON library works.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper json = new ObjectMapper();
JsonNode view = json.readTree(doc.pageViewJson(0));
System.out.println(view.get("rotation") + " " + view.get("crop") + " " + view.get("to_display"));To place a PDF rectangle (for example a search hit) on a rendered image, apply to_display
[a, b, c, d, e, f] and multiply by dpi / 72:
static double[] toPixels(JsonNode view, double x, double y, double dpi) {
JsonNode m = view.get("to_display");
double s = dpi / 72;
return new double[] {
(m.get(0).asDouble() * x + m.get(2).asDouble() * y + m.get(4).asDouble()) * s,
(m.get(1).asDouble() * x + m.get(3).asDouble() * y + m.get(5).asDouble()) * s,
};
}Overprint simulation
Print-oriented PDF/X files can use overprint. setOverprint(mode) sets how later renders treat it:
0 simulates it for PDF/X documents only (the default), 1 always, 2 never.
doc.setOverprint(1);
byte[] png = doc.renderPagePng(0, 300);Memory
Rendering caches decoded fonts and images per document. For long-running workers,
doc.trimMemory() drops those caches and doc.memoryUsageBytes() reports the current use.