Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 42 additions & 48 deletions reader/uiframe/DocSheet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,14 @@ DWIDGET_USE_NAMESPACE

namespace {
constexpr double kXpsLogicalDpi = 96.0;
constexpr double kPointLogicalDpi = 72.0; //PDF/DOCX/DjVu 等页面逻辑尺寸为印刷点(1/72 英寸)
constexpr int kFallbackPrintDpi = 300;
constexpr int kMaxPrintPixelsPerSide = 10000;
//DTK 异步打印会一次性持有整个页范围的页面位图,大文档按页数分级限制渲染 DPI,避免内存耗尽
constexpr int kHugePrintDocPageCount = 200;
constexpr int kLargePrintDocPageCount = 50;
constexpr int kHugePrintDocDpiCeiling = 150;
constexpr int kLargePrintDocDpiCeiling = 200;
}

QReadWriteLock DocSheet::g_lock;
Expand Down Expand Up @@ -594,9 +600,11 @@ QImage DocSheet::getImage(int index, int width, int height, const QRect &slice)

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.

#ifdef XPS_SUPPORT_ENABLED
if (m_fileType != Dr::XPS) {
return QSize();
if (m_fileType == Dr::XPS) {
logicalDpi = kXpsLogicalDpi;
}
#endif

Expand All @@ -610,10 +618,27 @@ QSize DocSheet::calculatePrintTargetSize(int pageIndex, const QPrinter &printer,
if (printerDpi <= 0) {
qCWarning(appLog) << "Printer resolution is invalid, fallback to default DPI:" << kFallbackPrintDpi;
printerDpi = kFallbackPrintDpi;
} else if (printerDpi < kFallbackPrintDpi) {
// 打印预览的 DPrinter 为 ScreenResolution(72DPI),按其取图会导致打印模糊
qCWarning(appLog) << "Printer resolution" << printerDpi << "too low, raise to" << kFallbackPrintDpi;
printerDpi = kFallbackPrintDpi;
}

//大文档限制渲染 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.

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;
Comment on lines +628 to +637

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`.

}

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`.


if (widthPixels <= 0.0 || heightPixels <= 0.0) {
qCWarning(appLog) << "Calculated print size is invalid:" << widthPixels << heightPixels;
Expand Down Expand Up @@ -1055,11 +1080,6 @@ void DocSheet::onPrintRequested(DPrinter *printer, const QVector<int> &pageRange

painter.setRenderHints(QPainter::Antialiasing | QPainter::Antialiasing | QPainter::SmoothPixmapTransform);

#ifdef XPS_SUPPORT_ENABLED
const bool isXpsDocument = (m_fileType == Dr::XPS);
#else
const bool isXpsDocument = false;
#endif
auto targetRectForSize = [&pageRect](const QSize &sourceSize) -> QRect {
if (!sourceSize.isValid() || sourceSize.isEmpty()) {
return QRect();
Expand Down Expand Up @@ -1088,17 +1108,15 @@ void DocSheet::onPrintRequested(DPrinter *printer, const QVector<int> &pageRange
QImage image;
QRect targetRect;

if (isXpsDocument) {
const int zeroBasedIndex = pageRange[i] - 1;
const QSize requestedSize = calculatePrintTargetSize(zeroBasedIndex, *printer, pageRect);
if (!requestedSize.isValid()) {
qCWarning(appLog) << "Falling back to view-based print size for XPS page" << zeroBasedIndex;
}

if (requestedSize.isValid()) {
image = loading.getImageForPrint(this, zeroBasedIndex, requestedSize);
//优先按打印机 DPI 渲染高清晰度位图(并列打印等设置走 paintRequested 路径,需保证打印清晰度)
const int zeroBasedIndex = pageRange[i] - 1;
const QSize requestedSize = calculatePrintTargetSize(zeroBasedIndex, *printer, pageRect);
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.

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.

if (!image.isNull())
targetRect = targetRectForSize(image.size());
}
}

if (image.isNull()) {
Expand Down Expand Up @@ -2048,35 +2066,11 @@ void DocSheet::onPopPrintDialog()
//文件打印
preview->setAsynPreview(pageCount());
preview->setDocName(QFileInfo(filePath()).fileName());
if (Dr::DOCX == fileType()) {//旧版本和最新版本使用新接口,PDF文件直接传,解决打印模糊问题
preview->setPrintFromPath(openedFilePath());
}

//pdf若是Linearized类型的,需要另存为Normal类型,然后打印
if (Dr::PDF == fileType()) {
QString pdfPath = filePath();
// 使用 pdftocairo 转换为嵌入矢量pdf,解决打印乱码和模糊问题
QString tmpPdfPath = convertedFileDir() + "/pdftocairoPrint.pdf";
QProcess process;
process.start("pdftocairo", QStringList() << "-pdf" << pdfPath << tmpPdfPath);
bool converted = process.waitForFinished(5 * 60 * 1000) && process.exitCode() == 0;
if (converted) {
// pdftocairo 有时 exit code 为 0 但输出 PDF 结构不完整,验证关键标记是否存在
QFile outFile(tmpPdfPath);
if (outFile.open(QIODevice::ReadOnly)) {
outFile.seek(qMax(0LL, outFile.size() - 1024));
const QByteArray tail = outFile.readAll();
outFile.close();
if (!tail.contains("startxref") || !tail.contains("%%EOF"))
converted = false;
} else {
converted = false;
}
}
if (!converted)
qCWarning(appLog) << "pdftocairo conversion failed or produced invalid PDF, using original";
preview->setPrintFromPath(converted ? tmpPdfPath : pdfPath);
}
// 不使用 setPrintFromPath:该接口把打印交给打印插件按文件路径输出,DTK 会
// 因此禁用并列打印(N-up)以及方向、缩放、边距、水印等设置项。统一走
// paintRequested 由本应用渲染页面,并列打印等设置方可生效;原 PDF 经
// pdftocairo 转换后按路径打印是为解决模糊/乱码,现由 onPrintRequested
// 的高 DPI 位图渲染保证清晰度。
connect(preview, QOverload<DPrinter *, const QVector<int> &>::of(&DPrintPreviewDialog::paintRequested), this, QOverload<DPrinter *, const QVector<int> &>::of(&DocSheet::onPrintRequested));
#else
//图片打印
Expand Down
Loading