GroupDocs.Viewer for Python via .NET is designed to work seamlessly with AI agents, LLMs, and automated code generation tools. The library ships machine-readable documentation in multiple formats — including an AGENTS.md file inside the pip package itself — so that AI assistants can discover and use the API without manual guidance.
MCP server
GroupDocs provides an MCP (Model Context Protocol) server that enables LLMs to query the documentation on demand instead of loading it all at once. This saves tokens and lets your AI assistant fetch only the information it needs for the current task.
To connect your AI tool to the MCP server, add the GroupDocs endpoint to your MCP configuration:
// Claude Code: ~/.claude/settings.json (or project .mcp.json)
// Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json
{"mcpServers":{"groupdocs-docs":{"url":"https://docs.groupdocs.com/mcp"}}}
// .vscode/mcp.json in your project root
{"servers":{"groupdocs-docs":{"url":"https://docs.groupdocs.com/mcp"}}}
// .cursor/mcp.json in your project root
{"mcpServers":{"groupdocs-docs":{"url":"https://docs.groupdocs.com/mcp"}}}
The documentation server helps an agent write code. The GroupDocs.Viewer MCP server is a separate tool for the opposite case: the agent itself needs to see a document. It renders any page of a PDF, Word, Excel, PowerPoint, email or CAD file as a PNG image on your machine and hands it to the agent, so a vision-capable model can read a chart, check a layout or describe a scan, with nothing uploaded. Run it with Docker, or with dnx GroupDocs.Viewer.Mcp --yes when the .NET 10 SDK is installed:
docker run --rm -i -v $(pwd)/documents:/data ghcr.io/groupdocs-viewer/viewer-net-mcp:latest
Use the documentation server when an agent writes Python code against this library, and the Viewer MCP server when the agent reads documents. SDK, Cloud or MCP? compares the options.
AGENTS.md — built into the package
The groupdocs-viewer-net pip package includes an AGENTS.md file at groupdocs/viewer/AGENTS.md. AI coding assistants that scan installed packages (such as Claude Code, Cursor, GitHub Copilot) can automatically discover the API surface, usage patterns, and troubleshooting tips.
After installing the package, you can find it at:
pip show -f groupdocs-viewer-net | grep AGENTS
Machine-readable documentation
Every documentation page is available as a plain Markdown file that AI tools can fetch and process directly:
Point your AI assistant to the full documentation file for comprehensive context:
Fetch https://docs.groupdocs.com/viewer/python-net/llms-full.txt and use it
as a reference for GroupDocs.Viewer for Python via .NET API.
Or reference individual pages for focused tasks:
Read https://docs.groupdocs.com/viewer/python-net/quick-start-guide.md
and help me render a DOCX to HTML in Python.
Why GroupDocs.Viewer is a good building block for AI document pipelines
LLMs and RAG systems can rarely consume DOCX, XLSX, PPTX, EML, CAD drawings, or scanned PDFs directly. GroupDocs.Viewer renders the long tail of office, image, CAD, email, and archive formats into the few formats your model can actually read:
Render to per-page PNG / JPG for vision models — one image per page, size-controlled, ready to feed straight to a multimodal LLM.
Render to PDF for OCR and page-level routing — with watermarks, password protection, or optimization applied during rendering.
Render to HTML when you want to keep semantic structure (headings, tables, lists) for downstream parsers or embedding generators.
Render to HTML with external resources for indexing systems that want the markup and assets separated.
A typical preprocessing step looks like:
fromgroupdocs.viewerimportViewerfromgroupdocs.viewer.optionsimport(HtmlViewOptions,PdfViewOptions,PngViewOptions,ViewInfoOptions,)# Step 1: Inspect — let the agent decide what to do based on metadatawithViewer("inbox/incoming.docx")asv:file_info=v.get_file_info()view_info=v.get_view_info(ViewInfoOptions.for_html_view())print(f"format={file_info.file_type.file_format} pages={len(view_info.pages)}")# Step 2: Render to a model-friendly formatwithViewer("inbox/incoming.docx")asv:# HTML for structure-preserving parsingv.view(HtmlViewOptions.for_embedded_resources("staging/incoming_{0}.html"))# PDF for OCR / page routingv.view(PdfViewOptions("staging/incoming.pdf"))# Per-page PNG for vision modelsv.view(PngViewOptions("staging/incoming_page_{0}.png"))
For end-to-end examples — including rendering archives, attachments, password-protected documents, and format-specific options — see the Developer Guide and Rendering Basics. Every code block on those pages has a runnable counterpart in the examples repository.
Pair with GroupDocs.Conversion for hard-to-render inputs
If you are handling exotic or legacy formats (older DOC/XLS/PPT, password-protected archives, custom email containers), chain GroupDocs.Viewer with GroupDocs.Conversion for Python via .NET:
Use GroupDocs.Conversion to normalise the source — for example, convert a legacy .doc or a PST archive entry to .docx or .pdf.
Use GroupDocs.Viewer to render the normalised file to HTML, PDF, PNG, or JPG that your model can consume.
This combination covers the long tail of input formats while keeping the model-facing stage simple and predictable.
AGENTS.md reference
The content below is the same AGENTS.md file that ships inside the groupdocs-viewer-net package. Copy it into your project as AGENTS.md or point your AI assistant to this page.
# GroupDocs.Viewer for Python via .NET -- AGENTS.md
> Instructions for AI agents working with this package.
Render documents to HTML, PNG, JPG, or PDF -- 190+ file formats supported -- to files or to memory, and open them in the browser with the `groupdocs-viewer` command.
## Install
```bash
pip install groupdocs-viewer-net
```**Python**: 3.5 - 3.14 (pip 20.3+) | **Platforms**: Windows x64, Linux x64 (glibc 2.27+), macOS 12+ (x64, ARM64)
pip also installs `groupdocs-shared-net`, which holds the modules every GroupDocs Python package shares. For an offline install, download both wheels and install them together: `pip install --no-index --find-links <folder> groupdocs-viewer-net`.
## Resources
| Resource | URL |
|---|---|
| Documentation | https://docs.groupdocs.com/viewer/python-net/ |
| LLM-optimized docs | https://docs.groupdocs.com/viewer/python-net/llms-full.txt |
| API reference | https://reference.groupdocs.com/viewer/python-net/ |
| Code examples | https://docs.groupdocs.com/viewer/python-net/developer-guide/ |
| Release notes | https://releases.groupdocs.com/viewer/python-net/release-notes/ |
| PyPI | https://pypi.org/project/groupdocs-viewer-net/ |
| Free support forum | https://forum.groupdocs.com/c/viewer/ |
| Temporary license | https://purchase.groupdocs.com/temporary-license |
## MCP Server
If your environment has MCP configured, you can connect your AI tool to the GroupDocs documentation server for on-demand API lookups:
```json
{"mcpServers":{"groupdocs-docs":{"url":"https://docs.groupdocs.com/mcp"}}}```Works with Claude Code (`~/.claude/settings.json`), Cursor (`.cursor/mcp.json`), VS Code Copilot (`.vscode/mcp.json`), and any MCP-compatible client. If MCP is unavailable, fall back to the LLM-optimized docs URL above and this file -- both are shipped inside the wheel.
**GroupDocs.Viewer MCP server.** A separate server lets an agent see document pages: it renders any page as a PNG image on the user's machine and hands it to the agent, with nothing uploaded. Run it with `docker run --rm -i -v $(pwd)/documents:/data ghcr.io/groupdocs-viewer/viewer-net-mcp:latest`, or `dnx GroupDocs.Viewer.Mcp --yes` with the .NET 10 SDK. Setup for each AI client: https://docs.groupdocs.com/viewer/mcp/
## Imports
```python
fromgroupdocs.viewerimportLicense,FileType,Viewer,ViewerSettingsfromgroupdocs.viewer.exceptionsimport(GroupDocsViewerException,IncorrectPasswordException,PasswordRequiredException,InvalidFontFormatException,InvalidImageFormatException,)fromgroupdocs.viewer.cachingimportCacheKeys,FileCache,ICachefromgroupdocs.viewer.drawingimport(Argb32Color,Rgb24Color,CssLevel1,CssLevel2,CssLevel3,CssLevel4,Image2DFormat,KnownColors,)fromgroupdocs.viewer.fontsimport(FolderFontSource,FontFormat,FontSettings,FontStyles,IFontInfo,IFontSource,PdfFontInfo,PresentationFontInfo,SpreadsheetFontInfo,WordProcessingFontInfo,WordProcessingSubstitutedFontInfo,SearchOption,)fromgroupdocs.viewer.interfacesimport(CreatePageStream,CreateResourceStream,CreateResourceUrl,CreateFileStream,ReleasePageStream,ReleaseResourceStream,ReleaseFileStream,IPageStreamFactory,IResourceStreamFactory,IFileStreamFactory,)fromgroupdocs.viewer.loggingimportConsoleLogger,FileLogger,ILoggerfromgroupdocs.viewer.optionsimport(# View-options flavours — the four output formatsHtmlViewOptions,PngViewOptions,JpgViewOptions,PdfViewOptions,ViewInfoOptions,ViewOptions,BaseViewOptions,# Loading + format-specific rendering tweaksLoadOptions,ArchiveOptions,CadOptions,EmailOptions,MailStorageOptions,OutlookOptions,PdfOptimizationOptions,PdfOptions,PresentationOptions,ProjectManagementOptions,SearchHighlightOptions,SpreadsheetOptions,TextOptions,VisioRenderingOptions,WebDocumentOptions,WordProcessingOptions,# Rendering primitivesWatermark,Rotation,Position,ImageQuality,PageSize,Permissions,Security,Resolution,Size,Tile,TimeUnit,TextOverflowMode,Field,FileName,)fromgroupdocs.viewer.resultsimport(ViewInfo,FileInfo,Attachment,Page,Resource,TextElement,Character,Word,Line,ArchiveViewInfo,CadViewInfo,MailMessageViewInfo,MboxViewInfo,OutlookViewInfo,LotusNotesViewInfo,PdfViewInfo,ProjectManagementViewInfo,Layer,Layout,)```## Quick Start
```python
fromgroupdocs.viewerimportViewerfromgroupdocs.viewer.optionsimportHtmlViewOptionswithViewer("document.docx")asviewer:options=HtmlViewOptions.for_embedded_resources("page_{0}.html")viewer.view(options)```## Render to PNG
```python
fromgroupdocs.viewerimportViewerfromgroupdocs.viewer.optionsimportPngViewOptionswithViewer("document.pdf")asviewer:viewer.view(PngViewOptions("page_{0}.png"))```## Render to PDF
```python
fromgroupdocs.viewerimportViewerfromgroupdocs.viewer.optionsimportPdfViewOptionswithViewer("spreadsheet.xlsx")asviewer:viewer.view(PdfViewOptions("output.pdf"))```## Render selected pages / reorder pages
```python
fromgroupdocs.viewerimportViewerfromgroupdocs.viewer.optionsimportHtmlViewOptions,PdfViewOptions# Render only pages 1 and 3withViewer("document.docx")asviewer:viewer.view(HtmlViewOptions.for_embedded_resources("page_{0}.html"),page_numbers=[1,3])# Reorder: render page 2 first, then page 1withViewer("document.docx")asviewer:viewer.view(PdfViewOptions("out.pdf"),page_numbers=[2,1])```## Load password-protected documents
```python
fromgroupdocs.viewerimportViewerfromgroupdocs.viewer.optionsimportHtmlViewOptions,LoadOptionsload_options=LoadOptions()load_options.password="12345"withViewer("protected.docx",load_options)asviewer:viewer.view(HtmlViewOptions.for_embedded_resources("page_{0}.html"))```## Get View Info
```python
fromgroupdocs.viewerimportViewerfromgroupdocs.viewer.optionsimportViewInfoOptionswithViewer("document.pdf")asviewer:info=viewer.get_view_info(ViewInfoOptions.for_html_view())print("Pages:",len(info.pages))forpageininfo.pages:print(" Page %d: %dx%d"%(page.number,page.width,page.height))```**Viewer constructor.**`Viewer(source, load_options=None, settings=None, leave_open=None)` accepts all four positional **or** as kwargs. Prefer kwargs when you only need `settings`:
```python
fromgroupdocs.viewerimportViewer,ViewerSettingsfromgroupdocs.viewer.loggingimportConsoleLoggerfromgroupdocs.viewer.optionsimportHtmlViewOptionssettings=ViewerSettings(logger=ConsoleLogger())withViewer("input.docx",settings=settings)asviewer:# no None placeholderviewer.view(HtmlViewOptions.for_embedded_resources("page_{0}.html"))```## Render to custom streams
Viewer accepts Python callables that return streams. Pass a function to the `HtmlViewOptions` / `PngViewOptions` / `JpgViewOptions` / `PdfViewOptions` constructors that take the `CreatePageStream` / `CreateResourceStream` / `CreateResourceUrl` / `CreateFileStream` delegates, and the bridge wraps it as the .NET delegate. This lets a web service return the output without touching the disk.
```python
# The whole document as one PDF in memory, e.g. for an HTTP responseimportiofromgroupdocs.viewerimportViewerfromgroupdocs.viewer.optionsimportPdfViewOptionspdf=io.BytesIO()withViewer("input.docx")asviewer:viewer.view(PdfViewOptions(lambda:pdf))pdf_bytes=pdf.getvalue()``````python
# Write each page to an in-memory bufferimportiofromgroupdocs.viewerimportViewerfromgroupdocs.viewer.optionsimportPngViewOptionspage_buffers={}defcreate_page_stream(page_number):buf=io.BytesIO()page_buffers[page_number]=bufreturnbufwithViewer("input.docx")asviewer:viewer.view(PngViewOptions(create_page_stream))# page_buffers now holds {1: <BytesIO>, 2: <BytesIO>, ...}``````python
# Write HTML pages + resources with custom namingimportosfromgroupdocs.viewerimportViewerfromgroupdocs.viewer.optionsimportHtmlViewOptionsdefcreate_page(page_number):os.makedirs("out",exist_ok=True)returnopen("out/page_%d.html"%page_number,"wb")defcreate_resource(page_number,resource_name):returnopen("out/res_%d_%s"%(page_number,resource_name),"wb")defresource_url(page_number,resource_name):return"res_%d_%s"%(page_number,resource_name)withViewer("input.docx")asviewer:viewer.view(HtmlViewOptions.for_external_resources(create_page,create_resource,resource_url))```What a create function returns, and when its output is ready:
- **Return** a writable file (`open(..., "wb")`) or an empty `io.BytesIO()`.
- **When it is filled:** a `BytesIO` is filled as soon as Viewer finishes that page or file, so every buffer holds its output by the time `view()` returns, and stays open. A file is written through its own .NET handle and is complete when Viewer releases it. The file object you returned is closed for you once .NET has opened the file.
- **Resources:** `resource_name` is the resource's file name, e.g. `s1.css`.
Optional release functions:
- **Signatures:** `release_page_stream(page_number, stream)`, `release_file_stream(stream)`, `release_resource_stream(page_number, resource_name, stream)`.
- **How to pass them:** after the create functions: `PngViewOptions(create_page_stream, release_page_stream)`, `PdfViewOptions(create_file_stream, release_file_stream)`, `HtmlViewOptions.for_external_resources(create_page_stream, create_resource_stream, create_resource_url, release_page_stream, release_resource_stream)`.
- **What they get:** the object your create function returned, already complete.
The factory interfaces (`IPageStreamFactory`, `IFileStreamFactory`, `IResourceStreamFactory`) take an object with `create_page_stream` / `create_file_stream` / `create_resource_stream` (plus `create_resource_url` and the `release_*` methods), or a single create function. Concurrent renders in separate threads each get their own buffers.
## Save attachments
```python
fromgroupdocs.viewerimportViewerwithViewer("with_attachments.msg")asviewer:forattachmentinviewer.get_attachments():# Pass a filesystem path — the wrapper opens the file, writes,# and closes it. Parent directories are created as needed.viewer.save_attachment(attachment,"./out/"+attachment.file_name)# Equivalent stream form (explicit control over the sink):# import io# buf = io.BytesIO()# viewer.save_attachment(attachment, buf)# buf.getvalue() # attachment bytes```**Note**: the .NET engine's native `SaveAttachment` only exposes the
`(Attachment, Stream)` overload (still true in 26.10). The path-accepting form is a Python-
side convenience layered on top — it wraps the open/close for you.
## Font sources
`FontSettings.set_font_sources(...)` is the .NET
`params IFontSource[]` method and accepts any of these call shapes:
```python
importosfromgroupdocs.viewer.fontsimportFontSettings,FolderFontSource,SearchOptionforfolderin("fonts/primary","fonts/backup","fonts/extra"):os.makedirs(folder,exist_ok=True)# a font folder must existsrc1=FolderFontSource("fonts/primary",SearchOption.ALL_FOLDERS)src2=FolderFontSource("fonts/backup",SearchOption.TOP_FOLDER_ONLY)src3=FolderFontSource("fonts/extra",SearchOption.TOP_FOLDER_ONLY)FontSettings.set_font_sources(src1,src2)# varargsFontSettings.set_font_sources([src1,src2])# single listFontSettings.set_font_sources([src1],[src2])# multiple lists (flattened)FontSettings.set_font_sources([src1,src2],src3)# mixed — also flattenedFontSettings.reset_font_sources()# clear```All four shapes normalize to the same flat list before crossing the
bridge. Strings are never flattened (a string path is passed through
as-is, not exploded into characters).
## View documents in the browser (`groupdocs-viewer`)
The package installs a console command that serves a file or a folder to the
GroupDocs.Viewer web UI on this machine, using only the standard library:
```bash
groupdocs-viewer # the current foldergroupdocs-viewer path/to/folder -v # log each requestgroupdocs-viewer report.docx -t png # one file, rendered as PNG pagespython -m groupdocs.viewer --version
```Options: `path` (default: the current folder), `-p/--port` (default 8080, a free
port when it is busy, `0` for any), `-b/--bind` (default `127.0.0.1`),
`--allow-host NAME` (repeatable), `--no-open`, `-l/--license-path` (file or URL;
default `GROUPDOCS_LIC_PATH`), `-t/--viewer-type html|png|jpg` (default `html`),
`--cache-dir`, `-v/--verbose`.
What to know when you suggest it:
- It is for a person at this machine. The address it prints and opens carries a
session token (`/?token=...`); the page turns it into a cookie, and the API
answers only with that cookie. After a restart, or in another browser, open the
new printed address. It binds to `127.0.0.1`, answers only `localhost` names and
refuses cross-site requests; with `-b 0.0.0.0` other machines can connect, and
only the token keeps them out.
- Given a file, only that file is served. Given a folder, its subfolders are
browsable; hidden files (on Windows also files with the hidden or system
attribute) and links leading out of it are not. There is no upload.
- Rendered pages are cached per user and rendered again when a file changes.
- A licence that cannot be applied stops the command at startup (exit 1). With no
licence, pages render in evaluation mode.
- To embed the viewer in a FastAPI, Flask or Django application, with cloud
storage, a shared cache or authentication, use the `groupdocs-viewer-net-ui` package instead.
## Licensing
```python
fromgroupdocs.viewerimportLicense# From fileLicense().set_license("path/to/license.lic")# From streamwithopen("license.lic","rb")asf:License().set_license(f)```Or auto-apply: `export GROUPDOCS_LIC_PATH="path/to/license.lic"`. It is applied at the first Viewer call, not at import. If it cannot be applied (an expired subscription, a licence for another product, a missing file), every Viewer call raises `LicenseError` naming the variable and the engine's reason, until a licence is applied:
```python
fromgroupdocs.viewerimportLicense,LicenseError,Viewertry:viewer=Viewer("document.docx")exceptLicenseErrorase:print(e)# GROUPDOCS_LIC_PATH=... could not be applied: <reason>License().set_license("path/to/other.lic")# ends the refusalviewer=Viewer("document.docx")````GROUPDOCS_LIC_STRICT=0` turns the failure into one `LicenseWarning` and evaluation mode instead.
**Evaluation vs licensed.** Without a license the library still runs, but every rendered page carries an evaluation notice, and only the first two pages of a document are rendered: `get_view_info` reports at most two pages too (a 5-page DOCX or a 6-slide PPTX gives 2). Set `GROUPDOCS_LIC_PATH` (or call `License().set_license(...)`) and re-run to clear both. A 30-day full license is free: https://purchase.groupdocs.com/temporary-license
## API Reference
### Viewer
| Method | Returns | Description |
|---|---|---|
| `__init__(source, load_options=None, settings=None, leave_open=None)` | | `source` is a path, bytes, or stream |
| `view(options, cancellation_token=None, page_numbers=None)` | `None` | Render with `HtmlViewOptions` / `PngViewOptions` / `JpgViewOptions` / `PdfViewOptions`. `view(options, [1, 3])` renders pages 1 and 3; `cancellation_token`: see "Cancelling a long render" |
| `get_view_info(options)` | `ViewInfo` | Page count, size, layout info (use `ViewInfoOptions.for_html_view()` etc.) |
| `get_file_info()` | `FileInfo` | Format, name, encrypted flag without viewing |
| `get_attachments()` | `list[Attachment]` | Embedded attachments (emails, PDFs) |
| `save_attachment(attachment, destination)` | `None` | Extract one attachment. `destination` can be a filesystem path (`str` / `os.PathLike`) or a writable stream (`BytesIO` / `open(..., "wb")`). Paths: the wrapper opens the file, writes through, and closes it — parent dirs are auto-created. Streams: passed straight to the bridge; caller owns the lifetime. |
| `get_all_fonts()` | `list` | Fonts embedded in the document |
| `search(options)` | `None` | Search with `SearchHighlightOptions` |
### HtmlViewOptions
Accepts the factory methods `for_embedded_resources(...)` and `for_external_resources(...)`. Each factory takes either a format string (e.g. `"page_{0}.html"`) or callables for `CreatePageStream` / `CreateResourceStream` / `CreateResourceUrl`.
| Property | Type | Writable |
|---|---|---|
| `render_responsive` | `bool` | yes |
| `minify` | `bool` | yes |
| `render_to_single_page` | `bool` | yes |
| `for_printing` | `bool` | yes |
| `exclude_fonts` | `bool` | yes |
| `fonts_to_exclude` | `list[str]` | yes |
| `remove_java_script` | `bool` | yes |
| `image_width` / `image_height` | `int` | yes |
| `image_max_width` / `image_max_height` | `int` | yes |
| `watermark` | `Watermark` | yes (inherited from `ViewOptions`) |
| `render_comments` | `bool` | yes (inherited from `BaseViewOptions`) |
| `render_hidden_pages` | `bool` | yes (inherited from `BaseViewOptions`) |
| `render_notes` | `bool` | yes (inherited from `BaseViewOptions`) |
| `default_font_name` | `str` | yes (inherited from `BaseViewOptions`) |
| `*_options` (`archive_options`, `cad_options`, `email_options`, `outlook_options`, `pdf_options`, `presentation_options`, `project_management_options`, `spreadsheet_options`, `text_options`, `visio_rendering_options`, `web_document_options`, `word_processing_options`, `mail_storage_options`) | format-specific tweaks | yes |
Two HTML options are new in 26.11 (engine 26.10):
-`options.cad_options.enable_layered_rendering = True` groups each CAD layer's objects under an element whose `id` is the layer name, so a page can show and hide layers without rendering again.
-`options.pdf_options.fix_thai_marks = True` fixes stranded Thai marks when a PDF is rendered to HTML with embedded resources (`for_embedded_resources`). It can slow rendering down considerably.
### PngViewOptions / JpgViewOptions
Constructor takes `file_path_format` (e.g. `"page_{0}.png"`) OR a `CreatePageStream` callable.
| Property | Type | Writable |
|---|---|---|
| `width` / `height` | `int` | yes |
| `max_width` / `max_height` | `int` | yes |
| `quality` (JPG only) | `int` 1-100 | yes |
| `extract_text` | `bool` | yes |
| `watermark`, `render_comments`, `render_hidden_pages`, `render_notes`, `default_font_name`, and all `*_options` | | yes |
### PdfViewOptions
Constructor takes `output_file_path` (single PDF output) OR a `CreateFileStream` callable.
| Property | Type | Writable |
|---|---|---|
| `security` | `Security` | yes |
| `pdf_optimization_options` | `PdfOptimizationOptions` | yes |
| `image_width` / `image_height` | `int` | yes |
| `image_max_width` / `image_max_height` | `int` | yes |
| `watermark`, `render_comments`, `render_hidden_pages`, `render_notes`, `default_font_name`, and all `*_options` | | yes |
Also has `rotate_page(page_number, rotation)` — rotates a specific page in the output PDF. `rotation` is one of `Rotation.ON_90_DEGREE`, `ON_180_DEGREE`, `ON_270_DEGREE`.
### ViewInfoOptions
Factory methods: `for_html_view()`, `for_png_view()`, `for_jpg_view()`, `for_pdf_view()`.
| Property | Type | Writable |
|---|---|---|
| `width` / `height` | `int` | yes |
| `max_width` / `max_height` | `int` | yes |
| `extract_text` | `bool` | yes |
| Same `render_comments`, `render_hidden_pages`, `render_notes`, `default_font_name`, and `*_options` as `BaseViewOptions` | | yes |
### LoadOptions
Pass to `Viewer(source, load_options)` to control how the source document is parsed.
| Property | Type | Writable |
|---|---|---|
| `file_type` | `FileType` | yes |
| `password` | `str` | yes |
| `encoding` | `str` | yes |
| `detect_encoding` | `bool` | yes |
| `try_repair` | `bool` | yes |
| `resource_loading_timeout` | `timedelta` | yes |
| `skip_external_resources` | `bool` | yes |
| `whitelisted_resources` | `list[str]` | yes |
### Watermark
Construct with `Watermark(text)` then tweak appearance.
| Property | Type | Writable |
|---|---|---|
| `text` | `str` | yes |
| `color` | color (Argb32Color / KnownColors) | yes |
| `position` | `Position` | yes |
| `size` | `int` | yes |
| `font_name` | `str` | yes |
## FileType enum
Viewer exposes every file type it knows on a single flat `FileType` class — access via `FileType.DOCX`, `FileType.PDF`, etc. (case-insensitive). Members grouped by family:
<!-- begin:filetypes -->| Family | Members |
| :- | :- |
| Archives / Compression | `ZIP, TAR, XZ, TXZ, TARXZ, TGZ, TARGZ, BZ2, RAR, GZ, GZIP, SevenZip, CPIO, Zstandard, Tzst, TarZst, Iso, Lha, Cab` |
| CAD | `DXF, DWG, DWT, STL, IFC, DWF, FBX, DWFX, DGN, PLT, CF2, OBJ, HPG, IGS` |
| Diagrams (Visio) | `VSD, VSDX, VSS, VSSX, VSDM, VST, VSTX, VSTM, VSSM, VSX, VTX` |
| Word-processing | `DOC, DOCM, DOCX, DOT, DOTM, DOTX, RTF, ODT, OTT, TXT, FlatOpc` |
| Spreadsheets | `XLS, XLSX, XLSM, XLSB, ODS, OTS, XLT, XLTX, XLTM, CSV, TSV, DIF, SXC, FlatOpc, Numbers` |
| Presentations | `PPT, PPS, PPTX, PPSX, ODP, OTP, POTX, POT, POTM, PPTM, PPSM, FlatOpc` |
| PDF / Page Description | `PDF, PS, EPS, XPS, OXPS, TEX, PCL` |
| eBook | `EPUB, MOBI, AZW3, CHM` |
| Email | `MSG, EML, EMLX, VCF, MBOX, PST, OST, OLM, ICS` |
| Images | `JPG, JPEG, JFIF, PNG, BMP, DIB, TIFF, TIF, GIF, ICO, WebP, EMZ, WMZ, EMF, WMF, SVG, SVGZ, DCM, DICOM, CDR, CMX, DjVu, DNG, Jp2, J2C, J2K, JPX, JPF, JPM, JPC, JLS, TGA, HEIC, AVIF, PSD, PSB, AI, APNG` |
| Project Management | `MPP, MPT, MPX, XER` |
| Web / Markup | `HTML, HTM, MHT, MHTML, XML, JSON, CSS` |
| 3D | `Usd, Usdz, Obj, Ply, Gltf, Glb, ThreeDS, ThreeMF` |
| Fonts | `TTF, EOT, OTF, CFF, WOFF, WOFF2, Type1` |
| Source code / Text | `MD, LOG, AS, AS3, ASM, BAT, C, CC, CMAKE, CPP, CS, CXX, DIFF, ...` (the full list: `FileType.get_supported_file_types()` at runtime) |
<!-- end:filetypes -->Use `FileType.from_extension("docx")` when you don't know which family owns a format — it returns the correct `FileType` instance. `FileType.from_stream(stream)` sniffs file headers. `FileType.get_supported_file_types()` returns what the running engine can render — on Linux/macOS it omits PSD, PSB, AI and ONE (194 file types there, 198 on Windows, in 26.11) — so it is the reliable platform gate.
**Platform note:** Linux/macOS wheels run the cross-platform engine, which does **not** render **Photoshop** (`PSD, PSB`), **Adobe Illustrator** (`AI`) or **OneNote** (`ONE`) — those render only on Windows. Every other family works on every platform, including Visio and, since 26.9, Microsoft Project (`MPP, MPT, MPX`). The Python API is the same in every wheel, so `FileType.PSD`, `FileType.PSB`, `FileType.AI` and `FileType.ONE` exist everywhere — but on Linux/macOS touching one raises `GroupDocsViewerException: Member 'GroupDocs.Viewer.FileType.PSD' not found.` Gate on `FileType.get_supported_file_types()` instead.
## Key Patterns
- **Properties**: use `snake_case` -- auto-mapped to .NET `PascalCase`- **Context managers**: `with Viewer(...) as x:` ensures resources are released
- **Streams**: pass `open("file", "rb")` or `io.BytesIO(data)` where .NET expects Stream. A file object stays open and is read from its current position. A file opened for update (`"r+b"`) is not truncated, and `"ab"` appends.
- **Stream write-back**: `BytesIO` objects are updated after .NET writes to them
- **Enums**: case-insensitive, lazy-loaded (e.g., `FileType.DOCX`)
- **Collections**: every property whose declared return type is
`List[T]` comes back wrapped as a ``_NetListProxy`` — a thin layer
that gives you the full Python MutableSequence surface over the
underlying ``.NET List<T>``:
| Python op | .NET call |
|---|---|
| `coll.append(v)` | `Add(v)` |
| `coll.extend(it)` / `coll += it` | `AddRange(it)` |
| `coll.insert(i, v)` | `Insert(i, v)` |
| `coll.remove(v)` | `Remove(v)` |
| `coll.clear()` | `Clear()` |
| `coll.index(v)` | `IndexOf(v)` |
| `coll[i]`, `coll[-1]`, `coll[a:b]` | `get_Item(i)` + slice materialize |
| `coll[i] = v` | `set_Item(i, v)` |
| `del coll[i]`, `del coll[a:b]` | `RemoveAt(i)` (slices walk) |
| `coll.pop()` / `coll.pop(i)` | `get_Item(i)` + `RemoveAt(i)` |
| `v in coll` | `Contains(v)` (falls back to linear scan) |
| `coll.count(v)` | linear scan |
| `coll.reverse()` | `Reverse()` |
| `len(coll)` | `Count` property |
| `for v in coll` | `GetEnumerator` |
```python
from groupdocs.viewer.options import HtmlViewOptions, Tile
view_options = HtmlViewOptions.for_embedded_resources("page_{0}.html")
# view_options.cad_options.tiles is a List<Tile>.
tiles = view_options.cad_options.tiles
tiles.append(Tile(0, 0, 500, 500))
tiles.extend([Tile(100, 100, 200, 200)])
first = tiles[0]
last = tiles[-1]
popped = tiles.pop()
del tiles[0]
tiles += [Tile(1, 1, 10, 10), Tile(2, 2, 20, 20)]
tiles.reverse()
tiles.clear()
```
Slice assignment (``coll[a:b] = [...]``) is not yet supported —
use explicit ``del`` + ``insert`` for now.
- **Callbacks**:
- **Delegates:** Python functions work for the stream delegates `CreatePageStream`, `CreateResourceStream`, `CreateResourceUrl`, `CreateFileStream` and their `Release*` counterparts.
- **Factory interfaces:** they take Python objects.
- See [Render to custom streams](#render-to-custom-streams) above.
- **Factory methods**: `HtmlViewOptions.for_embedded_resources("path/page_{0}.html")` and `.for_external_resources(page_fmt, resource_fmt, url_fmt)` accept either string path templates OR callback factories. The dispatcher Python-side type-checks before calling into .NET, so positional strings route to the string overload without a bridge round-trip.
## Multiprocessing and web servers
The engine runs in your Python process on an embedded .NET runtime, and .NET does not survive `fork()`. Once a process has made its first GroupDocs call, a process forked from it cannot use GroupDocs.
**Safe:**- threads, with one `Viewer` per thread;
-`uvicorn --workers N`, and `gunicorn` without `--preload`: each worker imports the app itself;
-`multiprocessing.get_context("spawn")` or `"forkserver"` (the Linux default from Python 3.14), e.g. `ProcessPoolExecutor(mp_context=multiprocessing.get_context("spawn"))`;
- forking before the first GroupDocs call.
**Not safe**, once the parent has made a GroupDocs call:
- the `fork` start method (the Linux default before Python 3.14);
-`gunicorn --preload` with an app that calls GroupDocs while loading;
- Celery's prefork pool.
Such a child gets `RuntimeError: The .NET runtime cannot be used in a process forked after it started ...` at its first GroupDocs call, and the parent keeps working. Wheels up to 26.9.0 instead crashed the **parent** with a segmentation fault.
## Cancelling a long render
Pass a `CancellationTokenSource`'s `token` to `view()`, and cancel it from any thread, or after a delay. The call then raises `OperationCanceledError`:
```python
fromgroupdocs.viewerimportCancellationTokenSource,OperationCanceledError,Viewerfromgroupdocs.viewer.optionsimportHtmlViewOptionssource=CancellationTokenSource()source.cancel_after(30)# seconds; or source.cancel() from another threadtry:withViewer("large.xlsx")asviewer:viewer.view(HtmlViewOptions.for_embedded_resources("page_{0}.html"),cancellation_token=source.token)exceptOperationCanceledError:pass# the pages written so far stay; the next render works```- **Call shapes:** `view(options, cancellation_token=token)` or `view(options, token)` renders every page. With a page list, the token comes first, as in .NET: `view(options, token, [1, 2])`, or `view(options, page_numbers=[1, 2], cancellation_token=token)`. `cancellation_token=None` is the same as no token.
- **What the engine checks** (GroupDocs.Viewer for .NET 26.10, which this package wraps; measured from Python, and on 26.8 from C# too):
- **before rendering starts:** a cancel during a long load takes effect when the load ends;
- **between pages of an all-pages render to HTML, PNG or JPG:** it stops within 0.03 s;
- **nothing else:** a PDF render, and a render of an explicit page list (`view(options, token, [1, 2])`), run to the end once rendering has started.
- **To stop a long PDF render**, run it in a worker process and terminate the process on timeout. Use `multiprocessing.get_context("spawn")`; see "Multiprocessing and web servers" above.
## Platform Requirements
| Platform | Requirements |
|---|---|
| Windows | None |
| Linux (glibc 2.27+: Ubuntu 18.04+, Debian 10+, RHEL 8+) | `apt install libicu-dev fontconfig ttf-mscorefonts-installer` (Debian: enable `contrib`) — no `libgdiplus` |
| macOS 12+ (Intel, Apple Silicon) | None |
The wheel tags state these floors (`manylinux_2_27_x86_64`, `macosx_12_0_x86_64`, `macosx_12_0_arm64`), so pip 20.3+ refuses an older OS up front instead of installing a runtime that cannot start.
**Format support by platform:**| Format family | Windows | Linux / macOS |
|---|:---:|:---:|
| Photoshop (PSD, PSB) | Yes | No |
| Adobe Illustrator (AI) | Yes | No |
| OneNote (ONE) | Yes | No |
| All other formats (Office, PDF, Visio, Project, CAD, images, email, archives, eBooks, web, …) | Yes | Yes |
Linux/macOS wheels run the cross-platform build of the engine (`GroupDocs.Viewer.Net100`), and Windows wheels its Windows build (`GroupDocs.Viewer.Net100.Windows`). The cross-platform build renders every format except Photoshop (PSD, PSB), Adobe Illustrator (AI) and OneNote — those are Windows-only. Everything else works on every platform, including Visio and Microsoft Project (MPP, MPT, MPX).
## Troubleshooting
**`IncorrectPasswordException` / `PasswordRequiredException`** -- the document is encrypted. Pass `LoadOptions(password="...")` to `Viewer(...)`.
**`Cannot convert String to CreatePageStream`** (fixed in 26.4.0+) -- older wheels had a static-factory dispatcher that leaked .NET cast errors. Upgrade with `pip install --upgrade groupdocs-viewer-net`.
**`GroupDocsViewerException: Failed to detect file type`** when rendering a PSD, PSB, AI or ONE file on Linux/macOS -- those formats are Windows-only; the cross-platform engine does not include them. Render them on Windows.
**`DllNotFoundException: libgdiplus` / `Gdip` type initializer exception** -- not expected: since 26.9 no libgdiplus is needed on Linux or macOS. If it appears, install it (`sudo apt install libgdiplus` / `brew install mono-libgdiplus`) and report the document to support.
**`Cannot find fallback font 'Generic Sans Serif'`** when rendering an MPP/MPT/MPX file on Linux -- MS Project rendering needs the Microsoft core fonts: `sudo apt install ttf-mscorefonts-installer && sudo fc-cache -f` (Debian: enable `contrib`). Liberation fonts do not satisfy this lookup.
**Garbled text / missing fonts** -- install fonts: `sudo apt install ttf-mscorefonts-installer fontconfig && sudo fc-cache -f`**`DllNotFoundException: libSkiaSharp`** -- stale system copy conflicts with bundled version. Rename it: `sudo mv /usr/local/lib/libSkiaSharp.dylib /usr/local/lib/libSkiaSharp.dylib.bak`**The process exits with code 134 and `Couldn't find a valid ICU package`**, with no Python exception (Linux) -- ICU is missing. Install it: `sudo apt install libicu-dev`. Do NOT set `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT` instead.
**`RuntimeError: The .NET runtime cannot be used in a process forked after it started`**, or the parent process dying with a segmentation fault (up to 26.9.0) -- a worker was forked after the parent's first GroupDocs call. Use the `spawn` start method, start the workers before the first call, or drop `gunicorn --preload`. See [Multiprocessing and web servers](#multiprocessing-and-web-servers).
**`is not a supported wheel on this platform` / `No matching distribution found for groupdocs-viewer-net` / pip installs a version older than 26.9** -- the OS is older than glibc 2.27 / macOS 12, or pip is older than 20.3 (`python -m pip install --upgrade pip`). Versions up to 26.5 were tagged for older systems, so an unpinned install falls back to them, and they fail at first use there. On an Intel Mac, a Python built against an old SDK reports macOS 10.16: use pip 24.1+ or `SYSTEM_VERSION_COMPAT=0 pip install groupdocs-viewer-net`.
**Page images (PNG, JPG) of a spreadsheet lose the spaces between words and clip digits at cell edges** (Linux) -- a known issue of engine 26.10. Render spreadsheets to PDF or HTML on Linux.
**A workbook rendered twice with the same `Viewer` has more pages the second time** -- a known engine issue. Create a new `Viewer` for each render.
**The process dies while rendering a presentation whose fonts are not installed** (Linux) -- it happens when Debian's `fonts-noto-extra` is installed. Set `default_font_name` on the view options to an installed font, or remove `fonts-noto-extra`.
**`TypeLoadException`** -- reinstall: `pip install --force-reinstall groupdocs-viewer-net`**Still stuck?** Post your question at https://forum.groupdocs.com/c/viewer/ -- the development team responds directly.