Skip to content

fix: enable N-up printing in preview via paintRequested - #457

Open
pengfeixx wants to merge 1 commit into
linuxdeepin:masterfrom
pengfeixx:fix/nup-printing-paintrequested
Open

pengfeixx wants to merge 1 commit into
linuxdeepin:masterfrom
pengfeixx:fix/nup-printing-paintrequested

Conversation

@pengfeixx

@pengfeixx pengfeixx commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

说明 / Summary

打印预览改走 paintRequested 路径,恢复并列(N-up)打印能力:

  1. 移除 PDF/DOCX 打印的 setPrintFromPath —— DTK 在按路径打印时会禁用并列打印及方向、缩放、边距、水印等设置项
  2. 全格式按打印机 DPI 渲染并设 300 DPI 下限,保证 paintRequested 路径的打印清晰度
  3. 按文档页数分级限制渲染 DPI 上限,避免整页范围高分辨率位图同时驻留内存导致耗尽

Switch print preview to the paintRequested path so N-up printing and orientation/scale/margin/watermark settings work for PDF and DOCX documents.

测试建议 / Test

  1. 打开 PDF/DOCX 进入打印预览,勾选并列打印并选择每张 2/4/6/9/16 页,验证拼版预览与实际输出
  2. 单页范围打印 PDF 验证 300 DPI 位图输出文字清晰度
  3. 打印 200 页以上大文档,观察内存占用稳定、无 OOM

Summary by Sourcery

Route document print previews through application-rendered pages so N-up and other print settings work while maintaining clear output and stable memory usage.

New Features:

  • Restore N-up printing and related layout options for PDF and DOCX documents through the print preview workflow.

Bug Fixes:

  • Improve print-preview output clarity by rendering pages at an appropriate minimum resolution across supported document formats.

Enhancements:

  • Limit rendering resolution for large documents to reduce memory consumption during asynchronous printing.

@sourcery-ai

sourcery-ai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Render every document format through the high-DPI application path, with a 300-DPI floor and page-count-based ceilings to balance print clarity against memory use.

  • reader/uiframe/DocSheet.cpp L53-60, L621-641, L1111-1118 (+3 small edits)

Remove file-path printing so the preview uses paintRequested and DTK can apply N-up and other print settings.

  • reader/uiframe/DocSheet.cpp L2069-2073

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 6 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="reader/uiframe/DocSheet.cpp" line_range="628-637" />
<code_context>
+    }
+
+    //大文档限制渲染 DPI 上限,防止打印时整册高分辨率位图同时驻留内存
+    const int totalPages = m_renderer ? m_renderer->getPageCount() : 0;
+    int dpiCeiling = kFallbackPrintDpi;
+    if (totalPages > kHugePrintDocPageCount) {
+        dpiCeiling = kHugePrintDocDpiCeiling;
+    } else if (totalPages > kLargePrintDocPageCount) {
+        dpiCeiling = kLargePrintDocDpiCeiling;
+    }
+    if (printerDpi > dpiCeiling) {
+        qCWarning(appLog) << "Total pages" << totalPages << "exceeds tier, limit print DPI from" << printerDpi << "to" << dpiCeiling;
+        printerDpi = dpiCeiling;
     }

</code_context>
<issue_to_address>
**Large print jobs exhaust memory**

When DTK retains rendered bitmaps for every page in a large selected range, `calculatePrintTargetSize` caps DPI using the document's total page count, while `onPrintRequested` renders every selected page and DTK retains the range's bitmaps; aggregate memory still grows with the range and can exhaust the process, including for a 201-page A4 job at 150 DPI. Use the selected range to bound aggregate bitmap memory, rather than relying only on per-page DPI tiers.

Calculate the DPI ceiling from the selected page range and a total bitmap-memory budget, or otherwise bound the number of retained page bitmaps.

Also at `reader/uiframe/DocSheet.cpp:59`.
</issue_to_address>

