Categories: PDF 프로그래밍

Delphi HotPDF 컴포넌트에서 안녕하세요

Delphi HotPDF 컴포넌트에서 안녕하세요

Delphi HotPDF 컴포넌트 HelloWorld 데모 프로그램의 종합 가이드에 오신 것을 환영합니다!

HotPDF 컴포넌트 소개

HotPDF 컴포넌트는 Delphi 및 C++Builder 개발자를 위해 특별히 설계된 강력하고 다재다능한 PDF 처리 라이브러리입니다. 이 종합적인 컴포넌트는 개발자가 쉽고 정확하게 PDF 문서를 생성, 조작 및 수정할 수 있도록 하는 광범위한 API를 제공합니다.

HotPDF 컴포넌트의 주요 기능:

  • PDF 생성 및 작성: 레이아웃, 서식 및 내용을 완전히 제어하여 처음부터 PDF 문서 생성
  • 텍스트 및 그래픽 지원: PDF 페이지에 텍스트, 이미지, 도형 및 복잡한 그래픽 추가
  • 다국어 지원: 국제 텍스트 렌더링을 위한 완전한 유니코드 지원
  • 폰트 관리: 다양한 시스템에서 일관된 문서 모양을 위한 폰트 임베딩
  • 압축 옵션: 파일 크기 최적화를 위한 다양한 압축 알고리즘
  • 보안 기능: 문서 암호화, 비밀번호 보호 및 권한 제어
  • 문서 조작: 기존 PDF 문서 병합, 분할 및 수정
  • 테이블 및 양식 지원: 복잡한 테이블 및 대화형 양식 생성

HelloWorld.dpr 프로그램 개요

HelloWorld.dpr 예제 프로그램은 HotPDF 컴포넌트의 가장 기본적이고 중요한 기능인 TexOut 함수에 대한 훌륭한 소개 역할을 합니다. 이 데모 프로그램은 또한 기본 PDF 생성 기능을 보여줍니다.

핵심 기능:

1. PDF 문서 생성

프로그램의 주요 기능은 다국어 “Hello World” 텍스트가 포함된 PDF 문서를 생성하는 것입니다. CreatePDF 프로시저는 다음을 보여줍니다:

  • 컴포넌트 초기화: THotPDF 컴포넌트의 적절한 설정 및 구성
  • 문서 속성: 압축 옵션 및 폰트 임베딩과 같은 메타데이터 설정
  • 다국어 텍스트 렌더링: 영어, 스페인어, 독일어, 프랑스어, 이탈리아어, 포르투갈어, 러시아어, 일본어, 터키어, 중국어, 한국어를 포함한 11개 언어로 텍스트 표시
  • 폰트 관리: 대부분의 언어에는 Arial Unicode MS 사용, 한국어 텍스트에는 맑은 고딕 사용
  • 압축 비교: 파일 크기 차이를 보여주기 위해 압축 및 비압축 버전 모두 생성

2. 창 관리 및 시스템 통합

프로그램에는 다음을 보여주는 정교한 창 열거 기능이 포함되어 있습니다:

  • 시스템 창 열거: Windows API EnumWindows 함수를 사용하여 모든 최상위 창을 반복
  • 창 제목 매칭: 대상 애플리케이션을 식별하기 위한 부분 문자열 매칭 구현
  • 자동 창 닫기: 파일이 열려 있을 수 있는 PDF 뷰어를 닫기 위해 WM_CLOSE 메시지 전송
  • 충돌 방지: 새 PDF 파일을 생성할 때 파일 액세스 충돌이 발생하지 않도록 보장

3. 오류 처리 및 리소스 관리

프로그램은 다음에 대한 모범 사례를 보여줍니다:

  • 메모리 관리: 컴포넌트 인스턴스의 적절한 생성 및 해제
  • 예외 안전성: 리소스 정리를 보장하기 위한 try-finally 블록 사용
  • 사용자 피드백: 프로그램 진행 상황을 사용자에게 알리는 콘솔 출력 제공

기술적 구현 세부사항:

압축 기술

