Thumbnails for Long PDFs: Do the Pixel and Memory Math First
generates thumbnails in batch for a 200-page engineering drawing PDF; the script is killed by the system due to OOM when it reaches page 30. This is a typical i
If you generate thumbnails in batch for a 200-page engineering drawing PDF, your script may be killed by the system when it reaches page 30. This out-of-memory (OOM) error is a common problem for developers handling long documents for the first time. It often appears only after many pages have been processed.
The problem usually comes from underestimating how much memory rasterization needs, not from a defect in the library. A single A3 page rendered as an RGB image at 150 DPI needs about 35 MB for its raw pixel data. If the previous Pixmap is not released inside the loop, or the alpha channel is enabled by accident, peak memory can exceed 1 GB within seconds. A faster machine will not fix this. You need to calculate the resource budget for each page before you run the code.
You will learn how to convert page dimensions into pixel counts and byte sizes, which input limits to enforce, and a PyMuPDF approach that keeps memory use predictable. You will also get acceptance criteria for deciding when results need a manual check.
How do you generate thumbnails from a long PDF without running out of memory? The short answer
Calculate the memory budget for each page before you render it, render without the alpha channel, release each Pixmap promptly, and check the output against clear acceptance criteria.
| Your situation | What to do | Why |
|---|---|---|
| Thumbnails for a preview with no transparent overlay | Set alpha=False when rendering | An RGB frame uses 3 bytes per pixel, while RGBA uses 4 bytes |
| Rendering a batch of pages in a loop | Release each Pixmap reference right after rendering | Old buffers left for the garbage collector can push resident memory well above the theoretical value |
| Input DPI or page size is unusual | Validate DPI and page dimensions before rendering | An extremely large DPI can consume hundreds of MB for one page |
| Pages are rotated 90 degrees | Get the rotated rectangle before computing pixel size | Using the original width and height causes cropping or stretching |
| Memory is close to the limit | Lower the DPI and retry once, then send persistent failures to manual review | Automatic degradation handles most cases, and manual judgement covers the rest |
Converting page size into pixels and bytes
Before you call any rendering API, map physical dimensions to byte counts. Page sizes are measured in points, where 1 point equals 1/72 inch.
Pixel dimensions
- Pixel width:
int(page_width_pt / 72 * dpi) - Pixel height:
int(page_height_pt / 72 * dpi) - Example: standard A4 paper (595×842 points) rendered at 144 DPI gives an image of 1190×1684 pixels.
Memory per frame
Memory depends on the total number of pixels and the bytes per pixel:
- RGB uses 3 bytes per pixel.
- RGBA uses 4 bytes per pixel.
- For the A4 example above, an RGB frame is about 6.0 MB (1190×1684×3).
- Enabling the alpha channel raises this to about 8.0 MB, a 33% increase.
For thumbnail previews, keep the alpha channel disabled unless you need a transparent background overlay.
Although this arithmetic is simple, actual resident memory can be several times the theoretical value during batch loops. This happens when the buffer from the previous frame is not cleared promptly by the garbage collector.
Input limits and expected behaviour
To test the memory control logic, use controlled synthetic inputs rather than files you cannot reproduce. A valid input includes a virtual page of known dimensions, explicit DPI, and a flag that disables alpha. For example, a square 100×100 point page rendered at 72 DPI as RGB should produce a buffer of 100×100 pixels, or 30000 bytes.
Common input errors
- Zero or negative DPI. Some libraries throw an exception, but this is easy to catch.
- Very large DPI with no upper bound. A value such as 1200 can use hundreds of megabytes for a single page and leave too little memory for later pages. This is the more dangerous case.
- Rotated pages. If you calculate the buffer from the original width and height, the output is cropped or stretched.
Validation rules
Add these checks before rendering:
- DPI must be greater than 0 and below a predefined threshold (for example, 300).
- Page dimensions must not exceed reasonable limits (for example, A0).
- Rotated pages must use the actual rectangle after rotation.
These thresholds are not industry standards. They are engineering constraints based on the memory available in your runtime environment.
A secure PyMuPDF rendering approach
The following example shows how to generate thumbnails safely in a memory-constrained environment. It uses the PyMuPDF library (install pymupdf>=1.24.0) and performs all operations in memory, without relying on external files.
This example is a synthetic scenario built for instruction. Run and verify it in your own locked-dependency environment.
import pymupdf
def generate_thumbnail_safe(doc_bytes: bytes, dpi: int = 144) -> bytes:
"""安全生成首页缩略图,含资源预算校验"""
assert 0 < dpi <= 300, "DPI must be in (0, 300]"
doc = pymupdf.open(stream=doc_bytes, filetype="pdf")
try:
page = doc[0]
rect = page.rect
# 计算旋转后实际尺寸
if page.rotation in (90, 270):
width_px = int(rect.height * dpi / 72)
height_px = int(rect.width * dpi / 72)
else:
width_px = int(rect.width * dpi / 72)
height_px = int(rect.height * dpi / 72)
# 内存预算检查(假设最大允许50MB)
mem_estimate = width_px * height_px * 3
assert mem_estimate < 50 * 1024 * 1024, f"Estimated {mem_estimate}B exceeds limit"
pix = page.get_pixmap(dpi=dpi, alpha=False)
thumbnail_bytes = pix.tobytes("png")
pix = None # 显式释放
return thumbnail_bytes
finally:
doc.close()
# 合成测试:创建100x100点空白PDF
blank_pdf = pymupdf.open()
page = blank_pdf.new_page(width=100, height=100)
blank_bytes = blank_pdf.tobytes()
blank_pdf.close()
result = generate_thumbnail_safe(blank_bytes, dpi=72)
assert len(result) > 0, "Thumbnail generation failed"
The key points in the code are:
alpha=Falseavoids the unnecessary channel.- Pixel dimensions are recalculated from the rotation state.
- Memory use is estimated before rendering, with a hard upper limit.
- The Pixmap reference is cleared immediately after rendering.
These measures cannot guarantee that overflows never happen, but they keep the risk within a predictable range.
Acceptance criteria and manual review
Code that runs is not necessarily ready for production. The table below lists the acceptance criteria and edge cases to watch during deployment. It separates what automation can cover from what needs a person.
| Observation | Automated handling | Manual review trigger |
|---|---|---|
| Thumbnail is entirely black or entirely white | Checks that the Pixmap is not null and that its variance is above a threshold | Three consecutive anomalous pages, or an anomaly on the first or last page |
| Rendering time suddenly spikes | Records single-page time and raises an alarm when it exceeds twice the mean | A single page takes more than 5 seconds, or total duration exceeds the expected value by 30% |
| Memory peak is close to the limit | Lowers the DPI and retries once | Failure persists after degradation, or image quality is unacceptable |
| Page content is missing | Compares the number of text blocks with the metadata | A key section's thumbnail is blank or misaligned |
| Imbalance in rotated pages | Checks aspect ratio against the source file | Deformation in engineering drawings or tabular documents |
This table covers resource control at the code-demo level only. End-to-end performance validation must also account for factors such as colour accuracy and font-embedding integrity. Encrypted PDFs, corrupted files, and pages with complex vector graphics can make automated scripts fail silently. In those cases, decide manually whether to skip the page or handle it specially.
References and next steps
Start by checking the memory estimation logic in your own environment with the synthetic examples above. Then test edge cases with real long documents. If a particular page type repeatedly triggers exceptions, record its structural features, such as the number of nested layers and font types, to guide later optimisation. Do not assume generic parameters suit every document. Resource budgeting is always an engineering decision for your specific scenario.
Translating documents with a checklist
Before you translate, confirm that the page order, source locations, and text integrity are correct. Then submit the same sample to the translation process. After translation, check that headings, body text, and figure captions still correspond correctly. Do not rely only on whether the text reads smoothly.
OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation.
📊 At a glance
Comparing RGB and RGBA for one A4 page rendered at 144 DPI (1190×1684 pixels):
| Mode | Bytes per pixel | Uncompressed size per frame | When to use it |
|---|---|---|---|
| RGB | 3 | about 6.0 MB | Thumbnail previews without a transparent overlay |
| RGBA | 4 | about 8.0 MB | Only when a transparent background overlay is required |
🎯 Which approach fits you?
If you are building thumbnails for a preview
Disable the alpha channel, render in RGB, and release each Pixmap right after use.
If you are processing a long engineering drawing set
Estimate memory for each page before rendering, cap the DPI, and send persistent failures to manual review.
If you are translating a document
Check page order and text integrity first, then translate a real sample and verify headings, body text, and captions.
❓ FAQ
1. Why does my script run out of memory after many pages?
Each rendered page can use a large amount of memory, and buffers from earlier pages may not be released in time. Releasing each Pixmap right after use and estimating memory before rendering keeps peak use predictable.
2. Should I keep the alpha channel for thumbnails?
Only if you need a transparent background overlay. Otherwise, disable it, because RGBA uses 4 bytes per pixel instead of 3.
3. How do I handle rotated pages?
Get the actual rectangle after rotation and compute pixel dimensions from it. Using the original width and height can crop or stretch the output.
4. What DPI should I use?
The article's thresholds (such as a maximum of 300 DPI) are engineering constraints, not industry standards. Set limits based on the memory available in your runtime environment.
5. When should a person check the output?
When a key section's thumbnail is blank or misaligned, when a page keeps failing after the DPI is lowered, or when engineering drawings or tables look deformed.
📝 Summary
Measure the memory cost of each page before you render it, keep the alpha channel off for previews, and release each Pixmap promptly. Use the acceptance criteria to decide when a person needs to review the results.
Try it now: upload a document and get it translated with the layout intact


