Ao trabalhar com PDFs, muitas vezes é necessário redimensionar o conteúdo para diversos fins. Neste cenário, nosso objetivo é reduzir o tamanho de todas as páginas dentro de um PDF em 70%. Este guia descreve as etapas necessárias, abordando as perguntas relevantes e fornecendo soluções.
Declaração do problema.
Precisamos reduzir o tamanho de cada página de um documento PDF em 70%, mantendo a ordem original das páginas. Isso requer:
- Carregar o arquivo PDF.
- Capturar e redimensionar cada página.
- Salvar as páginas redimensionadas em um novo arquivo PDF.
Passos para alcançar o objetivo.
- Inicializar o ambiente:
- Carregue o arquivo PDF original.
- Exclua qualquer arquivo de saída existente para evitar conflitos.
- Configure os parâmetros de dimensionamento:
- Defina o fator de escala (70%).
- Calcule as bordas necessárias para centralizar o conteúdo dimensionado.
- Processe cada página em um loop:
- Selecione a primeira página.
- Capture o conteúdo da página.
- Crie uma nova página com as dimensões originais.
- Desenhe o conteúdo capturado e redimensionado na nova página.
- Repita para todas as páginas.
- Salve o novo arquivo PDF e abra-o.
- Salve as páginas modificadas em um novo arquivo PDF.
- Abra automaticamente o novo arquivo PDF para revisar os resultados.
Implementação do código.
Aqui está o código C# que executa as etapas acima:
|
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"); |
Explicação e justificativa:
- Exclusão de arquivos: Garante que qualquer saída anterior seja limpa para evitar erros ou conteúdo desatualizado.
- Fator de Escala: Definido como 0.70, isso reduz o tamanho do conteúdo para 70% do original.
- Cálculo da Borda: Centraliza o conteúdo escalado dentro das dimensões originais da página.
- Loop de Processamento de Página: Itera por todas as páginas, capturando, escalando e desenhando cada uma em sequência.
- Salvamento e Abertura de Arquivo: Finaliza o novo documento e o abre para que o usuário possa verificar as alterações.
Ao seguir esta abordagem estruturada, garantimos que cada página do PDF seja dimensionada de forma consistente e mantenha sua ordem original, resultando em um documento processado profissionalmente.
Versão Delphi:
Use Delphi para dimensionar as páginas do PDF em 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; |
Versão VB.Net
Aqui está o código VB.Net para realizar a tarefa:
|
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 |
Tanto a versão VB.Net quanto a versão Delphi do código alcançam o mesmo resultado que o código C# original, garantindo que cada página do PDF seja redimensionada em 70%, mantendo a ordem original.