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

PDFium Component: secure PDF preview surfaces в Delphi

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

Эта статья предназначена для teams showing sensitive PDFs inside line-of-business applications without granting full document-control features. Она рассматривает secure PDF preview surfaces как промышленную инженерию документов, а не как одиночный вызов компонента.

Практический риск состоит в том, что a preview window can accidentally become a data-exfiltration surface if printing, saving, clipboard, links, attachments, and temporary files are not governed. Поэтому процессу нужны письменный контракт, наблюдаемая диагностика и реалистичные регрессионные файлы.

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

Treat preview as a permissioned operation. which roles can open, print, save, copy, search, annotate, or follow links / temporary file location, lifetime, naming, encryption, and cleanup policy

  • which roles can open, print, save, copy, search, annotate, or follow links
  • temporary file location, lifetime, naming, encryption, and cleanup policy
  • external link, embedded file, JavaScript, and attachment handling
  • audit events required for open, close, denied action, print, and export attempts

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

Disable features by policy rather than hiding buttons. The order below keeps the workflow reviewable for Delphi and C++Builder teams.

  1. resolve the user's preview policy before the PDF is loaded
  2. open the document through a controlled stream or temporary file boundary
  3. disable and audit denied actions at the command layer, not only in visible buttons
  4. handle links, attachments, and scripts according to the preview profile
  5. clean temporary resources and write a session summary when the viewer closes

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

Security evidence for preview sessions. Keep these fields with the output or support record.

  • user role, document classification, preview profile, and allowed action list
  • denied commands, external target attempts, attachment attempts, and print requests
  • temporary file path or stream mode plus cleanup result
  • session duration, pages viewed when policy requires it, and close reason

Read-only UI is not the same as secure preview

Secure preview combines viewer permissions, application roles, document policy, link handling, attachment policy, temp-file control, and audit logging. The PDF renderer is only one layer of that surface.

Customer-visible behavior

Users do not see internal call order. They see whether the file opens, validates, prints, edits, imports, or gets rejected. The workflow should translate secure PDF preview surfaces results into states users can act on.

  • resolve the user's preview policy before the PDF is loaded
  • open the document through a controlled stream or temporary file boundary
  • disable and audit denied actions at the command layer, not only in visible buttons
  • keyboard shortcuts and context menus can bypass toolbar-only restrictions
  • attachments and links may leak data even when save is disabled

Замечания для инженерного ревью по secure PDF preview surfaces

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

  • Решение: which roles can open, print, save, copy, search, annotate, or follow links. Точка приложения при реализации: open the document through a controlled stream or temporary file boundary. Доказательство приемки: temporary file path or stream mode plus cleanup result. Триггер регрессии: watermarks should supplement policy but should not be the only protection
  • Решение: temporary file location, lifetime, naming, encryption, and cleanup policy. Точка приложения при реализации: disable and audit denied actions at the command layer, not only in visible buttons. Доказательство приемки: session duration, pages viewed when policy requires it, and close reason. Триггер регрессии: keyboard shortcuts and context menus can bypass toolbar-only restrictions

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

  • keyboard shortcuts and context menus can bypass toolbar-only restrictions
  • attachments and links may leak data even when save is disabled
  • temporary preview files can remain recoverable if cleanup is not verified
  • watermarks should supplement policy but should not be the only protection

Примечания по 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. Важные термины включают secure preview, read-only viewer, audit log, temporary file, attachments, policy.

Пример кода Delphi

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

procedure TSecurePreview.OpenReadOnly(const FileName: string);
begin
  RequireAllowedLocation(FileName);
  PdfView.LoadFromFile(FileName);
  DisableSaveAndClipboardCommands;
  RenderWatermarkedPage(1, CurrentUserName);
  LogPreviewSession(FileName, PdfView.PageCount);
end;

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

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

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

PDFium Component

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

procedure TPreviewPane.PdfViewWebLinkClick(Sender: TObject;
  const Url: WString; var Handled: Boolean);
begin
  Handled := True;   // never fall through to the default shell behavior

  if (AnsiStartsText('https://', Url) or AnsiStartsText('http://', Url))
    and HostIsAllowed(Url) then
    OpenInBrowser(Url)
  else
    FAudit.LogBlockedLink(FDocumentId, Url);
end;
procedure TPreviewPane.ExportAttachment(Index: Integer; const TargetDir: string);
var
  RawName, SafeName, Ext: string;
  Data: TBytes;
begin
  RawName := string(Pdf.AttachmentName[Index]);
  SafeName := ExtractFileName(RawName);    // strips any path components
  Ext := LowerCase(ExtractFileExt(SafeName));

  if not FAllowedExt.Contains(Ext) then    // allowlist, not blocklist
    raise EPreviewPolicy.CreateFmt('Attachment type %s blocked by policy', [Ext]);

  Data := Pdf.Attachment[Index];           // embedded payload as raw bytes
  TFile.WriteAllBytes(
    IncludeTrailingPathDelimiter(TargetDir) + SafeName, Data);
end;