프로그램은 FlateDecode 압축의 효과를 보여주기 위해 동일한 PDF의 두 가지 버전을 생성합니다:

  • 비압축 버전: 더 빠른 생성 시간, 더 큰 파일 크기
  • 압축 버전: 약간 더 긴 생성 시간, 상당히 작은 파일 크기

폰트 처리 전략

프로그램은 정교한 폰트 선택 전략을 사용합니다:

  • Arial Unicode MS: 광범위한 문자 지원으로 인해 대부분의 언어에 사용
  • 맑은 고딕 Semilight: 한국어 텍스트 렌더링을 위해 특별히 선택
  • 폰트 임베딩: 다양한 시스템에서 일관된 모양 보장

크로스 버전 호환성

코드에는 최신 및 레거시 Delphi 버전을 모두 지원하는 조건부 컴파일 지시문이 포함되어 있습니다:

  • XE2+ 지원: 네임스페이스 단위 사용 (WinApi.Windows, System.SysUtils 등)
  • 레거시 지원: 이전 Delphi 버전을 위한 전통적인 단위 이름으로 대체
  • EurekaLog 통합: 선택적 메모리 누수 감지 및 디버깅 지원

교육적 가치

이 HelloWorld 예제는 여러 교육적 목적을 제공합니다:

  • 컴포넌트 소개: HotPDF 컴포넌트 사용에 대한 부드러운 소개 제공
  • 모범 사례: 적절한 리소스 관리 및 오류 처리 시연
  • 시스템 통합: PDF 생성을 Windows 시스템 작업과 통합하는 방법 표시
  • 국제화: PDF 문서에서 다국어 텍스트 처리 설명
  • 성능 고려사항: 다양한 압축 전략과 그 장단점 비교

시작하기

이 예제 프로그램을 실행하려면:

  1. HotPDF 컴포넌트가 Delphi IDE에 올바르게 설치되어 있는지 확인
  2. HelloWorld.dpr 프로젝트 파일 열기
  3. 프로그램 컴파일 및 실행
  4. 프로그램이 압축 차이를 보여주는 두 개의 PDF 파일을 자동으로 생성
  5. 생성된 파일을 검사하여 다국어 텍스트 렌더링을 확인하고 파일 크기 비교

소스 코드

다음은 HelloWorld 데모 프로그램의 완전하고 잘 문서화된 소스 코드입니다:

{************************************************************}
// HotPDF PDF Component
// Copyright(c)2007-2025, https://www.loslab.com
{************************************************************}
// HelloWorld Demo Program for HotPDF Component
// This program demonstrates basic PDF creation capabilities
// including multilingual text support and compression options
{************************************************************}

program HelloWorld;
{$APPTYPE CONSOLE}  // Console application type
{$I ..\..\..\Lib\HotPDF.inc}  // Include HotPDF configuration file

uses
  // EurekaLog units for memory leak detection and debugging (optional)
  {$IFDEF EurekaLog}
  EMemLeaks,          // Memory leak detection
  EResLeaks,          // Resource leak detection
  EDebugJCL,          // JCL debugging support
  EDebugExports,      // Export debugging information
  EFixSafeCallException, // SafeCall exception handling
  EMapWin32,          // Win32 mapping support
  EAppConsole,        // Console application support
  EDialogConsole,     // Console dialog support
  ExceptionLog7,      // Exception logging
  {$ENDIF EurekaLog}
  // System units - different namespaces for XE2+ vs older versions
  {$IFDEF XE2+}
  WinApi.Windows,     // Windows API functions
  WinApi.Messages,    // Windows message constants
  System.SysUtils,    // System utilities
  System.Classes,     // Base classes (TStringList, etc.)
  Vcl.Graphics,       // Graphics support
  {$ELSE}
  Windows,            // Windows API functions (older Delphi)
  Messages,           // Windows message constants (older Delphi)
  SysUtils,           // System utilities (older Delphi)
  Classes,            // Base classes (older Delphi)
  Graphics,           // Graphics support (older Delphi)
  {$ENDIF}
  HPDFDoc;            // HotPDF main component unit

