기술 문서

Delphi, C# 및 VB.Net에서 losLab PDF 라이브러리를 사용하여 PDF 페이지를 70% 확장

· PDF 프로그래밍
losLab PDF 라이브러리를 사용하여 PDF 페이지를 70% 축소합니다. losLab PDF 라이브러리

PDF 파일을 사용할 때, 다양한 목적을 위해 콘텐츠의 크기를 조정해야 하는 경우가 많습니다. 이 시나리오에서는 PDF 파일 내의 모든 페이지 크기를 70% 줄이는 것을 목표로 합니다. 이 가이드에서는 필요한 단계를 안내하고, 관련된 질문에 답하고, 해결책을 제공합니다.

문제 정의

PDF 문서의 각 페이지를 원래 페이지 순서를 유지하면서 70% 축소해야 합니다. 이를 위해서는 다음이 필요합니다.

  1. PDF 파일을 로드합니다.
  2. 각 페이지를 캡처하고 크기를 조정합니다.
  3. 크기가 조정된 페이지를 새 PDF 파일로 저장합니다.

목표 달성을 위한 단계

  1. 환경 초기화:
    • 원래 PDF 파일을 로드합니다.
    • 기존에 존재하는 출력 파일을 삭제하여 충돌을 방지합니다.
  2. 스케일링 매개변수 설정:
    • 스케일링 비율을 정의합니다 (70%).
    • 스케일링된 콘텐츠를 중앙에 배치하기 위해 필요한 경계를 계산합니다.
  3. 페이지를 반복적으로 처리합니다:
    • 첫 번째 페이지를 선택합니다.
    • 페이지 내용을 캡처합니다.
    • 원래 크기의 새 페이지를 생성합니다.
    • 캡처된, 크기가 조정된 내용을 새 페이지에 그립니다.
    • 모든 페이지에 대해 반복합니다.
  4. 새 PDF 파일을 저장하고 엽니다.
    • 수정된 페이지를 새 PDF 파일로 저장합니다.
    • 새 PDF 파일을 자동으로 열어 결과를 확인합니다.

코드 구현

