Rendering pages
Render PDF pages and thumbnails to PNG with NexPDF for C++, 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
render_page_png(page_index, 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.
#include <nexpdf.hpp>
namespace nexpdf = nexdevit::nexpdf;
auto doc = nexpdf::Document::open("report.pdf");
for (int32_t i = 0; i < doc.page_count(); ++i) {
write_file("page-" + std::to_string(i + 1) + ".png", doc.render_page_png(i, 144));
}Render a thumbnail
render_thumb_png(page_index, max_dim) fits the page into a square of max_dim pixels, keeping the
aspect ratio:
std::vector<uint8_t> thumb = doc.render_thumb_png(0, 256);Page size and orientation
page_width(i) and page_height(i) return the displayed size in points, with the crop box,
/Rotate and /UserUnit applied. page_view_json(i) adds the rotation, the crop box and the
matrix from PDF user space to the displayed page:
#include <nlohmann/json.hpp> // an example; use your JSON library
double w = doc.page_width(0), h = doc.page_height(0);
auto view = nlohmann::json::parse(doc.page_view_json(0));
std::cout << view["rotation"] << " " << view["crop"] << " " << view["to_display"] << "\n";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:
std::pair<double, double> to_pixels(const nlohmann::json& view, double x, double y, double dpi) {
const auto& m = view["to_display"];
double a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
double s = dpi / 72;
return {(a * x + c * y + e) * s, (b * x + d * y + f) * s};
}Overprint simulation
Print-oriented PDF/X files can use overprint. set_overprint(mode) sets how later renders treat
it: 0 simulates it for PDF/X documents only (the default), 1 always, 2 never.
doc.set_overprint(1);
auto png = doc.render_page_png(0, 300);Memory
Rendering caches decoded fonts and images per document. For long-running workers,
doc.trim_memory() drops those caches and doc.memory_usage_bytes() reports the current use.