// Creates a PDF file with multilingual "Hello World" text
// Parameters:
//   FileName: Output PDF file name
//   UseCompression: True to enable FlateDecode compression, False for no compression
procedure CreatePDF(const FileName: string; UseCompression: Boolean);
var
  HotPDF: THotPDF;  // Main HotPDF component instance
begin
  // Create HotPDF component instance
  HotPDF := THotPDF.Create(nil);
  try
    // Configure PDF properties
    HotPDF.AutoLaunch := true;        // Automatically open PDF after creation
    HotPDF.FileName := FileName;      // Set output file name

    // Set compression based on parameter
    if UseCompression then
    begin
      HotPDF.Compression := cmFlateDecode;  // Enable FlateDecode compression
      WriteLn('Creating compressed PDF: ', FileName);
    end
    else
    begin
      HotPDF.Compression := cmNone;         // No compression
      WriteLn('Creating uncompressed PDF: ', FileName);
    end;

    HotPDF.FontEmbedding := true;     // Embed fonts for better compatibility
    HotPDF.BeginDoc;                  // Start PDF document creation

    // Set Unicode font for multilingual text support
    // Arial Unicode MS supports most languages except Korean
    // procedure SetFont ( FontName: AnsiString; FontStyle: TFontStyles; ASize: Single; FontCharset: TFontCharset = DEFAULT_CHARSET; IsVertical: boolean = false);
    // DEFAULT_CHARSET: 1 - Font is chosen based on Name. If the described font is not available on the system, Windows will substitute another font
    HotPDF.CurrentPage.SetFont('Arial Unicode MS', [], 12, 1, False);
    
    // Display "Hello World" in multiple languages
    // TextOut parameters: (X, Y, Angle, Text)
    HotPDF.CurrentPage.TextOut(80, 50, 0, 'Hello, Delphi PDF world!');      // English
    HotPDF.CurrentPage.TextOut(80, 70, 0, 'Hola, mundo Delphi PDF!');       // Spanish
    HotPDF.CurrentPage.TextOut(80, 90, 0, 'Hallo, Delphi PDF Welt!');       // German
    HotPDF.CurrentPage.TextOut(80, 110, 0, 'Bonjour, monde PDF Delphi!');   // French
    HotPDF.CurrentPage.TextOut(80, 130, 0, 'Ciao, mondo Delphi PDF!');      // Italian
    HotPDF.CurrentPage.TextOut(80, 150, 0, 'Olá, mundo Delphi PDF!');       // Portuguese
    HotPDF.CurrentPage.TextOut(80, 170, 0, 'Здравствуйте, Delphi PDF мир!'); // Russian
    HotPDF.CurrentPage.TextOut(80, 190, 0, 'こんにちは、Delphi PDFの世界!');    // Japanese
    HotPDF.CurrentPage.TextOut(80, 210, 0, 'Merhaba, Delphi PDF dünyası!'); // Turkish
    HotPDF.CurrentPage.TextOut(80, 230, 0, '你好,Delphi PDF世界');           // Chinese
    
    // Korean text requires a specific Korean font
    // Arial Unicode MS doesn't properly support Korean characters
    HotPDF.CurrentPage.SetFont('Malgun Gothic Semilight', [], 12, 0, False);
    HotPDF.CurrentPage.TextOut(80, 250, 0, '여보세요, Delphi PDF 세계!');     // Korean
    
    HotPDF.EndDoc;  // Finalize and save the PDF document
    WriteLn('PDF created successfully: ', FileName);
  finally 
    HotPDF.Free;    // Clean up HotPDF component
  end;
end;

// Global variables for window enumeration and PDF creation
var
  Title: String;                        // Individual title string (unused in current implementation)
  Titles: TStrings;                     // List of window titles to search for
  Window: HWND;                         // Window handle (unused in current implementation)
  WindowText: array[0..255] of Char;    // Buffer for window text (unused in current implementation)
  WindowTitle: String;                  // Window title string (unused in current implementation)
  I: Integer;                           // Loop counter (unused in current implementation)