다음은 위 단계를 수행하는 C# 코드입니다.

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
private void button_Click(object sender, EventArgs e)
{
    // Delete the old file if it exists to avoid any conflicts.
    File.Delete("newpages.pdf");
 
    // Define variables for page dimensions and scaling factors.
    double pageWidth, pageHeight, horizBorder, vertBorder;
    double scaleFactor = 0.70; // 70% scaling reduction.
    int capturedPageId;
    int ret;
 
    // Load the original PDF document.
    PDFL.LoadFromFile("Pages.pdf");
    PDFL.SetOrigin(1);
 
    // Get the total number of pages in the document.
    int numPages = PDFL.PageCount();
 
    // Loop through all pages to process each one.
    for (int i = 1; i <= numPages; i++)
    {
        // Always select the first page as the pages get deleted after capture.
        PDFL.SelectPage(1);
 
        // Retrieve the dimensions of the current page.
        pageWidth = PDFL.PageWidth();
        pageHeight = PDFL.PageHeight();
 
        // Calculate the borders to center the scaled page content.
        horizBorder = pageWidth * (1.0 - scaleFactor) / 2;
        vertBorder = pageHeight * (1.0 - scaleFactor) / 2;
 
        // Capture the content of the first page. This action deletes the page from the document.
        capturedPageId = PDFL.CapturePage(1);
 
        // Create a new page with the original dimensions.
        int pageId = PDFL.NewPage();
        PDFL.SetPageDimensions(pageWidth, pageHeight);
 
        // Draw the captured page content onto the new page with the specified scaling.
        ret = PDFL.DrawCapturedPage(capturedPageId, horizBorder, vertBorder, pageWidth - 2 * horizBorder, pageHeight - 2 * vertBorder);
    }
 
    // Save the modified document as a new PDF file.
    PDFL.SaveToFile("newpages.pdf");
 
    // Open the newly created PDF file for review.
    System.Diagnostics.Process.Start(@"newpages.pdf");

설명 및 근거
  • 파일 삭제: 이전 출력이 모두 지워져 오류나 오래된 내용이 발생하지 않도록 합니다.
  • 스케일링 계수: 0.70으로 설정하면 콘텐츠 크기가 원본의 70%로 줄어듭니다.
  • 테두리 계산: 스케일링된 콘텐츠를 원본 페이지 크기 내에 중앙에 배치합니다.
  • 페이지 처리 루프: 모든 페이지를 반복하며, 각 페이지를 순서대로 캡처, 스케일링 및 그립니다.
  • 파일 저장 및 열기: 새 문서를 완료하고 사용자에게 변경 사항을 확인하도록 엽니다.

이 체계적인 접근 방식을 따르면 PDF의 각 페이지가 일관되게 크기 조정되고 원래 순서를 유지하여 전문적으로 처리된 문서를 만들 수 있습니다.

Delphi 버전:

Delphi를 사용하여 PDF 페이지를 70%로 크기 조정합니다.

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
procedure TForm1.ButtonClick(Sender: TObject);
var
  pageWidth, pageHeight, horizBorder, vertBorder: Double;
  scaleFactor: Double;
  capturedPageId, ret: Integer;
  numPages, pageId, i: Integer;
begin
  // Delete the old file if it exists to avoid any conflicts.
  if FileExists('newpages.pdf') then
    DeleteFile('newpages.pdf');
 
  // Define the scaling factor (70%).
  scaleFactor := 0.70; // 70% scaling reduction.
 
  // Load the original PDF document.
  PDFL.LoadFromFile('Pages.pdf');
  PDFL.SetOrigin(1);
 
  // Get the total number of pages in the document.
  numPages := PDFL.PageCount();
 
  // Loop through all pages to process each one.
  for i := 1 to numPages do
  begin
    // Always select the first page as the pages get deleted after capture.
    PDFL.SelectPage(1);
 
    // Retrieve the dimensions of the current page.
    pageWidth := PDFL.PageWidth();
    pageHeight := PDFL.PageHeight();
 
    // Calculate the borders to center the scaled page content.
    horizBorder := pageWidth * (1.0 - scaleFactor) / 2;
    vertBorder := pageHeight * (1.0 - scaleFactor) / 2;
 
    // Capture the content of the first page. This action deletes the page from the document.
    capturedPageId := PDFL.CapturePage(1);
 
    // Create a new page with the original dimensions.
    pageId := PDFL.NewPage();
    PDFL.SetPageDimensions(pageWidth, pageHeight);
 
    // Draw the captured page content onto the new page with the specified scaling.
    ret := PDFL.DrawCapturedPage(capturedPageId, horizBorder, vertBorder, pageWidth - 2 * horizBorder, pageHeight - 2 * vertBorder);
  end;
 
  // Save the modified document as a new PDF file.
  PDFL.SaveToFile('newpages.pdf');
 
  // Open the newly created PDF file for review.
  ShellExecute(0, 'open', 'newpages.pdf', nil, nil, SW_SHOWNORMAL);
end;

VB.Net 버전

다음은 이 작업을 수행하는 VB.Net 코드입니다.

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
Private Sub button_Click(sender As Object, e As EventArgs) Handles button.Click
    ' Delete the old file if it exists to avoid any conflicts.
    If File.Exists("newpages.pdf") Then
        File.Delete("newpages.pdf")
    End If
 
    ' Define variables for page dimensions and scaling factors.
    Dim pageWidth, pageHeight, horizBorder, vertBorder As Double
    Dim scaleFactor As Double = 0.70 ' 70% scaling reduction.
    Dim capturedPageId, ret As Integer
 
    ' Load the original PDF document.
    PDFL.LoadFromFile("Pages.pdf")
    PDFL.SetOrigin(1)
 
    ' Get the total number of pages in the document.
    Dim numPages As Integer = PDFL.PageCount()
 
    ' Loop through all pages to process each one.
    For i As Integer = 1 To numPages
        ' Always select the first page as the pages get deleted after capture.
        PDFL.SelectPage(1)
 
        ' Retrieve the dimensions of the current page.
        pageWidth = PDFL.PageWidth()
        pageHeight = PDFL.PageHeight()
 
        ' Calculate the borders to center the scaled page content.
        horizBorder = pageWidth * (1.0 - scaleFactor) / 2
        vertBorder = pageHeight * (1.0 - scaleFactor) / 2
 
        ' Capture the content of the first page. This action deletes the page from the document.
        capturedPageId = PDFL.CapturePage(1)
 
        ' Create a new page with the original dimensions.
        Dim pageId As Integer = PDFL.NewPage()
        PDFL.SetPageDimensions(pageWidth, pageHeight)
 
        ' Draw the captured page content onto the new page with the specified scaling.
        ret = PDFL.DrawCapturedPage(capturedPageId, horizBorder, vertBorder, pageWidth - 2 * horizBorder, pageHeight - 2 * vertBorder)
    Next
 
    ' Save the modified document as a new PDF file.
    PDFL.SaveToFile("newpages.pdf")
 
    ' Open the newly created PDF file for review.
    Process.Start("newpages.pdf")
End Sub

VB.Net 및 Delphi 버전의 코드는 모두 원래 C# 코드와 동일한 결과를 제공하며, PDF의 각 페이지를 70% 축소하면서 원래 순서를 유지합니다.