GroupDocs.Watermark can render document pages as images so you can show page thumbnails without fully opening a document in a viewer. You drive the render with a create_page_stream callback that supplies a writable file stream for each page — the library writes the page image to it and closes it for you.
Generate a document preview
Set PreviewOptions with a create_page_stream callback, choose the preview_format, and list the page_numbers to render.
fromgroupdocs.watermarkimportWatermarkerfromgroupdocs.watermark.optionsimportPreviewOptions,PreviewFormatsdefgenerate_preview():# Supply a writable file stream for each page to renderdefcreate_page_stream(page_number):returnopen(f"./output-page-{page_number}.png","wb")withWatermarker("./sample.pdf")aswatermarker:options=PreviewOptions(create_page_stream)options.preview_format=PreviewFormats.PNGoptions.page_numbers=[1,2]watermarker.generate_preview(options)if__name__=="__main__":generate_preview()
sample.pdf is the two-page sample file used in this example. Click here to download it.
The page images are written to the current directory — one PNG per requested page. Use PreviewFormats.JPEG or PreviewFormats.BMP for other formats, and set options.width / options.height to control the rendered size.
The library closes each file create_page_stream returns once the page is written. To act on a page as soon as it is ready, pass a second callback: PreviewOptions(create_page_stream, release_page_stream) calls release_page_stream(page_number, stream) with the object create_page_stream returned for that page, after the whole image is in it. A one-argument release_page_stream(page_number) works too. create_page_stream may also return an io.BytesIO: it stays open, and holds the page image by the time release_page_stream gets it.
Use case: Generate page previews to display in a web app, dashboard, or document-management system without requiring users to download the full file.
Was this page helpful?
Any additional feedback you'd like to share with us?
Please tell us how we can improve this page.
Thank you for your feedback!
We value your opinion. Your feedback will help us improve our documentation.