Page Setting (11)
In some circumstances, you may need to change the page size of a PDF. For example, if you have a combined PDF file with pages of different sizes, you may want to resize the pages to the same size for easier reading and printing. In this article, we will introduce how to change the page size of a PDF file in Java using Spire.PDF for Java.
Install Spire.PDF for Java
First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.4.4</version> </dependency> </dependencies>
Change PDF Page Size to a Standard Paper Size in Java
The way to change the page size of a PDF file is to create a new PDF file and add pages of the desired size to it, next, create templates from the pages in the original PDF file, then draw the templates onto the pages in the new PDF file. This process will preserve text, images, and other elements present in the original PDF.
Spire.PDF for Java supports a variety of standard paper sizes like letter, legal, A0, A1, A2, A3, A4, B0, B1, B2, B3, B4 and many more. The following steps show you how to change the page size of a PDF file to a standard paper size.
- Initialize a PdfDocument instance and load the original PDF file using PdfDocument.loadFromFile() method.
- Initialize another PdfDocument instance to create a new PDF file.
- Loop through the pages in the original PDF.
- Add pages of the desired size to the new PDF file using PdfDocument.getPages().add() method.
- Initialize a PdfTextLayout instance and set the text layout as one page using PdfTextLayout.setLayout() method.
- Create templates based on the pages in the original PDF using PdfPageBase.createTemplate() method.
- Draw the templates onto the pages in the new PDF file with the specified text layout using PdfTemplate.draw() method.
- Save the result file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.PdfPageSize; import com.spire.pdf.graphics.*; import java.awt.geom.Point2D; public class ChangePageSizeToStandardPaperSize { public static void main(String []args){ //Load the original PDF document PdfDocument originPdf = new PdfDocument(); originPdf.loadFromFile("Sample.pdf"); //Create a new PDF document PdfDocument newPdf = new PdfDocument(); //Loop through the pages in the original PDF for(int i = 0; i< originPdf.getPages().getCount(); i++) { //Add pages of size A1 to the new PDF PdfPageBase newPage = newPdf.getPages().add(PdfPageSize.A1, new PdfMargins((0))); //Create a PdfTextLayout instance PdfTextLayout layout = new PdfTextLayout(); //Set text layout as one page (if not set the content will not scale to fit page size) layout.setLayout(PdfLayoutType.One_Page); //Create templates based on the pages in the original PDF PdfTemplate template = originPdf.getPages().get(i).createTemplate(); //Draw templates onto the pages in the new PDF template.draw(newPage, new Point2D.Float(0,0), layout); } //Save the result document newPdf.saveToFile("ChangePageSizeToA1.pdf"); } }
Change PDF Page Size to a Custom Paper Size in Java
Spire.PDF for Java uses point (1/72 of an inch) as the unit of measure. If you want to change the page size of a PDF to a custom paper size in other units of measure like inches or millimeters, you can use the PdfUnitConvertor class to convert them to points.
The following steps show you how to change the page size of a PDF file to a custom paper size in inches:
- Initialize a PdfDocument instance and load the original PDF file using PdfDocument.loadFromFile() method.
- Initialize another PdfDocument instance to create a new PDF file.
- Initialize a PdfUnitConvertor instance, then convert the custom size in inches to points using PdfUnitConvertor.convertUnits() method.
- Initialize a Dimension2D instance from the custom size.
- Loop through the pages in the original PDF.
- Add pages of the custom size to the new PDF file using PdfDocument.getPages().add() method.
- Create a PdfTextLayout instance and set the text layout as one page using PdfTextLayout.setLayout() method.
- Create templates based on the pages in the original PDF using PdfPageBase.createTemplate() method.
- Draw the templates onto the pages in the new PDF file with the specified text layout using PdfTemplate.draw() method.
- Save the result file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.graphics.*; import java.awt.*; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; public class ChangePageSizeToCustomPaperSize { public static void main(String []args){ //Load the original PDF document PdfDocument originPdf = new PdfDocument(); originPdf.loadFromFile("Sample.pdf"); //Create a new PDF document PdfDocument newPdf = new PdfDocument(); //Create a PdfUnitConvertor instance PdfUnitConvertor unitCvtr = new PdfUnitConvertor(); //Convert the custom size in inches to points float width = unitCvtr.convertUnits(6.5f, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point); float height = unitCvtr.convertUnits(8.5f, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point); //Create a Dimension2D instance from the custom size, then it will be used as the page size of the new PDF Dimension2D size = new Dimension(); size.setSize(width, height); //Loop through the pages in the original PDF for(int i = 0; i< originPdf.getPages().getCount(); i++) { //Add pages of the custom size (6.5*8.5 inches) to the new PDF PdfPageBase newPage = newPdf.getPages().add(size, new PdfMargins((0))); //Create a PdfTextLayout instance PdfTextLayout layout = new PdfTextLayout(); //Set text layout as one page (if not set the content will not scale to fit page size) layout.setLayout(PdfLayoutType.One_Page); //Create templates based on the pages in the original PDF PdfTemplate template = originPdf.getPages().get(i).createTemplate(); //Draw templates onto the pages in the new PDF template.draw(newPage, new Point2D.Float(0,0), layout); } //Save the result document newPdf.saveToFile("ChangePageSizeToCustomSize.pdf"); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Margins are white areas around a PDF page. In cases where you need more white space to add additional information, you can increase the margins. In some other cases, you may also have to reduce the margins. This article demonstrates how to adjust the margins of an existing PDF document using Spire.PDF for Java.
Install Spire.PDF for Java
First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.4.4</version> </dependency> </dependencies>
Increase Margins of an Existing PDF
The way to enlarge the margin of a PDF document is to create a new PDF that has a larger page size and then draw the original pages on the larger pages at the proper location. The following are the main steps to increase margins of an existing PDF document using Spire.PDF for Java.
- Load the original PDF document while initialing the PdfDocument object.
- Create another PdfDocument object, which is used to create a new PDF document that has a larger page size.
- Set the increasing values of the margins.
- Set the page size of the new PDF document.
- Loop through the pages in the original document, and create a template based on a certain page using PdfPageBase.createTemplate() method.
- Add a page to the new PDF document using PdfDocument.getPages().add() method.
- Draw the template on the page from (0, 0) using PdfTemplate.draw() method.
- Save the new PDF document to file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.graphics.PdfMargins; import com.spire.pdf.graphics.PdfTemplate; import java.awt.*; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; public class IncreaseMargins { public static void main(String[] args) { //Load the original PDF document PdfDocument originalPdf = new PdfDocument("C:\\Users\\Administrator\\Desktop\\sample.pdf"); //Get the first page PdfPageBase firstPage = originalPdf.getPages().get(0); //Create a new PdfDocument object PdfDocument newPdf = new PdfDocument(); //Set increasing value of the margins PdfMargins margins = newPdf.getPageSettings().getMargins(); margins.setTop(40); margins.setBottom(40); margins.setLeft(40); margins.setRight(40); //Set the size for the new PDF document Dimension2D dimension2D = new Dimension(); dimension2D.setSize(firstPage.getSize().getWidth() + margins.getLeft() + margins.getRight(), firstPage.getSize().getHeight() + margins.getTop() + margins.getBottom()); //Loop through the pages in the original document for (int i = 0; i < originalPdf.getPages().getCount(); i++) { //Create a template based on the source page PdfTemplate template = originalPdf.getPages().get(i).createTemplate(); //Add a page to the new PDF PdfPageBase page = newPdf.getPages().add(dimension2D); //Draw template on the page template.draw(page.getCanvas(), new Point2D.Float(0, 0)); } //Save the new document to file newPdf.saveToFile("output/IncreaseMargins.pdf", FileFormat.PDF); } }
Decrease Margins of an Existing PDF
Likewise, the way to decrease the margins of a PDF is to create a new PDF that has a smaller page size and then draw the original pages on the smaller pages at a specified coordinate. The following are the main steps to decrease margins of an existing PDF document using Spire.PDF for Java.
- Load the original PDF document while initialing the PdfDocument object.
- Create another PdfDocument object, which is used to create a new PDF document that has a smaller page size.
- Set the decreasing values of the margins.
- Set the page size of the new PDF document.
- Loop through the pages in the original document, and create a template based on a certain page using PdfPageBase.createTemplate() method.
- Add a page to the new PDF document using PdfDocument.getPages().add() method.
- Draw the template on the page at the specified position using PdfTemplate.draw() method.
- Save the new PDF document to file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.graphics.PdfMargins; import com.spire.pdf.graphics.PdfTemplate; import java.awt.*; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; public class DecreaseMargins { public static void main(String[] args) { //Load the original PDF document PdfDocument originalPdf = new PdfDocument("C:\\Users\\Administrator\\Desktop\\sample.pdf"); //Get the first page PdfPageBase firstPage = originalPdf.getPages().get(0); //Create a new PdfDocument object PdfDocument newPdf = new PdfDocument(); //Set decreasing value double left = -20; double right = -20; double top = -20; double bottom = -20; //Set the page size of the new PDF document Dimension2D dimension2D = new Dimension(); dimension2D.setSize(originalPdf.getPages().get(0).getSize().getWidth() + left + right, originalPdf.getPages().get(0).getSize().getHeight() + top + bottom); //Loop through the pages in the original document for (int i = 0; i < originalPdf.getPages().getCount(); i++) { //Create template based on the source page PdfTemplate template = originalPdf.getPages().get(i).createTemplate(); //Add a page to the new PDF PdfPageBase page = newPdf.getPages().add(dimension2D, new PdfMargins(0)); //Draw template on the page template.draw(page.getCanvas(), new Point2D.Float((float) left, (float) top)); } //Save the new document to file newPdf.saveToFile("output/DecreaseMargins.pdf", FileFormat.PDF); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Spire.PDF for java offers PdfDocument.split() method to split one PDF document to multiple files by pages. In this article, we will demonstrate how to horizontally or vertically split a single PDF page into multiple pages in Java by using Spire.PDF for Java.
Install Spire.PDF for Java
First of all, you need to add the Spire.PDF.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.4.4</version> </dependency> </dependencies>
Split a PDF Page into multiple Pages
Spire.PDF for Java offers PdfPageBase.createTemplate().draw() method to draw the content of a source page on a new PDF page. Splitting a page into multiple pages actually means that the content of the source page will be drew on multiple smaller pages. The following are the main steps to split the first page into two pages:
- Create an object of PdfDocument class and load a sample PDF document using PdfDocument.loadFromFile() method.
- Get the desired page of PDF using PdfDocument.getPages().get() method.
- Create a new PDF document and set the page margins to 0.
- Set the page size of the new PDF to half or a fraction of that of the original.
- Add a new page to the new PDF document using PdfDocument.getPages().add() method.
- Draw content of source page on the new page using PdfPageBase.createTemplate().draw() method.
- Save the document to another file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.*; import com.spire.pdf.graphics.*; import java.awt.geom.Point2D; public class SplitPDF { public static void main(String[] args) throws Exception { //Create an object of PdfDocument class. PdfDocument pdf = new PdfDocument(); //Load the sample PDF document pdf.loadFromFile("Sample.pdf"); //Get the first page of PDF PdfPageBase page = pdf.getPages().get(0); //Create a new PDF document and remove page margins PdfDocument newPdf = new PdfDocument(); newPdf.getPageSettings().getMargins().setAll(0); //Horizontally Split newPdf.getPageSettings().setWidth((float) page.getSize().getWidth()); newPdf.getPageSettings().setHeight((float) page.getSize().getHeight()/2); ////Vertically Split //newPdf.getPageSettings().setWidth((float) page.getSize().getWidth()/2); //newPdf.getPageSettings().setHeight((float) page.getSize().getHeight()); // Add a new page to the new PDF document PdfPageBase newPage = newPdf.getPages().add(); //Set the PdfLayoutType to Paginate to make the content paginated automatically PdfTextLayout layout = new PdfTextLayout(); layout.setBreak(PdfLayoutBreakType.Fit_Page); layout.setLayout(PdfLayoutType.Paginate); //Draw the content of source page in the new page page.createTemplate().draw(newPage, new Point2D.Float(0, 0), layout); //Save the Pdf document newPdf.saveToFile("SplitPDF.pdf"); newPdf.close(); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
If you are going to print or share a PDF document, it’s better to check if there are blank pages in the document, because they will lead to a waste of paper and a less professional look for your document. However, it will take much time to look through every page to find the empty pages and then delete them. A better way to deal with this problem is to use Spire.PDF for Java. In this article, you will learn how to use Spire.PDF for Java to find and remove blank pages from PDF document easily by programming.
Install Spire.PDF for Java
First, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.4.4</version> </dependency> </dependencies>
Find and Delete Blank Pages from a PDF Document
Spire.PDF for Java provides a method PdfPageBase.isBlank() to detect if a PDF page is absolutely blank. But some pages that look blank actually contain white images, these pages won't be deemed as blank using the PdfPageBase.isBlank() method. Therefore, it is necessary create a custom method isBlankImage() to be used in conjunction with PdfPageBase.isBlank() method to detect blank and white but non-blank pages.
Note: This solution will convert PDF pages into images and detect if an image is blank. It is necessary to apply a license to remove the evaluation message in the converted images. Otherwise, this method won't work properly. If you do not have a license, contact sales@e-iceblue.com for a temporary one for evaluation purpose.
The detailed steps are as follows:
- Create an object of PdfDocument class.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Loop through the pages in the PDF document to detect if the pages are blank using PdfPageBase.isBlank() method.
- For absolutely blank pages, delete them using PdfDocument.getPages().remove() method.
- For pages that are not absolutely blank, save them as images using PdfDocument.saveAsImage() method, detect if the converted images are blank using custom method isBlankImage() and then remove the pages that are “balnk” using PdfDocument.getPages().remove().
- Save the result document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.graphics.PdfImageType; import java.awt.*; import java.awt.image.BufferedImage; public class removeBlankPages { public static void main(String []args){ //Create a PdfDocument class instance PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.loadFromFile("C:/Sample.pdf"); BufferedImage image; //Loop through pages in the PDF for(int i = pdf.getPages().getCount()-1; i>=0; i--) { PdfPageBase page = pdf.getPages().get(i); //Detect if a page is blank if(page.isBlank()) { //Remove the absolutely blank page pdf.getPages().remove(page); } else { //Save PDF page as image image = pdf.saveAsImage(i, PdfImageType.Bitmap); //Detect if the converted image is blank if (isBlankImage(image)) { //Remove the page pdf.getPages().remove(page); } } } //Save the result document pdf.saveToFile("RemoveBlankPages.pdf"); } //Detect if an image is blank public static boolean isBlankImage(BufferedImage image) { BufferedImage bufferedImage = image; Color pixel; for (int i = 0; i < bufferedImage.getWidth(); i++) { for (int j = 0; j < bufferedImage.getHeight(); j++) { pixel = new Color(bufferedImage.getRGB(i, j)); if (pixel.getRed() < 240 || pixel.getGreen() < 240 || pixel.getBlue() < 240) { return false; } } } return true; } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
When you receive a PDF file with pages out of order, you may need to change the page order for a better viewing experience. In this article, you will learn how to programmatically rearrange pages in a PDF file using Spire.PDF for Java.
Install Spire.PDF for Java
First of all, you're required to add the Spire.PDF.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.4.4</version> </dependency> </dependencies>
Rearrange Pages in PDF
The PdfDocument.getPages().reArrange() method offered by Spire.PDF for Java allows you to change the PDF page order quickly and effortlessly. The detailed steps are as follows.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.loadFromFile() method.
- Rearrange the pages using PdfDocument.getPages().reArrange() method.
- Save the document to another file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; public class RearrangePages { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Load a sample PDF file doc.loadFromFile("input.pdf"); //Rearrange pages by setting a new page order doc.getPages().reArrange(new int[]{0, 2, 1, 3}); //Save the document to another file doc.saveToFile("ChangeOrder.pdf"); doc.close(); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java set the viewer preference and zoom factor for PDF
2020-12-17 08:03:39 Written by support iceblueThis article will demonstrate how to set the zoom factor/percentage (such as default, 100 percent or any other zoom factors as required) and the viewer preference by using Spire.PDF for Java in Java applications.
Set the zoom factor
import com.spire.pdf.*; import com.spire.pdf.actions.*; import com.spire.pdf.general.*; import java.awt.geom.*; public class setZoomFactor { public static void main(String[] args) { //Load the sample document PdfDocument doc = new PdfDocument(); doc.loadFromFile("Sample.pdf"); //Get the first page of PDF PdfPageBase page = doc.getPages().get(0); //Set pdf destination PdfDestination dest = new PdfDestination(page); dest.setMode(PdfDestinationMode.Location); dest.setLocation(new Point2D.Float(-40f, -40f)); //Set zoom factor dest.setZoom(0.8f); //Set action PdfGoToAction gotoAction = new PdfGoToAction(dest); doc.setAfterOpenAction(gotoAction); //Save pdf document String output = "output/setZoomFactor.pdf"; doc.saveToFile(output); } }
Output:
Set the viewer preference
import com.spire.pdf.*; public class viewerPreference { public static void main(String[] args) { //Load the sample document PdfDocument doc = new PdfDocument(); doc.loadFromFile("Sample.pdf"); //Set viewer reference doc.getViewerPreferences().setCenterWindow(true); doc.getViewerPreferences().setDisplayTitle(false); doc.getViewerPreferences().setFitWindow(false); doc.getViewerPreferences().setHideMenubar(true); doc.getViewerPreferences().setHideToolbar(true); doc.getViewerPreferences().setPageLayout(PdfPageLayout.Two_Column_Left); //Save pdf document String output = "output/viewerPreference.pdf"; doc.saveToFile(output); } }
Output:
Spire.PDF for Java supports detecting the orientation of a PDF page by comparing the value of page width and page height. This article shows how to use Spire.PDF for Java to accomplish this function.
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; public class DetectPageOrientation { public static void main(String[] args){ //Load PDF file PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("Fields.pdf"); //Get the first page PdfPageBase page = pdf.getPages().get(0); //Compare the value of page width and height if (page.getSize().getWidth()> page.getSize().getHeight()){ System.out.println("The page orientation is Landscape"); } else{ System.out.println("The page orientation is Portrait"); } } }
Output
Page numbers provide clarity and structure to the content, making it easier for readers to navigate through the document. By including page numbers, readers can quickly locate specific information or refer to a specific page. Adding page numbers to a PDF document is a common requirement when creating professional and organized files. Whether you're working on a report, a thesis, or any other type of PDF document, incorporating page numbers enhances the overall readability and professionalism of your work.
In this article, you will learn how to add page numbers to a PDF document at the footer section using Spire.PDF for Java.
- Add Page Numbers to the Left Corner of PDF Footer
- Add Page Numbers to the Center of PDF Footer
- Add Page Numbers to the Right Corner of PDF Footer
Install Spire.PDF for Java
You're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.4.4</version> </dependency> </dependencies>
PDF Coordinate System
When using Spire.PDF for Java to manipulate an existing PDF document, the coordinate system's origin is positioned at the top left corner of the page. The x-axis extends to the right, while the y-axis extends downward.
In general, page numbers are commonly positioned in the header or footer section of a document. As a result, it is important to consider the page size and margins when deciding where to place the page numbers.
Add Page Numbers to the Left Corner of PDF Footer in Java
Spire.PDF for Java offers the PdfPageNumberField class and the PdfPageCountField class, which reflect the current page number and the total page count when added to a page of a PDF document. To insert a piece of text like "Page X" or "Page X of Y", you can use a PdfCompositeField object to combine the text with one or more fields into a single field.
To add "Page X of Y" to the left corner of PDF footer, follow the steps below.
- Create a Document object.
- Load a PDF file from a specified page.
- Create a PdfPageNumberField object and a PdfPageCountField object.
- Create a PdfCompositeField object to create a "Page X of Y" format.
- Specify the location of the PdfCompositeField object using PdfCompositeField.setLocation() method.
- Iterate though the pages in the document, and add "Page X of Y" to the left corner of the footer section using PdfCompositeField.draw() method.
- Save the document to a different PDF file.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.automaticfields.PdfCompositeField; import com.spire.pdf.automaticfields.PdfPageCountField; import com.spire.pdf.automaticfields.PdfPageNumberField; import com.spire.pdf.graphics.*; import com.spire.pdf.license.LicenseProvider; import java.awt.*; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; public class AddPageNumberToLeftCorner { public static void main(String[] args) { // Apply your license key LicenseProvider.setLicenseKey("License Key"); // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf"); // Create font, brush and pen, which determine the appearance of the page numbers to be added PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12),true); PdfBrush brush = PdfBrushes.getBlack(); PdfPen pen = new PdfPen(brush, 1.0); // Create a PdfPageNumberField object and a PdfPageCountField object PdfPageNumberField pageNumberField = new PdfPageNumberField(); PdfPageCountField pageCountField = new PdfPageCountField(); // Create a PdfCompositeField object to combine page count field and page number field in a single field PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField); // Get the page size Dimension2D pageSize = doc.getPages().get(0).getSize(); // Set the location of the composite field compositeField.setLocation(new Point2D.Float(72, (float) pageSize.getHeight() - 45)); // Iterate through the pages in the document for (int i = 0; i < doc.getPages().getCount(); i++) { // Get a specific page PdfPageBase page = doc.getPages().get(i); // Draw a line at the specified position page.getCanvas().drawLine(pen, 72, pageSize.getHeight() - 50, pageSize.getWidth() - 72, pageSize.getHeight() - 50); // Draw the composite field on the page compositeField.draw(page.getCanvas(), 0.0, 0.0); } // Save to a different PDF file doc.saveToFile("Output/AddPageNumbersToLeftCorner.pdf"); // Dispose resources doc.dispose(); } }
Add Page Numbers to the Center of PDF Footer in Java
To center-align the page number in the footer section, it is necessary to dynamically calculate the width of the text "Page X of Y." This calculation is important because the X coordinate of the page number (PdfCompositeField) will be determined by subtracting the width of the page number from the page width and then dividing the result by 2, i.e., (PageWidth - PageNumberWidth)/2.
The steps to add page numbers to the center of PDF footer are as follows.
- Create a Document object.
- Load a PDF file from a specified page.
- Create a PdfPageNumberField object and a PdfPageCountField object.
- Create a PdfCompositeField object to create a "Page X of Y" format.
- Specify the location of the PdfCompositeField object using PdfCompositeField.setLocation() method.
- Iterate though the pages in the document, and add "Page X of Y" to the center of the footer section using PdfCompositeField.draw() method.
- Save the document to a different PDF file.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.automaticfields.PdfCompositeField; import com.spire.pdf.automaticfields.PdfPageCountField; import com.spire.pdf.automaticfields.PdfPageNumberField; import com.spire.pdf.graphics.PdfBrush; import com.spire.pdf.graphics.PdfBrushes; import com.spire.pdf.graphics.PdfPen; import com.spire.pdf.graphics.PdfTrueTypeFont; import com.spire.pdf.license.LicenseProvider; import java.awt.*; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; public class AddPageNumberToCenter { public static void main(String[] args) { // Apply your license key LicenseProvider.setLicenseKey("License Key"); // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf"); // Create font, brush and pen, which determine the appearance of the page numbers to be added PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12),true); PdfBrush brush = PdfBrushes.getBlack(); PdfPen pen = new PdfPen(brush, 1.0); // Create a PdfPageNumberField object and a PdfPageCountField object PdfPageNumberField pageNumberField = new PdfPageNumberField(); PdfPageCountField pageCountField = new PdfPageCountField(); // Create a PdfCompositeField object to combine page count field and page number field in a single field PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField); // Iterate through the pages in the document for (int i = 0; i < doc.getPages().getCount(); i++) { // Get a specific page PdfPageBase page = doc.getPages().get(i); // Get the page size Dimension2D pageSize = doc.getPages().get(i).getSize(); // Draw a line at the specified position page.getCanvas().drawLine(pen, 72, pageSize.getHeight() - 50, pageSize.getWidth() - 72, pageSize.getHeight() - 50); // Measure the size the "Page X of Y" Dimension2D pageNumberSize = font.measureString(String.format("Page %d of %d", i + 1, doc.getPages().getCount())); // Set the location of the composite field compositeField.setLocation(new Point2D.Float((float)(pageSize.getWidth() - pageNumberSize.getWidth())/2, (float)pageSize.getHeight() - 45)); // Draw the composite field on the page compositeField.draw(page.getCanvas()); } // Save to a different PDF file doc.saveToFile("Output/AddPageNumbersToCenter.pdf"); // Dispose resources doc.dispose(); } }
Add Page Numbers to the Right Corner of PDF Footer in Java
To position the page number at the right corner of the footer section, it is necessary to dynamically calculate the width of the text "Page X of Y" as well. Because the X coordinate of the page number (PdfCompositeField) will be determined by subtracting the width of the page number and the right page margin from the page width, i.e., PageWidth - PageNumberWidth - RightPageMargin.
The steps to add page numbers to the right corner of PDF footer are as follows.
- Create a Document object.
- Load a PDF file from a specified page.
- Create a PdfPageNumberField object and a PdfPageCountField object.
- Create a PdfCompositeField object to create a "Page X of Y" format.
- Specify the location of the PdfCompositeField object using PdfCompositeField.setLocation() method.
- Iterate though the pages in the document, and add "Page X of Y" to the right corner of the footer section using PdfCompositeField.draw() method.
- Save the document to a different PDF file.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.automaticfields.PdfCompositeField; import com.spire.pdf.automaticfields.PdfPageCountField; import com.spire.pdf.automaticfields.PdfPageNumberField; import com.spire.pdf.graphics.PdfBrush; import com.spire.pdf.graphics.PdfBrushes; import com.spire.pdf.graphics.PdfPen; import com.spire.pdf.graphics.PdfTrueTypeFont; import com.spire.pdf.license.LicenseProvider; import java.awt.*; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; public class AddPageNumberToRightCorner { public static void main(String[] args) { // Apply your license key LicenseProvider.setLicenseKey("License Key"); // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf"); // Create font, brush and pen, which determine the appearance of the page numbers to be added PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12),true); PdfBrush brush = PdfBrushes.getBlack(); PdfPen pen = new PdfPen(brush, 1.0); // Create a PdfPageNumberField object and a PdfPageCountField object PdfPageNumberField pageNumberField = new PdfPageNumberField(); PdfPageCountField pageCountField = new PdfPageCountField(); // Create a PdfCompositeField object to combine page count field and page number field in a single field PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField); // Iterate through the pages in the document for (int i = 0; i < doc.getPages().getCount(); i++) { // Get a specific page PdfPageBase page = doc.getPages().get(i); // Get the page size Dimension2D pageSize = doc.getPages().get(i).getSize(); // Draw a line at the specified position page.getCanvas().drawLine(pen, 72, pageSize.getHeight() - 50, pageSize.getWidth() - 72, pageSize.getHeight() - 50); // Measure the size the "Page X of Y" Dimension2D pageNumberSize = font.measureString(String.format("Page %d of %d", i + 1, doc.getPages().getCount())); // Set the location of the composite field compositeField.setLocation(new Point2D.Float((float)(pageSize.getWidth() - pageNumberSize.getWidth() - 72), (float)(pageSize.getHeight() - 45))); // Draw the composite field on the page compositeField.draw(page.getCanvas()); } // Save to a different PDF file doc.saveToFile("Output/AddPageNumbersToRightCorner.pdf"); // Dispose resources doc.dispose(); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Some scanned PDF documents may contain pages displayed in the wrong orientation (e.g., upside-down), which could cause great inconvenience while reading. Rotating pages can help you solve this problem and provide readers with a better reading experience. This article will introduce how to rotate pages in PDF in Java using Spire.PDF for Java.
Install Spire.PDF for Java
First, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.4.4</version> </dependency> </dependencies>
Rotate a Specific Page in PDF in Java
Rotation is based on 90-degree increments. You can rotate a PDF page by 0/90/180/270 degrees. The following are the steps to rotate a PDF page:
- Create an instance of PdfDocument class.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Get the desired page by its index (zero-based) using PdfDocument.getPages().get(pageIndex) method.
- Get the original rotation angle of the page using PdfPageBase.getRotation().getValue() method.
- Increase the original rotation angle by desired degrees.
- Apply the new rotation angle to the page using PdfPageBase.setRotation() method.
- Save the result document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.PdfPageRotateAngle; public class RotatePdfPage { public static void main(String []args){ //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.loadFromFile("Sample.pdf"); //Get the first page PdfPageBase page = pdf.getPages().get(0); //Get the original rotation angle of the page int rotation = page.getRotation().getValue(); //Rotate the page 180 degrees clockwise based on the original rotation angle rotation += PdfPageRotateAngle.Rotate_Angle_180.getValue(); page.setRotation(PdfPageRotateAngle.fromValue(rotation)); //Save the result document pdf.saveToFile("Rotate.pdf"); } }
Rotate All Pages in PDF in Java
The following are the steps to rotate all pages in a PDF document:
- Create an instance of PdfDocument class.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Loop through the pages in the document.
- Get the original rotation angle of each page using PdfPageBase.getRotation().getValue() method.
- Increase the original rotation angle by desired degrees.
- Apply the new rotation angle to the page using PdfPageBase.setRotation() method.
- Save the result document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.PdfPageRotateAngle; public class RotateAllPdfPages { public static void main(String []args){ //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.loadFromFile("Sample.pdf"); //Loop through each page in the document for(PdfPageBase page :(Iterable) pdf.getPages()) { //Get the original rotation angle of the page int rotation = page.getRotation().getValue(); //Rotate the page 180 degrees clockwise based on the original rotation angle rotation += PdfPageRotateAngle.Rotate_Angle_180.getValue(); page.setRotation(PdfPageRotateAngle.fromValue(rotation)); } //Save the result document pdf.saveToFile("RotateAll.pdf"); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java: Set the Background Color or Background Image for PDF
2023-06-19 09:11:00 Written by support iceblueProper backgrounds can make different content elements of PDF documents better matched and improve the visual impression and reading experience of PDF documents. Besides, it's important to add different backgrounds to PDF documents for different usage scenarios to enhance the professionalism of the documents. This article will show how to use Spire.PDF for Java to set the background color and background image for PDF documents.
Install Spire.PDF for Java
First, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.4.4</version> </dependency> </dependencies>
Add Background Color to PDF Documents in Java
As setting the background of a PDF document needs to be done page by page, we can loop through all the pages in the document and use the PdfPageBase.setBackgroundColor() method to set the background color for each page. The following are the detailed steps:
- Create an object of PdfDocument.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Loop through the pages in the PDF document and add a background color to each page using PdfPageBase.setBackgroundColor() method. You can also use the PdfPageBase.setBackgroudOpacity() method to set the opacity of the background.
- Save the document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import java.awt.*; public class SetPDFBackgroundColor { public static void main(String[] args) { //Create an object of PdfDocument PdfDocument pdf = new PdfDocument(); //Load a PDF file pdf.loadFromFile("Sample.pdf"); //Loop through the pages in the PDF file for (PdfPageBase page : (Iterable) pdf.getPages() ) { //Set the background color for each page page.setBackgroundColor(Color.PINK); //Set the opacity of the background page.setBackgroudOpacity(0.2f); } //Save the PDF file pdf.saveToFile("BackgroundColor.pdf"); } }
Add Background Picture to PDF Documents in Java
Spire.PDF for Java provides the PdfPageBase.setBackgroundImage() to set a picture as the PDF page background. The detailed steps for adding an image background to a PDF document are as follows:
- Create an object of PdfDocument.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Loop through the pages in the PDF document and add a background picture to each page using PdfPageBase.setBackgroundImage() method. You can also use the PdfPageBase.setBackgroudOpacity() method to set the opacity of the background.
- Save the document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class SetPDFBackgroundImage { public static void main(String[] args) throws IOException { //Create an object of PdfDocument PdfDocument pdf = new PdfDocument(); //Load a PDF file pdf.loadFromFile("Sample.pdf"); //Load an image BufferedImage background = ImageIO.read(new File("background.jpg")); //Loop through the pages in the PDF file for (PdfPageBase page : (Iterable) pdf.getPages() ) { //Set the loaded image as the background image of a page page.setBackgroundImage(background); //Set the opacity of the background page.setBackgroudOpacity(0.2f); } //Save the PDF file pdf.saveToFile("BackgroundImage.pdf"); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.