// Callback function for EnumWindows API
// This function is called for each top-level window in the system
// Parameters:
//   hWnd: Handle to the current window being enumerated
//   lParam: User-defined data (in our case, pointer to TStrings with target titles)
// Returns: True to continue enumeration, False to stop
function EnumWindowsProc(hWnd: HWND; lParam: LPARAM): BOOL; stdcall;
var
  Titles: TStrings;                     // List of target window titles
  I: Integer;                           // Loop counter
  WindowText: array[0..255] of Char;    // Buffer to store window text
  WindowTitle: String;                  // Current window's title as string
begin
  Result := True;                       // Continue enumeration by default
  Titles := TStrings(lParam);           // Cast lParam back to TStrings
  
  // Get the window title text
  if GetWindowText(hWnd, WindowText, SizeOf(WindowText)) > 0 then
  begin
    WindowTitle := String(WindowText);  // Convert char array to string
    
    // Check if window title contains any of our target strings
    for I := 0 to Titles.Count - 1 do
    begin
      // Use Pos function to check if target string is contained in window title
      if Pos(Titles[I], WindowTitle) > 0 then
      begin
        // Send WM_CLOSE message to close the window
        PostMessage(hWnd, WM_CLOSE, 0, 0);
        Break;  // Exit loop after finding first match
      end;
    end;
  end;
end;

// Main program execution begins here
begin
  // Close any existing PDF files that might be open in PDF viewers
  // This prevents file access conflicts when creating new PDFs with same names
  Titles := TStringList.Create;
  try
    // Define list of window title substrings to search for
    // Any window containing these strings will be closed
    // This will close Adobe and Foxit PDF reader & editor and many other PDF apps
    Titles.CommaText := '"HelloWorld-compressed.pdf", "HelloWorld-uncompressed.pdf", "Foxit"';

    // Enumerate all top-level windows and close matching ones
    // EnumWindows calls our callback function for each window
    EnumWindows(@EnumWindowsProc, LPARAM(Titles));
  finally
    Titles.Free;  // Clean up string list
  end;

  // Display program header
  WriteLn('=== HotPDF Compression Test ===');
  WriteLn('This demo creates two PDF files to demonstrate compression differences.');
  WriteLn('');

  // Create uncompressed PDF first
  // This version will be larger but faster to create
  CreatePDF('HelloWorld-uncompressed.pdf', False);

  // Create compressed PDF second
  // This version will be smaller but takes slightly longer to create
  CreatePDF('HelloWorld-compressed.pdf', True);

  // Display completion message
  WriteLn('');
  WriteLn('All PDF files created successfully!');
  WriteLn('Please check the files to compare compressed vs uncompressed versions.');
  WriteLn('You can examine file sizes to see the compression effect.');
  WriteLn('');
  WriteLn('Press Enter to exit...');
  ReadLn;  // Wait for user input before closing console

end.

 

losLab

Devoted to developing PDF and Spreadsheet developer library, including PDF creation, PDF manipulation, PDF rendering library, and Excel Spreadsheet creation & manipulation library.

Recent Posts

HotPDF Delphi组件:在PDF文档中创建垂直文本布局

HotPDF Delphi组件:在PDF文档中创建垂直文本布局 本综合指南演示了HotPDF组件如何让开发者轻松在PDF文档中生成Unicode垂直文本。 理解垂直排版(縦書き/세로쓰기/竖排) 垂直排版,也称为垂直书写,中文称为縱書,日文称为tategaki(縦書き),是一种起源于2000多年前古代中国的传统文本布局方法。这种书写系统从上到下、从右到左流动,创造出具有深厚文化意义的独特视觉外观。 历史和文化背景 垂直书写系统在东亚文学和文献中发挥了重要作用: 中国:传统中文文本、古典诗歌和书法主要使用垂直布局。现代简体中文主要使用横向书写,但垂直文本在艺术和仪式场合仍然常见。 日本:日语保持垂直(縦書き/tategaki)和水平(横書き/yokogaki)两种书写系统。垂直文本仍广泛用于小说、漫画、报纸和传统文档。 韩国:历史上使用垂直书写(세로쓰기),但现代韩语(한글)主要使用水平布局。垂直文本出现在传统场合和艺术应用中。 越南:传统越南文本在使用汉字(Chữ Hán)书写时使用垂直布局,但随着拉丁字母的采用,这种做法已基本消失。 垂直文本的现代应用 尽管全球趋向于水平书写,垂直文本布局在几个方面仍然相关: 出版:台湾、日本和香港的传统小说、诗集和文学作品…

