Rendering pages
Render PDF pages to PNG with NexPDF for Flutter, show them in an Image widget, and map PDF coordinates to widget 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
renderPagePng(pageIndex, dpi:) returns the PNG bytes of a page. At 72 dpi one pixel is one PDF
point; the default is 150. For a sharp image, multiply 72 by the device pixel ratio and the zoom:
import 'package:flutter/widgets.dart';
import 'package:nexpdf_flutter/nexpdf_flutter.dart';
Widget pageImage(BuildContext context, NexPdfDocument doc, int page) {
final dpi = 72 * MediaQuery.devicePixelRatioOf(context);
return Image.memory(doc.renderPagePng(page, dpi: dpi), gaplessPlayback: true);
}renderPagePng throws NexPdfException if the page cannot be rendered. Rendering is synchronous:
for large pages or many thumbnails, open the document in a background isolate and render there.
Page size and orientation
pageSize(i) returns the displayed size in points, with the crop box, /Rotate and /UserUnit
applied. pageView(i) returns a NexPdfPageView with the rotation, the crop box and the transform
between PDF user space and the displayed page (origin at the top-left, y down):
final size = doc.pageSize(0);
final view = doc.pageView(0);
print('${size.width} x ${size.height}, rotation ${view.rotation}');
const scale = 144 / 72; // pixels per point at 144 dpi
final (x, y) = view.toView(72, 700, scale); // PDF point to image pixels
final (px, py) = view.toPdf(tapX, tapY, scale); // a tap back to PDF points
final (l, t, r, b) = view.rectToView(hit.llx, hit.lly, hit.urx, hit.ury, scale); // a search hitThumbnails
nexpdf_render_thumb_png fits a page into a square of max_dim pixels. It has no Dart method;
call it through dart:ffi:
import 'dart:ffi';
import 'nexpdf_ffi.dart';
// NexPdfBytes nexpdf_render_thumb_png(const NexPdfDocument *doc, size_t page_index, uint32_t max_dim);
final renderThumb = nexpdfLib.lookupFunction<
NexPdfBytes Function(Pointer<Void>, Size, Uint32),
NexPdfBytes Function(Pointer<Void>, int, int)>('nexpdf_render_thumb_png');
final thumb = nexpdfCall(() => takeBytes(renderThumb(doc.handle, 0, 256)));Overprint simulation
Print-oriented PDF/X files can use overprint. nexpdf_set_overprint(doc, mode) sets how later
renders treat it: 0 simulates it for PDF/X documents only (the default), 1 always, 2 never.
final setOverprint = nexpdfLib.lookupFunction<Int32 Function(Pointer<Void>, Int32),
int Function(Pointer<Void>, int)>('nexpdf_set_overprint');
nexpdfCall(() => setOverprint(doc.handle, 1));Related
NexPdfDocument,NexPdfPageView- Reader for a ready-made page view