Skip to content

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

Merged
pengfeixx merged 1 commit into
linuxdeepin:release/eaglefrom
pengfeixx:fix/nup-printing-eagle
Nov 26, 2026
Merged

pengfeixx merged 1 commit into
linuxdeepin:release/eaglefrom
pengfeixx:fix/nup-printing-eagle

Conversation

@pengfeixx

@pengfeixx pengfeixx commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

同步 master 提交 9722c02 到 release/eagle 分支(cherry-pick + 手工适配)。

背景 / Background

打印预览中 PDF/DOCX 走 setPrintFromPath 时,DTK 会禁用并列打印(N-up)以及方向、缩放、边距、水印等设置项。本提交统一改走 paintRequested 由应用侧高 DPI 渲染页面,并列打印等设置方可生效。

改动 / Changes

  1. 移除 PDF/DOCX 打印的 setPrintFromPath(含 pdftocairo 转换按路径打印逻辑)
  2. 新增 calculatePrintTargetSize:全格式按打印机 DPI 渲染并设 300 DPI 下限,保证 paintRequested 路径的打印清晰度
  3. 按文档页数分级限制渲染 DPI 上限(>200 页 150 DPI、>50 页 200 DPI),避免整页范围高分辨率位图同时驻留内存导致耗尽
  4. 新增 LoadingWidget::getImageForPrint 打印专用取图接口(eagle 分支此前缺失,一并补齐)

与 master 版本的差异适配 / Adaptations for eagle

  • eagle 分支无分类日志(QLoggingCategory),qCDebug(appLog)/qCWarning(appLog) 改为 qDebug()/qWarning()
  • 保留 eagle 现有 render hints(HighQualityAntialiasing)
  • 补齐 eagle 缺失的 calculatePrintTargetSize / getImageForPrint 声明与实现

测试 / Testing

  • eagle 分支 Qt5/qmake 环境下 reader 子项目 DocSheet.cpp 编译通过
  • 打开 PDF/DOCX 进入打印预览,勾选并列打印并选择每张 2/4/6/9/16 页,验证拼版预览与实际输出
  • 单页范围打印 PDF 验证 300 DPI 位图输出文字清晰度
  • 打印 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

Summary by Sourcery

Route PDF and DOCX preview printing through high-resolution application rendering so layout controls remain available while maintaining print quality and memory safety.

New Features:

  • Enable N-up printing and other print layout options for PDF and DOCX documents in print preview through application-rendered pages.

Bug Fixes:

  • Improve PDF and DOCX print clarity by rendering pages at print-appropriate resolution instead of printing directly from file paths.

Enhancements:

  • Add adaptive print image sizing with DPI safeguards and document-size limits to balance output quality and memory usage.
  • Add a dedicated print image retrieval path with fallback rendering when high-resolution page generation is unavailable.

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
@sourcery-ai

sourcery-ai Bot commented Nov 26, 2026

Copy link
Copy Markdown

Reviewer's Guide

Uses of the API

Remove path-based printing and connect the preview's paintRequested signal so PDF/DOCX printing uses the application-rendered path and can honor N-up and other preview settings.

  • reader/uiframe/DocSheet.cpp L1439-1443

Implementation

Add print-size calculation and DPI limits, render print-requested pages at the calculated resolution with a view-based fallback, and add the dedicated synchronous print-image loader.

  • reader/uiframe/DocSheet.cpp L454-524, L866-903, L1511-1539 (+2 small edits)
  • reader/uiframe/DocSheet.h L818, L882-886

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 5 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="1527" />
<code_context>
+    QEventLoop loop;
+    const QSize requestSize = targetSize;
+    QThread *thread = QThread::create([=, &image]() {
+        image = doc->getImage(index, requestSize.width(), requestSize.height());
+    });
+    QObject::connect(thread, &QThread::finished, &loop, &QEventLoop::quit);
</code_context>
<issue_to_address>
**Closing a tab crashes printing**

When the user closes the document tab while `getImageForPrint` is waiting for its worker, the worker dereferences `doc` in `getImage` while the nested event loop is running; closing the tab can destroy the `DocSheet` and its renderer first, causing a use-after-free and a crash.