2 days ago

HotPDF Delphi 컴포넌트: PDF 문서에서 세로쓰기

HotPDF Delphi 컴포넌트: PDF 문서에서 세로쓰기 텍스트 레이아웃 생성 이 포괄적인 가이드는 HotPDF 컴포넌트를 사용하여…

2 days ago

HotPDF Delphiコンポーネント-PDFドキュメントでの縦書き

HotPDF Delphiコンポーネント:PDFドキュメントでの縦書きテキストレイアウトの作成 この包括的なガイドでは、HotPDFコンポーネントを使用して、開発者がPDFドキュメントでUnicode縦書きテキストを簡単に生成する方法を実演します。 縦書き組版の理解(縦書き/세로쓰기/竖排) 縦書き組版は、日本語では縦書きまたはたてがきとも呼ばれ、2000年以上前の古代中国で生まれた伝統的なテキストレイアウト方法です。この書字体系は上から下、右から左に流れ、深い文化的意義を持つ独特の視覚的外観を作り出します。 歴史的・文化的背景 縦書きシステムは東アジアの文学と文書において重要な役割を果たしてきました: 中国:伝統的な中国語テキスト、古典詩、書道では主に縦書きレイアウトが使用されていました。現代の簡体字中国語は主に横書きを使用していますが、縦書きテキストは芸術的・儀式的な文脈で一般的です。 日本:日本語は縦書き(縦書き/たてがき)と横書き(横書き/よこがき)の両方の書字体系を維持しています。縦書きテキストは小説、漫画、新聞、伝統的な文書で広く使用されています。 韓国:歴史的には縦書き(세로쓰기)を使用していましたが、現代韓国語(한글)は主に横書きレイアウトを使用しています。縦書きテキストは伝統的な文脈や芸術的応用で見られます。 ベトナム:伝統的なベトナム語テキストは漢字(Chữ Hán)で書かれた際に縦書きレイアウトを使用していましたが、この慣行はラテン文字の採用とともにほぼ消失しました。 縦書きテキストの現代的応用 横書きへの世界的な傾向にもかかわらず、縦書きテキストレイアウトはいくつかの文脈で関連性を保っています: 出版:台湾、日本、香港の伝統的な小説、詩集、文学作品…

2 days ago

Отладка проблем порядка страниц PDF: Реальный кейс-стади

Отладка проблем порядка страниц PDF: Реальный кейс-стади компонента HotPDF Опубликовано losLab | Разработка PDF |…

4 days ago

PDF 페이지 순서 문제 디버깅: HotPDF 컴포넌트 실제 사례 연구

PDF 페이지 순서 문제 디버깅: HotPDF 컴포넌트 실제 사례 연구 발행자: losLab | PDF 개발…

4 days ago

PDFページ順序問題のデバッグ:HotPDFコンポーネント実例研究

PDFページ順序問題のデバッグ:HotPDFコンポーネント実例研究 発行者:losLab | PDF開発 | Delphi PDFコンポーネント PDF操作は特にページ順序を扱う際に複雑になることがあります。最近、私たちはPDF文書構造とページインデックスに関する重要な洞察を明らかにした魅力的なデバッグセッションに遭遇しました。このケーススタディは、一見単純な「オフバイワン」エラーがPDF仕様の深い調査に発展し、文書構造に関する根本的な誤解を明らかにした過程を示しています。 PDFページ順序の概念 - 物理的オブジェクト順序と論理的ページ順序の関係 問題 私たちはHotPDF DelphiコンポーネントのCopyPageと呼ばれるPDFページコピーユーティリティに取り組んでいました。このプログラムはデフォルトで最初のページをコピーするはずでしたが、代わりに常に2番目のページをコピーしていました。一見すると、これは単純なインデックスバグのように見えました -…

4 days ago