Rendering pages
Render PDF pages and thumbnails to PNG with NexPDF for Go, 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.
doc, err := nexpdf.Open("report.pdf")
if err != nil {
log.Fatal(err)
}
defer doc.Close()
n, _ := doc.PageCount()
for i := 0; i < int(n); i++ {
png, err := doc.RenderPagePNG(i, 144)
if err != nil {
log.Fatal(err)
}
os.WriteFile(fmt.Sprintf("page-%d.png", i+1), png, 0o644)
}Render a thumbnail
RenderThumbPNG(pageIndex, maxDim) fits the page into a square of maxDim pixels, keeping the
aspect ratio:
thumb, err := 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:
type PageView struct {
Rotation int `json:"rotation"`
Crop []float64 `json:"crop"`
ToDisplay [6]float64 `json:"to_display"`
}
s, _ := doc.PageViewJSON(0)
var view PageView
json.Unmarshal([]byte(s), &view)
fmt.Println(view.Rotation, view.Crop, view.ToDisplay)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:
func toPixels(view PageView, x, y, dpi float64) (float64, float64) {
a, b, c, d, e, f := view.ToDisplay[0], view.ToDisplay[1], view.ToDisplay[2],
view.ToDisplay[3], view.ToDisplay[4], view.ToDisplay[5]
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. 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)
png, err := 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.