Categories: PDF Programming

Scaling PDF Pages by 70% using losLab PDF Library, in Delphi, C# & VB.Net

Scale PDF pages by 70% through losLab PDF library

When working with PDFs, there are often requirements to scale the content for various purposes. In this scenario, we aim to reduce the size of all pages within a PDF by 70%. This guide walks through the necessary steps, addressing the relevant questions and providing solutions.

Problem Statement

We need to scale down each page of a PDF document by 70% while maintaining the original page order. This requires:

  1. Loading the PDF file.
  2. Capturing and scaling each page.
  3. Saving the scaled pages into a new PDF file.

Steps to Achieve the Goal

  1. Initialize the Environment:
    • Load the original PDF file.
    • Delete any previously existing output file to avoid conflicts.
  2. Set Up the Scaling Parameters:
    • Define the scaling factor (70%).
    • Calculate the borders required to center the scaled content.
  3. Process Each Page in a Loop:
    • Select the first page.
    • Capture the page content.
    • Create a new page with the original dimensions.
    • Draw the captured, scaled content onto the new page.
    • Repeat for all pages.
  4. Save the New PDF and Open it:
    • Save the modified pages into a new PDF file.
    • Automatically open the new PDF to review the results.

Code Implementation

Here is the C# code that performs the above steps:

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");

Explanation and Justification

  • File Deletion: Ensures that any previous output is cleared to prevent errors or outdated content.
  • Scaling Factor: Set to 0.70, this reduces the size of the content to 70% of the original.
  • Border Calculation: Centers the scaled content within the original page dimensions.
  • Page Processing Loop: Iterates through all pages, capturing, scaling, and drawing each one in sequence.
  • File Saving and Opening: Finalizes the new document and opens it for the user to verify the changes.

By following this structured approach, we ensure that each page in the PDF is scaled consistently and maintains its original order, resulting in a professionally processed document.

Delphi edition:

Use Delphi to Scale PDF pages by 70%:

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 edition

Here is the VB.Net code to perform the task:

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

Both VB.Net and Delphi versions of the code achieve the same result as the original C# code, ensuring that each page in the PDF is scaled down by 70% while maintaining the original order.

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 |…

3 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