### Comment 2
<location path="reader/uiframe/DocSheet.cpp" line_range="1117" />
<code_context>
-            }
-
-            if (requestedSize.isValid()) {
-                image = loading.getImageForPrint(this, zeroBasedIndex, requestedSize);
+        //优先按打印机 DPI 渲染高清晰度位图(并列打印等设置走 paintRequested 路径,需保证打印清晰度)
+        const int zeroBasedIndex = pageRange[i] - 1;
</code_context>
<issue_to_address>
**Concurrent rendering races**

When a print render overlaps a viewer render or another print render for the same document, `getImageForPrint` invokes `DocSheet::getImage` on a new thread while `PageRenderThread` can render the same shared page for the viewer, and separate preview callbacks can start more print threads. `SheetRenderer::getImage` has no serialization around `Page::render`, so overlapping renders can race in the document backend and produce corrupted output or a crash.

Serialize access to page rendering, for example by routing print renders through the existing render thread or protecting backend page renders with a shared per-document lock.
</issue_to_address>

### Comment 3
<location path="reader/uiframe/DocSheet.cpp" line_range="604" />
<code_context>
 QSize DocSheet::calculatePrintTargetSize(int pageIndex, const QPrinter &printer, const QRectF &pageRect) const
 {
+    // XPS 页面逻辑尺寸按 96 DPI 计,PDF/DOCX/DjVu 等按印刷点(72 DPI)计
+    double logicalDpi = kPointLogicalDpi;
 #ifdef XPS_SUPPORT_ENABLED
-    if (m_fileType != Dr::XPS) {
</code_context>
<issue_to_address>
**Some formats allocate oversized bitmaps**

When printing a DjVu or OFD document, `calculatePrintTargetSize` treats DjVu pixel dimensions and OFD dimensions derived from document resolution as points, so it requests inflated bitmaps that waste memory; if rendering or allocation fails, the fallback prints at lower view-based resolution.

Use the appropriate format-specific logical DPI or source resolution when converting DjVu and OFD page dimensions.
</issue_to_address>

### Comment 4
<location path="reader/uiframe/DocSheet.cpp" line_range="1117" />
<code_context>
-            }
-
-            if (requestedSize.isValid()) {
-                image = loading.getImageForPrint(this, zeroBasedIndex, requestedSize);
+        //优先按打印机 DPI 渲染高清晰度位图(并列打印等设置走 paintRequested 路径,需保证打印清晰度)
+        const int zeroBasedIndex = pageRange[i] - 1;
</code_context>
<issue_to_address>
**Window re-enabled during printing**

When two print-preview callbacks overlap for the same main window, each overlapping `onPrintRequested` callback creates a `LoadingWidget` for the same main window. When the first callback finishes, `LoadingWidget::~LoadingWidget` enables that window even though the other callback is still rendering, so the user can interact with the document while printing remains in progress.

Track the number of active loading operations or restore the parent’s prior enabled state only after the final operation finishes.
</issue_to_address>

### Comment 5
<location path="reader/uiframe/DocSheet.cpp" line_range="641" />
<code_context>
-    double widthPixels = logicalSize.width() / kXpsLogicalDpi * static_cast<double>(printerDpi);
-    double heightPixels = logicalSize.height() / kXpsLogicalDpi * static_cast<double>(printerDpi);
+    double widthPixels = logicalSize.width() / logicalDpi * static_cast<double>(printerDpi);
+    double heightPixels = logicalSize.height() / logicalDpi * static_cast<double>(printerDpi);

     if (widthPixels <= 0.0 || heightPixels <= 0.0) {
</code_context>
<issue_to_address>
**Print preview output remains blurry**

When the preview printer reports 72 DPI and `pageRect` is expressed in its device pixels, `calculatePrintTargetSize` raises `printerDpi` to 300 but then scales the requested image down to the 72-DPI `pageRect`; `getImageForPrint` therefore renders a low-resolution bitmap that `onPrintRequested` stretches across the page, leaving preview and print output blurry.

Calculate the requested bitmap size independently of the preview printer's device-pixel `pageRect`, or convert that rectangle to the intended print resolution before fitting.

Also at `reader/uiframe/DocSheet.cpp:621-625`, `reader/uiframe/DocSheet.cpp:1113`.
</issue_to_address>

### Comment 6
<location path="reader/uiframe/DocSheet.cpp" line_range="629" />
<code_context>
+
+    //大文档限制渲染 DPI 上限,防止打印时整册高分辨率位图同时驻留内存
+    const int totalPages = m_renderer ? m_renderer->getPageCount() : 0;
+    int dpiCeiling = kFallbackPrintDpi;
+    if (totalPages > kHugePrintDocPageCount) {
+        dpiCeiling = kHugePrintDocDpiCeiling;
</code_context>
<issue_to_address>
**Small documents lose high-resolution detail**

When the document has at most 50 pages and the printer resolution exceeds 300 DPI, `dpiCeiling` defaults to `kFallbackPrintDpi` and `calculatePrintTargetSize` clamps `printerDpi` to that ceiling even for small documents, so high-resolution printers receive 300-DPI bitmaps and output loses detail.

Apply DPI ceilings only to the large-document tiers and leave the printer DPI uncapped for small documents.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment on lines +628 to +637
const int totalPages = m_renderer ? m_renderer->getPageCount() : 0;
int dpiCeiling = kFallbackPrintDpi;
if (totalPages > kHugePrintDocPageCount) {
dpiCeiling = kHugePrintDocDpiCeiling;
} else if (totalPages > kLargePrintDocPageCount) {
dpiCeiling = kLargePrintDocDpiCeiling;
}
if (printerDpi > dpiCeiling) {
qCWarning(appLog) << "Total pages" << totalPages << "exceeds tier, limit print DPI from" << printerDpi << "to" << dpiCeiling;
printerDpi = dpiCeiling;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Large print jobs exhaust memory

When DTK retains rendered bitmaps for every page in a large selected range, calculatePrintTargetSize caps DPI using the document's total page count, while onPrintRequested renders every selected page and DTK retains the range's bitmaps; aggregate memory still grows with the range and can exhaust the process, including for a 201-page A4 job at 150 DPI. Use the selected range to bound aggregate bitmap memory, rather than relying only on per-page DPI tiers.

Calculate the DPI ceiling from the selected page range and a total bitmap-memory budget, or otherwise bound the number of retained page bitmaps.

Also at reader/uiframe/DocSheet.cpp:59.

Prompt for AI agents
In `reader/uiframe/DocSheet.cpp` at lines 628-637:

**Large print jobs exhaust memory**

When DTK retains rendered bitmaps for every page in a large selected range, `calculatePrintTargetSize` caps DPI using the document's total page count, while `onPrintRequested` renders every selected page and DTK retains the range's bitmaps; aggregate memory still grows with the range and can exhaust the process, including for a 201-page A4 job at 150 DPI. Use the selected range to bound aggregate bitmap memory, rather than relying only on per-page DPI tiers.

Calculate the DPI ceiling from the selected page range and a total bitmap-memory budget, or otherwise bound the number of retained page bitmaps.

Also at `reader/uiframe/DocSheet.cpp:59`.

if (!requestedSize.isValid()) {
qCWarning(appLog) << "Falling back to view-based print size for page" << zeroBasedIndex;
} else {
image = loading.getImageForPrint(this, zeroBasedIndex, requestedSize);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Concurrent rendering races

When a print render overlaps a viewer render or another print render for the same document, getImageForPrint invokes DocSheet::getImage on a new thread while PageRenderThread can render the same shared page for the viewer, and separate preview callbacks can start more print threads. SheetRenderer::getImage has no serialization around Page::render, so overlapping renders can race in the document backend and produce corrupted output or a crash.

Serialize access to page rendering, for example by routing print renders through the existing render thread or protecting backend page renders with a shared per-document lock.

Prompt for AI agents
In `reader/uiframe/DocSheet.cpp` at line 1117:

**Concurrent rendering races**

When a print render overlaps a viewer render or another print render for the same document, `getImageForPrint` invokes `DocSheet::getImage` on a new thread while `PageRenderThread` can render the same shared page for the viewer, and separate preview callbacks can start more print threads. `SheetRenderer::getImage` has no serialization around `Page::render`, so overlapping renders can race in the document backend and produce corrupted output or a crash.

Serialize access to page rendering, for example by routing print renders through the existing render thread or protecting backend page renders with a shared per-document lock.

QSize DocSheet::calculatePrintTargetSize(int pageIndex, const QPrinter &printer, const QRectF &pageRect) const
{
// XPS 页面逻辑尺寸按 96 DPI 计,PDF/DOCX/DjVu 等按印刷点(72 DPI)计
double logicalDpi = kPointLogicalDpi;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Some formats allocate oversized bitmaps

When printing a DjVu or OFD document, calculatePrintTargetSize treats DjVu pixel dimensions and OFD dimensions derived from document resolution as points, so it requests inflated bitmaps that waste memory; if rendering or allocation fails, the fallback prints at lower view-based resolution.

Use the appropriate format-specific logical DPI or source resolution when converting DjVu and OFD page dimensions.

Prompt for AI agents
In `reader/uiframe/DocSheet.cpp` at line 604:

**Some formats allocate oversized bitmaps**

When printing a DjVu or OFD document, `calculatePrintTargetSize` treats DjVu pixel dimensions and OFD dimensions derived from document resolution as points, so it requests inflated bitmaps that waste memory; if rendering or allocation fails, the fallback prints at lower view-based resolution.

Use the appropriate format-specific logical DPI or source resolution when converting DjVu and OFD page dimensions.

if (!requestedSize.isValid()) {
qCWarning(appLog) << "Falling back to view-based print size for page" << zeroBasedIndex;
} else {
image = loading.getImageForPrint(this, zeroBasedIndex, requestedSize);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Window re-enabled during printing

When two print-preview callbacks overlap for the same main window, each overlapping onPrintRequested callback creates a LoadingWidget for the same main window. When the first callback finishes, LoadingWidget::~LoadingWidget enables that window even though the other callback is still rendering, so the user can interact with the document while printing remains in progress.

Track the number of active loading operations or restore the parent’s prior enabled state only after the final operation finishes.

Prompt for AI agents
In `reader/uiframe/DocSheet.cpp` at line 1117:

**Window re-enabled during printing**

When two print-preview callbacks overlap for the same main window, each overlapping `onPrintRequested` callback creates a `LoadingWidget` for the same main window. When the first callback finishes, `LoadingWidget::~LoadingWidget` enables that window even though the other callback is still rendering, so the user can interact with the document while printing remains in progress.

Track the number of active loading operations or restore the parent’s prior enabled state only after the final operation finishes.

double widthPixels = logicalSize.width() / kXpsLogicalDpi * static_cast<double>(printerDpi);
double heightPixels = logicalSize.height() / kXpsLogicalDpi * static_cast<double>(printerDpi);
double widthPixels = logicalSize.width() / logicalDpi * static_cast<double>(printerDpi);
double heightPixels = logicalSize.height() / logicalDpi * static_cast<double>(printerDpi);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Print preview output remains blurry

When the preview printer reports 72 DPI and pageRect is expressed in its device pixels, calculatePrintTargetSize raises printerDpi to 300 but then scales the requested image down to the 72-DPI pageRect; getImageForPrint therefore renders a low-resolution bitmap that onPrintRequested stretches across the page, leaving preview and print output blurry.

Calculate the requested bitmap size independently of the preview printer's device-pixel pageRect, or convert that rectangle to the intended print resolution before fitting.

Also at reader/uiframe/DocSheet.cpp:621-625, reader/uiframe/DocSheet.cpp:1113.

Prompt for AI agents
In `reader/uiframe/DocSheet.cpp` at line 641:

**Print preview output remains blurry**

When the preview printer reports 72 DPI and `pageRect` is expressed in its device pixels, `calculatePrintTargetSize` raises `printerDpi` to 300 but then scales the requested image down to the 72-DPI `pageRect`; `getImageForPrint` therefore renders a low-resolution bitmap that `onPrintRequested` stretches across the page, leaving preview and print output blurry.

Calculate the requested bitmap size independently of the preview printer's device-pixel `pageRect`, or convert that rectangle to the intended print resolution before fitting.

Also at `reader/uiframe/DocSheet.cpp:621-625`, `reader/uiframe/DocSheet.cpp:1113`.


//大文档限制渲染 DPI 上限,防止打印时整册高分辨率位图同时驻留内存
const int totalPages = m_renderer ? m_renderer->getPageCount() : 0;
int dpiCeiling = kFallbackPrintDpi;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Small documents lose high-resolution detail

When the document has at most 50 pages and the printer resolution exceeds 300 DPI, dpiCeiling defaults to kFallbackPrintDpi and calculatePrintTargetSize clamps printerDpi to that ceiling even for small documents, so high-resolution printers receive 300-DPI bitmaps and output loses detail.

Apply DPI ceilings only to the large-document tiers and leave the printer DPI uncapped for small documents.

Prompt for AI agents
In `reader/uiframe/DocSheet.cpp` at line 629:

**Small documents lose high-resolution detail**

When the document has at most 50 pages and the printer resolution exceeds 300 DPI, `dpiCeiling` defaults to `kFallbackPrintDpi` and `calculatePrintTargetSize` clamps `printerDpi` to that ceiling even for small documents, so high-resolution printers receive 300-DPI bitmaps and output loses detail.

Apply DPI ceilings only to the large-document tiers and leave the printer DPI uncapped for small documents.

1. Remove setPrintFromPath for PDF/DOCX printing, as DTK disables
   N-up printing and other settings when printing from a file path
2. Render all formats at printer DPI with a 300 DPI floor to keep
   print sharpness on the paintRequested path
3. Cap print DPI by page-count tiers to avoid holding the whole
   page range as high-resolution bitmaps in memory

Influence:
1. Open a PDF/DOCX in print preview, enable N-up printing with
   2/4/6/9/16 pages per sheet and check the composed output
2. Print a small PDF page range and verify text sharpness (300 DPI)
3. Print a large document (200+ pages) and check memory stays stable

fix: 打印预览改走 paintRequested 以支持并列打印

1. 移除 PDF/DOCX 打印的 setPrintFromPath,DTK 在按路径打印时会
   禁用并列打印及方向、缩放、边距、水印等设置项
2. 全格式按打印机 DPI 渲染并设 300 DPI 下限,保证 paintRequested
   路径的打印清晰度
3. 按文档页数分级限制渲染 DPI 上限,避免整页范围高分辨率位图
   同时驻留内存导致耗尽

Influence:
1. 打开 PDF/DOCX 进入打印预览,勾选并列打印并选择每张 2/4/6/9/16
   页,验证拼版预览与实际输出
2. 单页范围打印 PDF 验证 300 DPI 位图输出文字清晰度
3. 打印 200 页以上大文档,观察内存占用稳定、无 OOM

Log: N-up printing and orientation/scale/margin/watermark settings are now available in print preview for PDF and DOCX documents
PMS: TASK-398545
@pengfeixx
pengfeixx force-pushed the fix/nup-printing-paintrequested branch from cf1e5e2 to a972e9f Compare November 24, 2026 08:34
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: lzwind, pengfeixx

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants