기술 문서

Delphi에서 PDFium VCL을 사용하여 기능이 풍부한 PDF 뷰어 구축

· PDF 프로그래밍

이 튜토리얼에서는 PDFium VCL을 사용하여 전문적인 PDF 뷰어 애플리케이션을 만드는 방법을 알아봅니다. PDFium VCL은 Google의 PDFium 렌더링 엔진을 래핑하는 강력한 Delphi 컴포넌트입니다.이 데모는 모든 PDF 애플리케이션의 기반이 되는 핵심 뷰잉 기능을 보여줍니다.

개요

PDF 뷰어 데모는 Delphi 애플리케이션에서 PDF 문서를 보는 데 필요한 필수 기능을 보여줍니다.

주요 기능

  • 문서 로딩 – 암호 보호를 지원하는 PDF 파일 열기
  • 페이지 탐색 – 첫 페이지, 이전 페이지, 다음 페이지, 마지막 페이지 버튼과 키보드 단축키
  • 확대/축소 컨트롤 – 다양한 확대/축소 레벨, 페이지 전체 또는 페이지 너비에 맞춤
  • 페이지 회전 – 페이지를 왼쪽 또는 오른쪽으로 90° 회전
  • 텍스트 선택 – PDF 문서에서 텍스트를 선택하고 복사
  • 북마크 – 문서의 목차를 사용하여 탐색
  • 텍스트 검색 – 문서 내 텍스트 찾기
  • 인쇄 – 페이지 범위 선택 기능을 사용하여 문서 인쇄
  • 다른 이름으로 저장 – 문서를 새 PDF 파일로 내보내기

PDFium DLL 요구 사항

PDFium VCL 애플리케이션을 실행하기 전에 PDFium DLL 파일을 설치해야 합니다. DLL 파일은 다음 폴더에 있습니다. DLLs PDFium VCL 패키지 폴더:

  • pdfium32.dll – 32비트 버전 (~5 MB)
  • pdfium64.dll – 64비트 버전 (~6 MB)
  • pdfium32v8.dll – 32비트, V8 JavaScript 엔진 탑재 (~23MB)
  • pdfium64v8.dll – 64비트, V8 JavaScript 엔진 탑재 (~27MB)

설치: 실행 PDFiumVCL\DLLs\CopyDlls.bat 관리자 권한으로 실행합니다. 이 스크립트는 적절한 DLL 파일을 Windows 시스템 디렉터리에 자동으로 복사합니다.

1
2
3
4
5
6
@echo off
REM On 64-bit Windows:
REM   - 32-bit DLLs %SystemRoot%\SysWOW64\
REM   - 64-bit DLLs %SystemRoot%\System32\
REM On 32-bit Windows:
REM   - 32-bit DLLs %SystemRoot%\System32\

참고: 표준 DLL(Standard DLL)을 사용하세요.pdfium32.dll/pdfium64.dll대부분의 애플리케이션에서는 이 설정을 사용하면 됩니다. V8 버전은 PDF 파일에 실행이 필요한 JavaScript가 포함되어 있는 경우에만 필요합니다.

핵심 구성 요소.

데모는 두 가지 주요 PDFium VCL 구성 요소를 사용합니다.

1
2
Pdf: TPdf;        // Non-visual component for PDF operations
PdfView: TPdfView; // Visual component for rendering PDF pages

TPdf 컴포넌트

The TPdf 이 컴포넌트는 PDF 문서 로드, 저장 및 문서 속성(메타데이터, 북마크, 페이지 정보 등) 접근을 포함한 모든 PDF 문서 작업을 처리합니다.

TPdfView 컴포넌트

The TPdfView 이 컴포넌트는 부드러운 스크롤, 확대/축소 지원 및 사용자 상호 작용 처리를 제공하는 스크롤 가능한 시각적 컨트롤입니다.

PDF 문서 로드

PDF 파일을 여는 것은 간단합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
procedure TFormMain.SpeedButtonOpenPdfClick(Sender: TObject);
var
  Password: string;
begin
  if OpenDialog.Execute then
  begin
    Pdf.FileName := OpenDialog.FileName;
    Pdf.Password := '';
    Pdf.PageNumber := 0;
    
    try
      PdfView.Active := True;
    except
      on Error: EPdfError do
        if Error.Message = 'Password required or incorrect password' then
        begin
          if InputQuery('Enter Password', 'Password: ', Password) then
          begin
            Pdf.Password := Password;
            PdfView.Active := True;
          end
          else
            raise;
        end
        else
          raise;
    end;
    
    if PdfView.PageCount > 0 then
      PdfView.PageNumber := 1;
  end;
end;

페이지 탐색

페이지 탐색 구현은 다음과 같이 간단합니다. PageNumber 속성:

1
2
3
4
5
6
7
8
9
10
11
// Navigate to first page
PdfView.PageNumber := 1;
 
// Navigate to last page
PdfView.PageNumber := PdfView.PageCount;
 
// Previous page
PdfView.PageNumber := PdfView.PageNumber - 1;
 
// Next page
PdfView.PageNumber := PdfView.PageNumber + 1;

Zoom 컨트롤

The TPdfView component은 다양한 확대/축소 옵션을 제공합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
// Set specific zoom levels
PdfView.Zoom := 1.0;    // 100%
PdfView.Zoom := 0.5;    // 50%
PdfView.Zoom := 2.0;    // 200%
 
// Fit to page width
PdfView.Zoom := PdfView.PageWidthZoom[PdfView.PageNumber];
 
// Fit entire page in view
PdfView.Zoom := PdfView.PageZoom[PdfView.PageNumber];
 
// Actual size (based on DPI)
PdfView.Zoom := PdfView.ActualSizeZoom[PdfView.PageNumber];

페이지 회전

다음을 사용하여 페이지를 회전합니다. Rotation 속성:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Rotate right (clockwise)
case PdfView.Rotation of
  ro0:   PdfView.Rotation := ro90;
  ro90:  PdfView.Rotation := ro180;
  ro180: PdfView.Rotation := ro270;
  ro270: PdfView.Rotation := ro0;
end;
 
// Rotate left (counter-clockwise)
case PdfView.Rotation of
  ro0:   PdfView.Rotation := ro270;
  ro90:  PdfView.Rotation := ro0;
  ro180: PdfView.Rotation := ro90;
  ro270: PdfView.Rotation := ro180;
end;

문서 정보 표시

다음을 통해 문서 메타데이터에 액세스합니다. TPdf component:

1
2
3
4
5
6
7
8
9
10
11
12
13
procedure TFormMain.SpeedButtonShowInfoClick(Sender: TObject);
begin
  ShowMessage(
    'Author: ' + Pdf.Author + #13#10 +
    'Creator: ' + Pdf.Creator + #13#10 +
    'Keywords: ' + Pdf.Keywords + #13#10 +
    'Producer: ' + Pdf.Producer + #13#10 +
    'Subject: ' + Pdf.Subject + #13#10 +
    'Title: ' + Pdf.Title + #13#10 +
    'Creation date: ' + Pdf.CreationDate + #13#10 +
    'Modified date: ' + Pdf.ModifiedDate
  );
end;

북마크 사용

데모에서는 TreeView를 사용하여 문서의 북마크를 표시하여 쉽게 탐색할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
procedure TFormMain.AddBookmarks(Node: TTreeNode; Bookmarks: TBookmarks);
var
  ChildNode: TTreeNode;
  I: Integer;
begin
  for I := 0 to Length(Bookmarks) - 1 do
  begin
    ChildNode := TreeViewBookmarks.Items.AddChildObject(
      Node,
      Bookmarks[I].Title,
      Bookmarks[I].Handle
    );
    ChildNode.HasChildren := Pdf.HasBookmarkChildren[Bookmarks[I]];
    
    if ChildNode.HasChildren then
      AddBookmarks(ChildNode, Pdf.BookmarkChildren[Bookmarks[I]]);
  end;
end;

렌더링 옵션

다양한 옵션을 사용하여 렌더링을 사용자 정의합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Available render options
type
  TRenderOption = (
    reAnnotations,      // Render annotations
    reLcd,              // LCD optimized rendering
    reNoNativeText,     // Don't use native text output
    reGrayscale,        // Render in grayscale
    reLimitCache,       // Limit image cache size
    reHalftone,         // Use halftone for image stretching
    rePrinting,         // Optimize for printing
    reNoSmoothText,     // Disable text anti-aliasing
    reNoSmoothImage,    // Disable image anti-aliasing
    reNoSmoothPath      // Disable path anti-aliasing
  );
 
// Apply options to the view
PdfView.Options := [reAnnotations, reLcd];

결론

PDF 뷰어 데모는 Delphi 애플리케이션에 PDF 뷰잉 기능을 추가하기 위한 견고한 기반을 제공합니다. PDFium VCL을 사용하면 Google Chrome에서 사용하는 동일한 PDF 렌더링 엔진에 액세스할 수 있어 고품질의 정확한 PDF 표시가 보장됩니다.

이 구성 요소는 주석, 양식 필드 및 포함된 글꼴과 같은 복잡한 PDF 기능을 자동으로 처리하므로, PDF 파싱과 같은 저수준 작업 대신 애플리케이션의 고유한 기능을 개발하는 데 집중할 수 있습니다.

PDFium VCL을 다운로드하여 Delphi에서 PDF 개발을 시작합니다. loslab.com에서 다운로드합니다.