Keep the sheet and renderer alive until the worker finishes, or cancel and join the worker before destroying them.
</issue_to_address>

### Comment 2
<location path="reader/uiframe/DocSheet.cpp" line_range="485-487" />
<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;
+    }
</code_context>
<issue_to_address>
**Large print jobs exhaust memory**

When a sufficiently large document or page range is retained by the asynchronous preview path, the per-page DPI tiers do not bound aggregate bitmap memory, and N-up pages are sized against the full sheet rather than their smaller slots. Retaining the requested range therefore exhausts memory.

Bound total retained bitmap memory and size rendered pages to their actual print slots.

Also at `reader/uiframe/DocSheet.cpp:504-508`.
</issue_to_address>

### Comment 3
<location path="reader/uiframe/DocSheet.cpp" line_range="896" />
<code_context>
+
     for (int i = 0; i < pageRange.count(); ++i) {
         if (pageRange[i] > pageCount() || pageRange[i] > m_browser->pages().count())
             continue;

-        const QRectF boundingrect = m_browser->pages().at(pageRange[i] - 1)->boundingRect();   //文档页缩放后的原区域不受旋转影响
</code_context>
<issue_to_address>
**Failed pages shift printed output**

When a page cannot be rendered by either path and later pages remain in the requested range, `onPrintRequested` continues before calling `printer->newPage()`, so the next rendered page is drawn on the failed page’s sheet and the printed sequence shifts or overlaps.

Advance the printer page when rendering fails, before continuing.

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

### Comment 4
<location path="reader/uiframe/DocSheet.cpp" line_range="504-508" />
<code_context>
+    }
+
+    if (pageRect.width() > 0.0 && pageRect.height() > 0.0) {
+        const double scale = qMin(pageRect.width() / widthPixels, pageRect.height() / heightPixels);
+        if (scale < 1.0) {
+            widthPixels *= scale;
+            heightPixels *= scale;
+        }
+    }
+
</code_context>
<issue_to_address>
**Preview pages lose print sharpness**

When the preview printer reports 72 DPI and `pageRect` is measured at that device resolution, `calculatePrintTargetSize` raises the target to 300 DPI, but its scale calculation compares it with the smaller, unconverted `pageRect` and shrinks the bitmap back to screen resolution. `getImageForPrint` therefore supplies a low-resolution image and preview-driven output loses print detail.

Convert `pageRect` to the target DPI coordinate system before fitting the bitmap, or otherwise avoid scaling the 300-DPI target back to screen resolution.

Also at `reader/uiframe/DocSheet.cpp:477-480`.
</issue_to_address>

### Comment 5
<location path="reader/uiframe/DocSheet.cpp" line_range="459" />
<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>
**DjVu print resolution is miscalculated**

When a DjVu page’s native resolution is not 72 DPI, djVu page dimensions are stored in pixels at each page’s `m_resolution`, but `calculatePrintTargetSize` treats them as 72-DPI points. The rendered bitmap therefore has the wrong pixel dimensions for the printer, so DjVu pages print at an unintended resolution and can be blurry or unnecessarily large.

Use each DjVu page’s stored DPI when converting its pixel dimensions to the requested print bitmap size.
</issue_to_address>

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

