losLab PDF Library предоставляет командам Delphi и C++Builder PDF-движок с доступным исходным кодом для настольных, серверных, DLL, ActiveX и Dylib процессов, включая встроенные проверки PDF/A и PDF/UA, подписи PAdES и выбор рендерера без отправки документов во внешний PDF-сервис.
Эта статья предназначена для teams building print-preview, hard-copy approval, label, or controlled-output workflows в Delphi. Она рассматривает print preview and device-context output как промышленную инженерию документов, а не как одиночный вызов компонента.
Практический риск состоит в том, что print output can differ from preview when device margins, scaling, rotation, duplex settings, and driver behavior are not modeled explicitly. Поэтому процессу нужны письменный контракт, наблюдаемая диагностика и реалистичные регрессионные файлы.
Архитектурные решения
Separate PDF page geometry from printer geometry. fit, actual size, shrink-only, center, rotation, and crop rules / paper selection, printable margins, tray, duplex, and color mode policy
- fit, actual size, shrink-only, center, rotation, and crop rules
- paper selection, printable margins, tray, duplex, and color mode policy
- preview fidelity requirements compared with printer-driver output
- whether annotations, form fields, watermarks, and backgrounds are printed
Порядок реализации
Preview with the same print contract used for output. The order below keeps the workflow reviewable for Delphi and C++Builder teams.
- read page size and rotation before asking the printer for device capabilities
- compute the target rectangle from paper, printable area, and scaling policy
- render preview using the same geometry contract as the print job
- record driver and device context details when output is generated
- test high-value documents on the printer families customers actually use
Доказательства проверки
Print evidence that helps support reproduce issues. Keep these fields with the output or support record.
- printer name, driver version, paper size, printable area, scaling, and rotation
- PDF page box, page number, rendered rectangle, and DPI
- annotation and form-field print policy
- operator selection and print result or driver error
A device context is a target, not a neutral canvas
A production print workflow should know the PDF page box, target paper size, printable area, scaling rule, rotation decision, and driver settings before rendering to a device context.
Operational metrics to watch
The first release should expose enough metrics to prove the workflow is healthy under real files, not only under curated samples.
- count and rate for printer name, driver version, paper size, printable area, scaling, and rotation
- warning trend for printer drivers can change printable margins after paper selection
- latency of the stage that must read page size and rotation before asking the printer for device capabilities
- profile usage for fit, actual size, shrink-only, center, rotation, and crop rules
Замечания для инженерного ревью по print preview and device-context output
Используйте эти замечания, чтобы убедиться, что функция вышла за рамки демо и может быть обоснована на релизе, в поддержке и при эскалации клиента
- Решение: fit, actual size, shrink-only, center, rotation, and crop rules. Точка приложения при реализации: compute the target rectangle from paper, printable area, and scaling policy. Доказательство приемки: annotation and form-field print policy. Триггер регрессии: preview should disclose when it cannot match a driver-specific feature
- Решение: paper selection, printable margins, tray, duplex, and color mode policy. Точка приложения при реализации: render preview using the same geometry contract as the print job. Доказательство приемки: operator selection and print result or driver error. Триггер регрессии: printer drivers can change printable margins after paper selection
- Решение: preview fidelity requirements compared with printer-driver output. Точка приложения при реализации: record driver and device context details when output is generated. Доказательство приемки: printer name, driver version, paper size, printable area, scaling, and rotation. Триггер регрессии: landscape pages need a clear auto-rotation policy
- Решение: whether annotations, form fields, watermarks, and backgrounds are printed. Точка приложения при реализации: test high-value documents on the printer families customers actually use. Доказательство приемки: PDF page box, page number, rendered rectangle, and DPI. Триггер регрессии: duplex output can expose odd-page and blank-page assumptions
- Решение: fit, actual size, shrink-only, center, rotation, and crop rules. Точка приложения при реализации: read page size and rotation before asking the printer for device capabilities. Доказательство приемки: annotation and form-field print policy. Триггер регрессии: preview should disclose when it cannot match a driver-specific feature
Пограничные случаи
- printer drivers can change printable margins after paper selection
- landscape pages need a clear auto-rotation policy
- duplex output can expose odd-page and blank-page assumptions
- preview should disclose when it cannot match a driver-specific feature
Примечания по Delphi / C++Builder
PDFlibPas should sit behind a small service boundary that receives files, streams, profiles, and credentials, then returns output paths, warnings, metrics, and validation status. Важные термины включают device context, print preview, DPI, printable area, scaling, duplex.
Пример кода Delphi
Следующий эскиз Delphi показывает практическую границу сервиса для этой темы. Оставляйте проверки политики, журналирование и валидацию вне узкого блока вызова продукта, чтобы сценарий было проще тестировать.
procedure PaintPreviewPage(Canvas: TCanvas; const FileName: string; PageRef: Integer; Dpi: Double);
var
Pdf: TPDFlib;
FileHandle: Integer;
begin
Pdf := TPDFlib.Create;
try
FileHandle := Pdf.DAOpenFileReadOnly(FileName, '');
try
Pdf.DARenderPageToDC(FileHandle, PageRef, Dpi, Canvas.Handle);
DrawPreviewOverlay(Canvas, PageRef, Dpi);
finally
Pdf.DACloseFile(FileHandle);
end;
finally
Pdf.Free;
end;
end;
Производственный чек-лист
- Запускайте сценарий на пустом файле, обычном клиентском файле и файле худшего случая
- Открывайте сгенерированный PDF в целевом просмотрщике, валидаторе, принтере или downstream-приложении
- Записывайте версию продукта, версию профиля, хэш входа, путь вывода, затраченное время и число предупреждений
- Храните пароли, сертификаты, временные файлы и данные клиентов по явным правилам хранения
- Добавляйте регрессионные документы, когда клиентский файл выявляет новый граничный случай
Документация по продукту
Дополнительные примеры кода
var
Pdf: TPDFlib;
Virt: WideString;
Opt: Integer;
begin
Pdf := TPDFlib.Create;
try
if Pdf.LoadFromFile('report.pdf', '') <> 1 then
raise Exception.Create('load failed');
Virt := Pdf.NewCustomPrinter(Pdf.GetDefaultPrinterName);
Pdf.SetupPrinter(Virt, 1, 9); // setting 1 = paper, DMPAPER_A4
Pdf.SetupPrinter(Virt, 11, 1); // setting 11 = orientation, 1 = portrait
Opt := Pdf.PrintOptions(1, 1, 'Monthly Report'); // fit to paper, auto-rotate + center
Pdf.PrintDocument(Virt, 1, Pdf.PageCount, Opt);
finally
Pdf.Free;
end;
end;procedure ShowPrinterTruePreview(Pdf: TPDFlib; const Virt: WideString; Opt: Integer);
var
Data: AnsiString;
Strm: TMemoryStream;
Bmp: TBitmap;
begin
Data := Pdf.GetPrintPreviewBitmapToString(Virt, 1, Opt, 1200, 0);
Strm := TMemoryStream.Create;
try
Strm.WriteBuffer(PAnsiChar(Data)^, Length(Data));
Strm.Position := 0;
Bmp := TBitmap.Create;
try
Bmp.LoadFromStream(Strm);
PreviewImage.Picture.Assign(Bmp);
finally
Bmp.Free;
end;
finally
Strm.Free;
end;
end;