Al trabajar con archivos PDF, a menudo existen requisitos para escalar el contenido para diversos fines. En este escenario, nuestro objetivo es reducir el tamaño de todas las páginas dentro de un archivo PDF en un 70%. Esta guía describe los pasos necesarios, aborda las preguntas relevantes y proporciona soluciones.
Declaración del problema.
Necesitamos reducir el tamaño de cada página de un documento PDF en un 70%, manteniendo el orden original de las páginas. Esto requiere:
- Cargar el archivo PDF.
- Capturar y escalar cada página.
- Guardar las páginas escaladas en un nuevo archivo PDF.
Pasos para lograr el objetivo.
- Inicializar el entorno:
- Cargar el archivo PDF original.
- Elimine cualquier archivo de salida existente para evitar conflictos.
- Configure los parámetros de escalado:
- Defina el factor de escalado (70%).
- Calcule los bordes necesarios para centrar el contenido escalado.
- Procese cada página en un bucle:
- Seleccione la primera página.
- Capture el contenido de la página.
- Cree una nueva página con las dimensiones originales.
- Dibuje el contenido capturado y escalado en la nueva página.
- Repita para todas las páginas.
- Guarde el nuevo archivo PDF y ábralo:
- Guarde las páginas modificadas en un nuevo archivo PDF.
- Abra automáticamente el nuevo archivo PDF para revisar los resultados.
Implementación del código
Aquí está el código en C# que realiza los pasos anteriores:
|
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"); |
Explicación y justificación.
- Eliminación de archivos: Asegura que cualquier salida anterior se borre para evitar errores o contenido desactualizado.
- Factor de escala: Establecer en 0.70, esto reduce el tamaño del contenido al 70% del original.
- Cálculo de bordes: Centra el contenido escalado dentro de las dimensiones originales de la página.
- Bucle de procesamiento de páginas: Itera a través de todas las páginas, capturando, escalando y dibujando cada una en secuencia.
- Guardado y apertura de archivos: Finaliza el nuevo documento y lo abre para que el usuario verifique los cambios.
Siguiendo este enfoque estructurado, garantizamos que cada página del PDF se escale de manera consistente y mantenga su orden original, lo que resulta en un documento procesado profesionalmente.
Edición Delphi:
Utilice Delphi para escalar las páginas del PDF en un 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; |
Edición VB.Net
Aquí está el código de VB.Net para realizar la tarea:
|
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 las versiones de VB.Net como de Delphi del código logran el mismo resultado que el código C# original, asegurando que cada página del PDF se reduzca en un 70% manteniendo el orden original.