QEventLoop loop;
const QSize requestSize = targetSize;
QThread *thread = QThread::create([=, &image]() {
image = doc->getImage(index, requestSize.width(), requestSize.height());

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 · Closing a tab crashes printing

When the user closes the document tab while getImageForPrint is waiting for its worker, the worker dereferences doc in getImage while the nested event loop is running; closing the tab can destroy the DocSheet and its renderer first, causing a use-after-free and a crash.

Keep the sheet and renderer alive until the worker finishes, or cancel and join the worker before destroying them.

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

**Closing a tab crashes printing**

When the user closes the document tab while `getImageForPrint` is waiting for its worker, the worker dereferences `doc` in `getImage` while the nested event loop is running; closing the tab can destroy the `DocSheet` and its renderer first, causing a use-after-free and a crash.

Keep the sheet and renderer alive until the worker finishes, or cancel and join the worker before destroying them.

Comment on lines +485 to +487
if (totalPages > kHugePrintDocPageCount) {
dpiCeiling = kHugePrintDocDpiCeiling;
} else if (totalPages > kLargePrintDocPageCount) {

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 a sufficiently large document or page range is retained by the asynchronous preview path, the per-page DPI tiers do not bound aggregate bitmap memory, and N-up pages are sized against the full sheet rather than their smaller slots. Retaining the requested range therefore exhausts memory.

Bound total retained bitmap memory and size rendered pages to their actual print slots.

Also at reader/uiframe/DocSheet.cpp:504-508.

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

**Large print jobs exhaust memory**

When a sufficiently large document or page range is retained by the asynchronous preview path, the per-page DPI tiers do not bound aggregate bitmap memory, and N-up pages are sized against the full sheet rather than their smaller slots. Retaining the requested range therefore exhausts memory.

Bound total retained bitmap memory and size rendered pages to their actual print slots.

Also at `reader/uiframe/DocSheet.cpp:504-508`.


if (image.isNull()) {
qWarning() << "Failed to render image for printing page" << pageRange[i];
continue;

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 · Failed pages shift printed output

When a page cannot be rendered by either path and later pages remain in the requested range, onPrintRequested continues before calling printer->newPage(), so the next rendered page is drawn on the failed page’s sheet and the printed sequence shifts or overlaps.

Advance the printer page when rendering fails, before continuing.

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

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

**Failed pages shift printed output**

When a page cannot be rendered by either path and later pages remain in the requested range, `onPrintRequested` continues before calling `printer->newPage()`, so the next rendered page is drawn on the failed page’s sheet and the printed sequence shifts or overlaps.

Advance the printer page when rendering fails, before continuing.

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

Comment on lines +504 to +508
const double scale = qMin(pageRect.width() / widthPixels, pageRect.height() / heightPixels);
if (scale < 1.0) {
widthPixels *= scale;
heightPixels *= scale;
}

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 · Preview pages lose print sharpness

When the preview printer reports 72 DPI and pageRect is measured at that device resolution, calculatePrintTargetSize raises the target to 300 DPI, but its scale calculation compares it with the smaller, unconverted pageRect and shrinks the bitmap back to screen resolution. getImageForPrint therefore supplies a low-resolution image and preview-driven output loses print detail.

Convert pageRect to the target DPI coordinate system before fitting the bitmap, or otherwise avoid scaling the 300-DPI target back to screen resolution.

Also at reader/uiframe/DocSheet.cpp:477-480.

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

**Preview pages lose print sharpness**

When the preview printer reports 72 DPI and `pageRect` is measured at that device resolution, `calculatePrintTargetSize` raises the target to 300 DPI, but its scale calculation compares it with the smaller, unconverted `pageRect` and shrinks the bitmap back to screen resolution. `getImageForPrint` therefore supplies a low-resolution image and preview-driven output loses print detail.

Convert `pageRect` to the target DPI coordinate system before fitting the bitmap, or otherwise avoid scaling the 300-DPI target back to screen resolution.

Also at `reader/uiframe/DocSheet.cpp:477-480`.

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.

🟠 High · DjVu print resolution is miscalculated

When a DjVu page’s native resolution is not 72 DPI, djVu page dimensions are stored in pixels at each page’s m_resolution, but calculatePrintTargetSize treats them as 72-DPI points. The rendered bitmap therefore has the wrong pixel dimensions for the printer, so DjVu pages print at an unintended resolution and can be blurry or unnecessarily large.

Use each DjVu page’s stored DPI when converting its pixel dimensions to the requested print bitmap size.

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

**DjVu print resolution is miscalculated**

When a DjVu page’s native resolution is not 72 DPI, djVu page dimensions are stored in pixels at each page’s `m_resolution`, but `calculatePrintTargetSize` treats them as 72-DPI points. The rendered bitmap therefore has the wrong pixel dimensions for the printer, so DjVu pages print at an unintended resolution and can be blurry or unnecessarily large.

Use each DjVu page’s stored DPI when converting its pixel dimensions to the requested print bitmap size.

@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

@pengfeixx
pengfeixx merged commit 4d06026 into linuxdeepin:release/eagle Nov 26, 2026
9 checks passed
@pengfeixx
pengfeixx deleted the fix/nup-printing-eagle branch November 26, 2026 11:16
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