Техническая статья

PDFium: low-vision color filters and reading modes в Delphi

Встраивайте workflow PDFium VCL Component в приложения Delphi и C++Builder или workflow PDFium LCL Component в Lazarus/FPC, используя компоненты с исходным кодом для просмотра, рендеринга, форм, печати, preflight-отчетов и проверки по стандартам.

Эта статья предназначена для developers adding viewing aids for users who need contrast, color inversion, or reduced visual strain. Она рассматривает low-vision color filters and reading modes как промышленную инженерию документов, а не как одиночный вызов компонента.

Практический риск состоит в том, что display filters can help users read documents, but they can also mislead review workflows if the application does not explain that the source PDF is unchanged. Поэтому процессу нужны письменный контракт, наблюдаемая диагностика и реалистичные регрессионные файлы.

Архитектурные решения

Keep visual assistance separate from document editing. available modes such as high contrast, grayscale, inverted color, and warm background / whether filters apply to pages, thumbnails, selection highlights, and annotations

  • available modes such as high contrast, grayscale, inverted color, and warm background
  • whether filters apply to pages, thumbnails, selection highlights, and annotations
  • preference persistence per user, per document, or per application profile
  • screen capture, print, and export behavior while filters are active

Порядок реализации

Apply filters in the rendering pipeline. The order below keeps the workflow reviewable for Delphi and C++Builder teams.

  1. add filter selection to viewer state rather than PDF modification code
  2. render representative text, images, forms, and annotations through each mode
  3. keep selection colors and focus indicators visible under every filter
  4. show whether printing uses the original PDF appearance or the filtered view
  5. record mode settings when users report readability issues

Доказательства проверки

Usability evidence for low-vision modes. Keep these fields with the output or support record.

  • filter mode, contrast ratio spot checks, zoom level, and page rendering backend
  • selection, annotation, form-field, and focus visibility under the active mode
  • preference storage decision and reset path
  • support screenshot that clearly labels filtered display state

A filter is a view, not a document change

Low-vision support should alter the rendered presentation without changing the PDF bytes. Users need predictable toggles, persistent preferences, clear print behavior, and fallback text when a document cannot be read visually.

Decision table for low-vision color filters and reading modes

A decision table keeps product ownership visible when the same workflow is reused by a desktop tool, service job, and support utility.

DecisionEngineering reasonEvidence
available modes such as high contrast, grayscale, inverted color, and warm backgroundadd filter selection to viewer state rather than PDF modification codefilter mode, contrast ratio spot checks, zoom level, and page rendering backend
whether filters apply to pages, thumbnails, selection highlights, and annotationsrender representative text, images, forms, and annotations through each modeselection, annotation, form-field, and focus visibility under the active mode
preference persistence per user, per document, or per application profilekeep selection colors and focus indicators visible under every filterpreference storage decision and reset path

Замечания для инженерного ревью по low-vision color filters and reading modes

Используйте эти замечания, чтобы убедиться, что функция вышла за рамки демо и может быть обоснована на релизе, в поддержке и при эскалации клиента

  • Решение: available modes such as high contrast, grayscale, inverted color, and warm background. Точка приложения при реализации: render representative text, images, forms, and annotations through each mode. Доказательство приемки: preference storage decision and reset path. Триггер регрессии: dark-mode application chrome should not reduce document focus visibility
  • Решение: whether filters apply to pages, thumbnails, selection highlights, and annotations. Точка приложения при реализации: keep selection colors and focus indicators visible under every filter. Доказательство приемки: support screenshot that clearly labels filtered display state. Триггер регрессии: image-heavy PDFs may lose detail under aggressive contrast transforms
  • Решение: preference persistence per user, per document, or per application profile. Точка приложения при реализации: show whether printing uses the original PDF appearance or the filtered view. Доказательство приемки: filter mode, contrast ratio spot checks, zoom level, and page rendering backend. Триггер регрессии: highlight colors can disappear if filters are applied after overlay painting
  • Решение: screen capture, print, and export behavior while filters are active. Точка приложения при реализации: record mode settings when users report readability issues. Доказательство приемки: selection, annotation, form-field, and focus visibility under the active mode. Триггер регрессии: printing a filtered view may be desired for accessibility but wrong for legal review

Пограничные случаи

  • image-heavy PDFs may lose detail under aggressive contrast transforms
  • highlight colors can disappear if filters are applied after overlay painting
  • printing a filtered view may be desired for accessibility but wrong for legal review
  • dark-mode application chrome should not reduce document focus visibility

Примечания по Delphi / C++Builder

PDFium Component should sit behind a small service boundary that receives files, streams, profiles, and credentials, then returns output paths, warnings, metrics, and validation status. Важные термины включают color filter, contrast, inversion, reading mode, render pipeline, accessibility.

Пример кода Delphi

Следующий эскиз Delphi показывает практическую границу сервиса для этой темы. Оставляйте проверки политики, журналирование и валидацию вне узкого блока вызова продукта, чтобы сценарий было проще тестировать.

procedure TPreviewForm.ApplyReadingTheme(const Theme: TReadingTheme);
begin
  FCurrentTheme := Theme;
  RenderCurrentPage;
  ApplyBitmapColorMatrix(FPageBitmap, Theme.ColorMatrix);
  PaintContrastCheckedBitmap(FPageBitmap);
  LogAccessibilitySetting(Theme.Name);
end;

Производственный чек-лист

  • Запускайте сценарий на пустом файле, обычном клиентском файле и файле худшего случая
  • Открывайте сгенерированный PDF в целевом просмотрщике, валидаторе, принтере или downstream-приложении
  • Записывайте версию продукта, версию профиля, хэш входа, путь вывода, затраченное время и число предупреждений
  • Храните пароли, сертификаты, временные файлы и данные клиентов по явным правилам хранения
  • Добавляйте регрессионные документы, когда клиентский файл выявляет новый граничный случай

Документация по продукту

PDFium Component

Дополнительные примеры кода

// Engine-level: grayscale applied during rasterization
GrayA := Pdf.RenderPage(0, 0, W, H, ro0, [reGrayscale]);

// Post-process: render in color, convert the finished bitmap
GrayB := Pdf.RenderPage(0, 0, W, H);
GrayscalePdfBitmap(GrayB);
// Affects the on-screen view only
PdfView.PageColor := $00D9EDF2;  // warm paper tone behind page content

// RenderPage output ignores PageColor; pass the color explicitly
Bmp := Pdf.RenderPage(0, 0, W, H, ro0, [], $00D9EDF2);