Java: Add, Hide or Delete Layers in PDF
PDF layers are supported through the usage of Optional Content Group (OCG) objects. As its name implies, optional content refers to the content in a PDF document that can be made visible or invisible dynamically by the user of PDF viewer applications. In this article, you will learn how to programmatically add, hide or delete layers in a PDF file using Spire.PDF for Java.
- Add Layers to a PDF Document in Java
- Set Visibility of Layers in a PDF Document in Java
- Delete Layers in a PDF Document in 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.10.7</version> </dependency> </dependencies>
Add Layers to a PDF Document in Java
Spire.PDF for Java provides PdfDocument.getLayers().addLayer() method to add a layer in a PDF document, and you can then draw text, lines, images or shapes on the PDF layer. The detailed steps are as follows.
- Create a PdfDocument instance.
- Load a sample PDF file using PdfDocument.loadFromFile() method.
- Add a layer with specified name in the PDF using PdfDocument.getLayers().addLayer(java.lang.String name) method. Or you can also set the visibility of the layer while adding it using PdfDocument. getLayers().addLayer(java.lang.String name, PdfVisibility state) method.
- Create a canvas for the layer using PdfLayer.createGraphics() method.
- Draw text, image or other elements on the canvas.
- Save the result document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.graphics.*; import com.spire.pdf.graphics.layer.PdfLayer; import java.awt.*; import java.awt.geom.Dimension2D; import java.io.IOException; public class AddLayersToPdf { public static void main(String[] args) throws IOException { //Create a PdfDocument instance and load the sample PDF file PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf"); //Invoke AddLayerWatermark method to add a watermark layer AddLayerWatermark(pdf); //Invoke AddLayerHeader method to add a header layer AddLayerHeader(pdf); //Save to file pdf.saveToFile("AddLayers.pdf"); pdf.close(); } private static void AddLayerWatermark(PdfDocument doc) throws IOException { //Create a layer named "watermark" PdfLayer layer = doc.getLayers().addLayer("Watermark"); //Create a font PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,48),true); //Specify watermark text String watermarkText = "CONFIDENTIAL"; //Get text size Dimension2D fontSize = font.measureString(watermarkText); //Calculate two offsets float offset1 = (float)(fontSize.getWidth() * Math.sqrt(2) / 4); float offset2 = (float)(fontSize.getHeight() * Math.sqrt(2) / 4); //Get page count int pageCount = doc.getPages().getCount(); //Declare two variables PdfPageBase page; PdfCanvas canvas; //Loop through the pages for (int i = 0; i < pageCount; i++) { page = doc.getPages().get(i); //Create a canvas from layer canvas = layer.createGraphics(page.getCanvas()); canvas.translateTransform(canvas.getSize().getWidth() / 2 - offset1 - offset2, canvas.getSize().getHeight() / 2 + offset1 - offset2); canvas.setTransparency(0.4f); canvas.rotateTransform(-45); //Draw sting on the canvas of layer canvas.drawString(watermarkText, font, PdfBrushes.getDarkBlue(), 0, 0); } } private static void AddLayerHeader(PdfDocument doc) { //Create a layer named "header" PdfLayer layer = doc.getLayers().addLayer("Header"); //Get page size Dimension2D size = doc.getPages().get(0).getSize(); //Specify the initial values of X and y float x = 90; float y = 40; //Get page count int pageCount = doc.getPages().getCount(); //Declare two variables PdfPageBase page; PdfCanvas canvas; //Loop through the pages for (int i = 0; i < pageCount; i++) { //Draw an image on the layer PdfImage pdfImage = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\img.jpg"); float width = pdfImage.getWidth(); float height = pdfImage.getHeight(); page = doc.getPages().get(i); canvas = layer.createGraphics(page.getCanvas()); canvas.drawImage(pdfImage, x, y, width, height); //Draw a line on the layer PdfPen pen = new PdfPen(PdfBrushes.getDarkGray(), 2f); canvas.drawLine(pen, x, y + height + 5, size.getWidth() - x, y + height + 2); } } }
Set Visibility of Layers in a PDF Document in Java
To set the visibility of an existing layer, you'll need to get a specified layer by its index or name using PdfDocument.getLayers().get() method, and then show or hide the layer using PdfLayer.setVisibility(PdfVisibility value) method. The detailed steps are as follows.
- Create a PdfDocument instance.
- Load a sample PDF document using PdfDocument.loadFromFile() method.
- Set the visibility of a specified layer using PdfDocument.getLayers().get().setVisibility() method.
- Save the result document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.graphics.layer.PdfVisibility; public class SetLayerVisibility { public static void main(String[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample PDF file pdf.loadFromFile("AddLayers.pdf"); //Set the visibility of the first layer to off pdf.getLayers().get(0).setVisibility(PdfVisibility.Off); //Save to file pdf.saveToFile("HideLayer.pdf", FileFormat.PDF); pdf.dispose(); } }
Delete Layers in a PDF Document in Java
Spire.PDF for Java also allows you to remove an existing layer by its name using PdfDocument.getLayers().removeLayer(java.lang.String name) method. But kindly note that the names of PDF layers may not be unique and this method will remove all PDF layers with the same name. The detailed steps are as follows.
- Create a PdfDocument instance.
- Load a sample PDF document using PdfDocument.LoadFromFile() method.
- Delete a specified layer by its name using PdfDocument.getLayers().removeLayer() method.
- Save the result document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; public class DeleteLayers { public static void main(String[] args) { //Create a PdfDocument object and load the sample PDF file PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("AddLayers.pdf"); //Delete the specific layer by its name pdf.getLayers().removeLayer("Watermark"); //Save to file pdf.saveToFile("DeleteLayer.pdf"); pdf.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.
Set custom properties for PDF files in Java
We have already demonstrated how to set PDF Document Properties in Java. This article we will show you how to set custom properties for PDF files in Java.
import com.spire.pdf.*; public class PDFCustomProperties { public static void main(String[] args) throws Exception { String inputPath = "Sample.pdf"; PdfDocument doc = new PdfDocument(inputPath); doc.loadFromFile(inputPath); //Set the custom properties doc.getDocumentInformation().setCustomerDefined("Number", "123"); doc.getDocumentInformation().setCustomerDefined("Name", "Daisy"); doc.getDocumentInformation().setCustomerDefined("Company", "e-iceblue"); //Save the document to file doc.saveToFile("Output/result.pdf"); doc.close(); } }
Effective screenshot after adding custom properties to PDF document:
Java: Reduce the Size of a PDF Document
PDFs are a popular file format for sharing and storing documents, but they can sometimes be quite large. This makes them difficult to upload or send via email, especially if you're dealing with slow internet speeds or limited storage space. Fortunately, there is a solution: compressing your PDF documents. Compressing a PDF can reduce its file size without sacrificing quality, making it easier to share and store your important files. In this article, you will learn how to reduce the size of a PDF document 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.10.7</version> </dependency> </dependencies>
Compress Fonts and Images in a PDF Document in Java
Fonts and high-quality images are two main factors that contribute to the size of a PDF document. To reduce the PDF document size, you can compress the font resources and the image quality. The following are the steps to compress a PDF document using Spire.PDF for Java.
- Load a PDF document while initializing the PdfCompressor object.
- Get text compression options using PdfCompressor.getOptions().getTextCompressionOptions() method.
- Compress font resources using TextCompressionOptions.setCompressFonts() method.
- Get image compression options using PdfCompressor.getOptions().getImageCompressionOptions() method.
- Set the image compression level using ImageCompressionOptions.setImageQuality() method.
- Compress images using ImageCompressionOptions.setCompressImage() method.
- Save the compressed document to file using PdfCompressor.compressToFile() method.
- Java
import com.spire.pdf.conversion.compression.ImageCompressionOptions; import com.spire.pdf.conversion.compression.ImageQuality; import com.spire.pdf.conversion.compression.PdfCompressor; import com.spire.pdf.conversion.compression.TextCompressionOptions; public class CompressPdfDocument { public static void main(String[] args) { //Load a PDF document while initializing the PdfCompressor object PdfCompressor compressor = new PdfCompressor("C:\\Users\\Administrator\\Desktop\\ToCompress.pdf"); //Get text compression options TextCompressionOptions textCompression = compressor.getOptions().getTextCompressionOptions(); //Compress fonts textCompression.setCompressFonts(true); //Unembed fonts //textCompression.setUnembedFonts(true); //Get image compression options ImageCompressionOptions imageCompression = compressor.getOptions().getImageCompressionOptions(); //Set the compressed image quality imageCompression.setImageQuality(ImageQuality.Low); //Resize images imageCompression.setResizeImages(true); //Compress images imageCompression.setCompressImage(true); //Save the compressed document to file compressor.compressToFile("output/Compressed.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: Add or Delete Pages in PDF Documents
When you edit a PDF document, it is sometimes necessary to delete redundant pages of the document or add new pages to the document. This article will show you how to add or delete pages in a 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.10.7</version> </dependency> </dependencies>
Add Empty Pages to a PDF Document
The following steps show you how to add empty pages to a specific position of a PDF document and its end.
- Create a PdfDocument instance.
- Load a sample PDF document using PdfDocument.loadFromFile() method.
- Create a new blank page and insert it into a specific position of the document using PdfDocument.getPages().insert(int index) method.
- Create another new blank page with the specified size and margins and then append it to the end of the document using PdfDocument.getPages().add(java.awt.geom.Dimension2D size, PdfMargins margins) method.
- Save the document to another file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.*; import com.spire.pdf.graphics.PdfMargins; public class InsertEmptyPage { public static void main(String[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample PDF document pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.pdf"); //Insert a blank page to the document as the second page pdf.getPages().insert(1); //Add an empty page to the end of the document pdf.getPages().add(PdfPageSize.A4, new PdfMargins(0, 0)); //Save the document to another file pdf.saveToFile("output/insertEmptyPage.pdf"); pdf.close(); } }
Delete an Existing Page in a PDF Document
The following steps are to delete a specific page of a PDF document.
- Create a PdfDocument instance.
- Load a sample PDF document using PdfDocument.loadFromFile() method.
- Remove a specific page of the document using PdfDocument.getPages().removeAt(int index) method.
- Save the document to another file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.*; public class DeletePage { public static void main(String[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample PDF document pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.pdf"); //Delete the second page of the document pdf.getPages().removeAt(1); //Save the document to another file pdf.saveToFile("output/deletePage.pdf"); pdf.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 PDF Viewer Preferences
Preserving and displaying documents precisely is a primary function of PDF. However, the viewing preference settings of different devices and users would still affect the display of PDF documents. To solve this problem, PDF provides the viewer preference entry in a document to control the way the PDF document presents on screen. Without it, PDF documents will display according to the current user’s preference setting. This article will show how to set PDF viewer preferences by programming 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.10.7</version> </dependency> </dependencies>
Set Viewer Preferences of a PDF Document
Spire.PDF for Java includes several methods under PdfViewerPreferences class, which can decide whether to center the window, display title, fit the window, and hide menu bar as well as tool bar and set page layout, page mode, and scaling mode. The detailed steps of setting viewer preferences are as follows.
- Create an object of PdfDocument class.
- Load a PDF file using PdfDocument.loadFromFile() method.
- Get viewer preferences of the document using PdfDocument.getViewerPreferences() method.
- Set the viewer preferences using the methods under PdfViewerPreferences object.
- Save the file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.*; public class setViewerPreference { public static void main(String[] args) { //Create an object of PdfDocument class PdfDocument pdf = new PdfDocument(); //Load a PDF file pdf.loadFromFile("C:/Sample3.pdf"); //Get viewer preferences of the document PdfViewerPreferences preferences = pdf.getViewerPreferences(); //Set viewer preferences preferences.setCenterWindow(true); preferences.setDisplayTitle(false); preferences.setFitWindow(true); preferences.setHideMenubar(true); preferences.setHideToolbar(true); preferences.setPageLayout(PdfPageLayout.Single_Page); //preferences.setPageMode(PdfPageMode.Full_Screen); //preferences.setPrintScaling(PrintScalingMode.App_Default); //Save the file pdf.saveToFile("SetViewerPreference.pdf"); pdf.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 or Retrieve PDF Properties
PDF properties, as a part of a PDF document, are not shown on a page. Those properties contain information on documents, including title, author, subject, keywords, creation date, and creator. Some of the property values will not be produced automatically, and we have to set them by ourselves. This article will show you how to set or retrieve PDF properties programmatically 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.10.7</version> </dependency> </dependencies>
Set Properties of a PDF Document in Java
The detailed steps of setting PDF properties are as follows.
- Create an object of PdfDocument class.
- Load a PDF document from disk using PdfDocument.loadFromFile() method.
- Set document properties including title, author, subject, keywords, creation date, modification date, creator, and producer using the methods under DocumentInformation object returned by PdfDocument.getDocumentInformation() method.
- Save the document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.*; import java.util.Date; public class setPDFProperties { public static void main(String[] args) { //Create an object of PdfDocument PdfDocument pdfDocument = new PdfDocument(); //Load a PDF document from disk pdfDocument.loadFromFile("D:/Samples/Sample.pdf"); //Set the title pdfDocument.getDocumentInformation().setTitle("PDF(Portable Document Format)"); //Set the author pdfDocument.getDocumentInformation().setAuthor("John"); //Set the subject pdfDocument.getDocumentInformation().setSubject("Introduction of PDF"); //Set the keywords pdfDocument.getDocumentInformation().setKeywords("PDF, document format"); //Set the creation time pdfDocument.getDocumentInformation().setCreationDate(new Date()); //Set the creator name pdfDocument.getDocumentInformation().setCreator("John"); //Set the modification time pdfDocument.getDocumentInformation().setModificationDate(new Date()); //Set the producer name pdfDocument.getDocumentInformation().setProducer("Spire.PDF for Java"); //Save the document pdfDocument.saveToFile("output/setPDFProperties.pdf"); } }
Get Properties of a PDF Document in Java
The detailed steps of retrieving PDF properties are as follows.
- Create an object of PdfDocument class.
- Load a PDF document from disk using PdfDocument.loadFromFile() method.
- Create a StringBuilder instance to store the values of document properties.
- Get properties using the methods under DocumentInformation object returned by PdfDocument.getDocumentInformation() method and put them in the StringBuilder.
- Create a new TXT file using File.createNewFile() method.
- Write the StringBuilder to the TXT file using BufferedWriter.write() method.
- Java
import com.spire.pdf.*; import java.io.*; public class getPDFProperties { public static void main(String[] args) throws IOException { //Create an object of PdfDocument class PdfDocument pdf = new PdfDocument(); //Load a PDF document from disk pdf.loadFromFile("D:/Samples/Sample.pdf"); //Create a StringBuilder instance to store the values of document properties StringBuilder stringBuilder = new StringBuilder(); //Retrieve property values and put them in the StringBuilder stringBuilder.append("Title: " + pdf.getDocumentInformation().getTitle() + "\r\n"); stringBuilder.append("Author: " + pdf.getDocumentInformation().getAuthor() + "\r\n"); stringBuilder.append("Subject: " + pdf.getDocumentInformation().getSubject() + "\r\n"); stringBuilder.append("Keywords: " + pdf.getDocumentInformation().getKeywords() + "\r\n"); stringBuilder.append("Creator: " + pdf.getDocumentInformation().getCreator() + "\r\n"); stringBuilder.append("Creation Date: " + pdf.getDocumentInformation().getCreationDate() + "\r\n"); stringBuilder.append("Producer: " + pdf.getDocumentInformation().getProducer() + "\r\n"); //Create a new TXT file File file = new File("D:/output/getPDFProperties.txt"); file.createNewFile(); //Write the StringBuilder to the TXT file FileWriter fileWriter = new FileWriter(file, true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(stringBuilder.toString()); bufferedWriter.flush(); } }
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: Create Lists in PDF Documents
Lists are a great way to organize your information. When compared to chunks of text, it is usually easier to identify important points from a list. There are generally two different types of lists in PDF: order list and unorder list. You can also mix these two types in a nested list. In this article, you will learn how to create various types of lists in a PDF document using Spire.PDF for Java.
- Create an Ordered List in PDF
- Create an Unordered List with Symbol Bullets in PDF
- Create an Unordered List with Image Bullets in PDF
- Create a Nested Numbered List in PDF
Spire.PDF for Java provides the PdfSortedList class and the PdfUnorderedList class to represent the ordered list and the unordered list, respectively. To set the list’s content, indent, font, marker style and other attributes, use the methods under these two classes. The following table lists some of the core items involved in this tutorial.
Member | Description |
PdfSortedList class | Represents an ordered list in a PDF document. |
PdfUnorderedList class | Represents an unordered list in a PDF document. |
PdfListBase.setBrush() method | Sets a list's brush. |
PdfListBase.setFont() method | Sets a list's font. |
PdfListBase.sertIndent() method | Sets a list's indent. |
PdfListBase.setTextIndent() method | Sets the indent from the marker to the list item text. |
PdfListBase.getItems() method | Gets items of a list. |
PdfListBase.setMarker() method | Sets the marker of a list. |
PdfListBase.draw() method | Draw list on the canvas of a page at the specified location. |
PdfOrderedMarker class | Represents the marker style of an ordered list, such as numbers, letters, and roman numerals. |
PdfMarker class | Represents bullet style for an unordered list. |
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.10.7</version> </dependency> </dependencies>
Create an Ordered List in PDF
An ordered list is a container, which holds a sequence of objects. Each item in the list is marked with a number, a letter, or a roman numeral. The following are the step to create an ordered list in PDF using Spire.PDF for Java.
- Create a PdfDocument object.
- Add a page to it using PdfDocument.getPages().add() method.
- Create PdfBrush and PdfFont objects for the list.
- Create a PdfOrderedMarker object, specifying the marker style as Lower_Latin.
- Specify the list content with a string, and create an object of PdfSortedList class based on the string.
- Set the font, indent, brush and marker of the list using the methods under the PdfSortedList object.
- Draw the list on the page at the specified location using PdfSortedList.draw() method.
- Save the document to another file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfNumberStyle; import com.spire.pdf.PdfPageBase; import com.spire.pdf.PdfPageSize; import com.spire.pdf.graphics.*; import com.spire.pdf.lists.PdfOrderedMarker; import com.spire.pdf.lists.PdfSortedList; public class CreateOrderedList { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Set the margins PdfMargins margins = new PdfMargins(30); //Add a page PdfPageBase page = doc.getPages().add(PdfPageSize.A4, margins); //Create a brush PdfBrush brush = PdfBrushes.getBlack(); //Create fonts PdfFont titleFont = new PdfFont(PdfFontFamily.Times_Roman, 12f, PdfFontStyle.Bold); PdfFont listFont = new PdfFont(PdfFontFamily.Times_Roman, 12f, PdfFontStyle.Regular); //Create a maker for ordered list PdfOrderedMarker marker = new PdfOrderedMarker(PdfNumberStyle.Lower_Latin, listFont); //Specify the initial coordinate float x = 10; float y = 20; //Draw title String title = "Required Web Development Skills:"; page.getCanvas().drawString(title, titleFont, brush, x, y); y = y + (float) titleFont.measureString(title).getHeight(); y = y + 5; //Create a numbered list String listContent = "Command-line Unix\n" + "Vim\n" + "HTML\n" + "CSS\n" + "Python\n" + "JavaScript\n" + "SQL"; PdfSortedList list = new PdfSortedList(listContent); //Set the font, indent, text indent, brush, marker of the list list.setFont(listFont); list.setIndent(2); list.setTextIndent(4); list.setBrush(brush); list.setMarker(marker); //Draw list on the page at the specified location list.draw(page, x, y); //Save to file doc.saveToFile("output/OrderedList.pdf"); } }
Create an Unordered List with Symbol Bullets in PDF
An unordered list, also named bulleted list, is a collection of related items that have no special order or sequence. Each item in the list is marked with a bullet. The following are the step to create an unordered list in PDF using Spire.PDF for Java.
- Create a PdfDocument object.
- Add a page to it using PdfDocument.getPages().add() method.
- Create PdfBrush and PdfFont objects for the list.
- Create a PdfMarker object, specifying the marker style.
- Specify the list content with a string, and create an object of PdfUnorderedList class based on the string.
- Set the font, indent, brush and marker of the list using the methods under the PdfUnorderedList object.
- Draw the list on the page at the specified location using PdfUnorderedList.draw() method.
- Save the document to another 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 com.spire.pdf.lists.PdfMarker; import com.spire.pdf.lists.PdfUnorderedList; import com.spire.pdf.lists.PdfUnorderedMarkerStyle; public class CreateUnorderedList { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Set the margin PdfMargins margin = new PdfMargins(30); //Add a page PdfPageBase page = doc.getPages().add(PdfPageSize.A4, margin); //Create fonts PdfFont titleFont = new PdfFont(PdfFontFamily.Times_Roman, 12f, PdfFontStyle.Bold); PdfFont listFont = new PdfFont(PdfFontFamily.Times_Roman, 12f, PdfFontStyle.Regular); PdfFont markerFont = new PdfFont(PdfFontFamily.Times_Roman, 6f, PdfFontStyle.Regular); //Create a brush PdfBrush brush = PdfBrushes.getBlack(); //Specify the initial coordinate float x = 10; float y = 20; //Draw title String title = "Computer Science Subjects:"; page.getCanvas().drawString(title, titleFont, brush, x, y); y = y + (float)titleFont.measureString(title).getHeight(); y = y + 5; //Specify the marker style PdfMarker marker = new PdfMarker(PdfUnorderedMarkerStyle.Asterisk); marker.setFont(markerFont); //Create an unordered list String listContent = "Data Structure\n" + "Algorithm\n" + "Computer Networks\n" + "Operating System\n" + "Theory of Computations\n" + "C Programming\n" +"Computer Organization and Architecture"; PdfUnorderedList list = new PdfUnorderedList(listContent); //Set the font, indent, text indent, brush, marker of the list list.setFont(listFont); list.setIndent(2); list.setTextIndent(4); list.setBrush(brush); list.setMarker(marker); //Draw list on the page at the specified location list.draw(page, x, y); //Save to file doc.saveToFile("output/UnorderedList.pdf"); } }
Create an Unordered List with Image Bullets in PDF
In addition to symbols, the bullet points of an unordered list can be also a picture. The steps to create an unordered list with images bullets are as follows.
- Create a PdfDocument object.
- Add a page to it using PdfDocument.getPages().add() method.
- Create PdfBrush and PdfFont objects for the list.
- Create a PdfMarker object, setting the marker style as Custom_Image.
- Set an image as the marker using PdfMarker.setImage() method.
- Specify the list content with a string, and create an object of PdfUnorderedList class based on the string.
- Set the font, indent, brush and marker of the list using the methods under the PdfUnorderedList object.
- Draw the list on the page at the specified location using PdfUnorderedList.draw() method.
- Save the document to another 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 com.spire.pdf.lists.PdfMarker; import com.spire.pdf.lists.PdfUnorderedList; import com.spire.pdf.lists.PdfUnorderedMarkerStyle; public class CustomizeBulletPointsWithImage { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Set the margin PdfMargins margin = new PdfMargins(30); //Add a page PdfPageBase page = doc.getPages().add(PdfPageSize.A4, margin); //Create fonts PdfFont titleFont = new PdfFont(PdfFontFamily.Times_Roman, 12f, PdfFontStyle.Bold); PdfFont listFont = new PdfFont(PdfFontFamily.Times_Roman, 12f, PdfFontStyle.Regular); //Create a brush PdfBrush brush = PdfBrushes.getBlack(); //Specify the initial coordinate float x = 10; float y = 20; //Draw title String title = "Project Task To-Do List:"; page.getCanvas().drawString(title, titleFont, brush, x, y); y = y + (float)titleFont.measureString(title).getHeight(); y = y + 5; //Specify the marker style to image PdfMarker marker = new PdfMarker(PdfUnorderedMarkerStyle.Custom_Image); //Set the image for the marker marker.setImage(PdfImage.fromFile("C:/Users/Administrator/Desktop/checkmark.png")); //Create an unordered list String listContent = "Define projects and tasks you're working on\n" + "Assign people to tasks\n" + "Define the priority levels of your tasks\n" + "Keep track of the progress status of your tasks\n" + "Mark tasks as done when completed"; PdfUnorderedList list = new PdfUnorderedList(listContent); //Set the font, indent, text indent, brush, maker of the list list.setFont(listFont); list.setIndent(2); list.setTextIndent(4); list.setBrush(brush); list.setMarker(marker); //Draw list on a page at the specified location list.draw(page, x, y); //Save to file doc.saveToFile("output/ImageBullets.pdf"); } }
Create a Nested Numbered List in PDF
A nested list is a list that contains at least one sub list. Nested lists are used to present data in hierarchical structures. The following are the steps to create a nested numbered list in PDF using Spire.PDF for Java.
- Create a PdfDocument object.
- Add a page to it using PdfDocument.getPages().add() method.
- Create a PdfOrderedMarker object, specifying the marker style as Numeric.
- Specify the list content with a string, and create a parent list based on the string. Then set the font, indent, brush and marker of the list using the methods under the PdfSortedList object.
- Repeat the above step to create sub lists and sub-sub lists.
- Get the specific item of the parent list using PdfSortedList.getItems().get() method, and add a list to it as its sub list using PdfListItem.setSublist() method.
- Draw the list on the page at the specified location using PdfSortedList.draw() method.
- Save the document to another file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfNumberStyle; import com.spire.pdf.PdfPageBase; import com.spire.pdf.PdfPageSize; import com.spire.pdf.graphics.*; import com.spire.pdf.lists.PdfListItem; import com.spire.pdf.lists.PdfOrderedMarker; import com.spire.pdf.lists.PdfSortedList; public class CreateMultiLevelList { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Set the margin PdfMargins margin = new PdfMargins(30); //Add a page PdfPageBase page = doc.getPages().add(PdfPageSize.A4, margin); //Specify the initial coordinate float x = 10; float y = 20; //Create two brushes PdfBrush blackBrush = PdfBrushes.getBlack(); PdfBrush purpleBrush = PdfBrushes.getPurple(); //Create two fonts PdfFont titleFont = new PdfFont(PdfFontFamily.Times_Roman, 12f, PdfFontStyle.Bold); PdfFont listFont = new PdfFont(PdfFontFamily.Times_Roman, 12f, PdfFontStyle.Regular); //Create a maker for ordered list PdfOrderedMarker marker = new PdfOrderedMarker(PdfNumberStyle.Numeric, listFont); //Draw title String title = "Below is a Nested Numbered List:"; page.getCanvas().drawString(title, titleFont, blackBrush, x, y); y = y + (float)titleFont.measureString(title).getHeight(); y = y + 5; //Create a parent list String parentListContent = "Parent Item 1\n" + "Parent Item 2"; PdfSortedList parentList = new PdfSortedList(parentListContent); parentList.setFont(listFont); parentList.setIndent(2); parentList.setBrush(purpleBrush); parentList.setMarker(marker); //Create a sub list - "subList_1" String subListContent_1 = "Sub Item 1\n" + "Sub Item 2\n" + "Sub Item 3\n" + "Sub Item 4"; PdfSortedList subList_1 = new PdfSortedList(subListContent_1); subList_1.setIndent(12); subList_1.setFont(listFont); subList_1.setBrush(blackBrush); subList_1.setMarker(marker); subList_1.setMarkerHierarchy(true); //Create another sub list -"subList_2" String subListContent_2 = "Sub Item 1\n" + "Sub Item 2\n" + "Sub Item 3"; PdfSortedList subList_2 = new PdfSortedList(subListContent_2); subList_2.setIndent(12); subList_2.setFont(listFont); subList_2.setBrush(blackBrush); subList_2.setMarker(marker); subList_2.setMarkerHierarchy(true); //Create a sub-sub list - "subList_1" String subSubListContent_1 = "Sub Sub Item 1\n" + "Sub Sub Item 2"; PdfSortedList subSubList = new PdfSortedList(subSubListContent_1); subSubList.setIndent(20); subSubList.setFont(listFont); subSubList.setBrush(blackBrush); subSubList.setMarker(marker); subSubList.setMarkerHierarchy(true); //Set subList_1 as sub list of the first item of parent list PdfListItem item_1 = parentList.getItems().get(0); item_1.setSubList(subList_1); //Set subList_2 as sub list of the second item of parent list PdfListItem item_2 = parentList.getItems().get(1); item_2.setSubList(subList_2); //Set subSubList as sub list of the first item of subList_1 PdfListItem item_1_1 = subList_1.getItems().get(0); item_1_1.setSubList(subSubList); //Draw parent list parentList.draw(page, x, y); //Save to file doc.saveToFile("output/MultiLevelList.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: Change PDF Version
PDF is a file format developed by Adobe in 1992, and during the years, it has undergone a lot of changes. Sometimes you may find that some devices have strict requirements on the PDF version. In such a case, it's necessary to change the PDF file to a different version for compatibility purpose. This article will show how to programmatically change the PDF version 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.10.7</version> </dependency> </dependencies>
Change PDF Version
Spire.PDF for Java supports the PDF versions from 1.0 to 1.7. The following are the detailed steps to change the PDF version.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.loadFromFile() method.
- Change the PDF file to another version using PdfDocument.getFileInfo().setVersion() method.
- Save the document to another file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.*; public class ChangePdfVersion { public static void main(String[] args) { //Create a PdfDocument object PdfDocument document = new PdfDocument(); //Load a sample PDF file document.loadFromFile("sample.pdf"); //Change the PDF to version 1.5 document.getFileInfo().setVersion(PdfVersion.Version_1_5); //Save to file document.saveToFile("PdfVersion.pdf", FileFormat.PDF); document.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: Split a PDF File into Multiple PDFs
By splitting PDF pages into separate files, you get smaller PDF documents that have one or some pages extracted from the original. A split file contains less information and is naturally smaller in size and easier to share over the internet. In this article, you will learn how to split PDF into single-page PDFs and how to split PDF by page ranges 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.10.7</version> </dependency> </dependencies>
Split a PDF File into Multiple Single-Page PDFs in Java
Spire.PDF for Java offers the split() method to divide a multipage PDF document into multiple single-page files. The following are the detailed steps.
- Create a PdfDcoument object.
- Load a PDF document using PdfDocument.loadFromFile() method.
- Split the document into one-page PDFs using PdfDocument.split(string destFilePattern, int startNumber) method.
- Java
import com.spire.pdf.PdfDocument; public class SplitPdfByEachPage { public static void main(String[] args) { //Specify the input file path String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf"; //Specify the output directory String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\"; //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Load a PDF file doc.loadFromFile(inputFile); //Split the PDF to one-page PDFs doc.split(outputDirectory + "output-{0}.pdf", 1); } }
Split a PDF File by Page Ranges in Java
No straightforward method is offered for splitting PDF documents by page ranges. To do so, we create two or more new PDF documents and import the selected page or page range from the source document into them. Here are the detailed steps.
- Load the source PDF file while initialing the PdfDocument object.
- Create two additional PdfDocument objects.
- Import the first page from the source file to the first document using PdfDocument.insertPage() method.
- Import the remaining pages from the source file to the second document using PdfDocument.insertPageRange() method.
- Save the two documents as separate PDF files using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; public class SplitPdfByPageRange { public static void main(String[] args) { //Specify the input file path String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf"; //Specify the output directory String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\"; //Load the source PDF file while initialing the PdfDocument object PdfDocument sourceDoc = new PdfDocument(inputFile); //Create two additional PdfDocument objects PdfDocument newDoc_1 = new PdfDocument(); PdfDocument newDoc_2 = new PdfDocument(); //Insert the first page of source file to the first document newDoc_1.insertPage(sourceDoc, 0); //Insert the rest pages of source file to the second document newDoc_2.insertPageRange(sourceDoc, 1, sourceDoc.getPages().getCount() - 1); //Save the two documents as PDF files newDoc_1.saveToFile(outputDirectory + "output-1.pdf"); newDoc_2.saveToFile(outputDirectory + "output-2.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: Merge Multiple PDFs into a Single PDF
If you are having trouble handling a great many PDF files, you might want to merge all of those files into one. Combining multiple files into one PDF lets you store, share and review them more easily. In this article, you will learn how to merge PDF documents in Java by 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.10.7</version> </dependency> </dependencies>
Merge Multiple PDFs into a Single PDF
Spire.PDF for Java offers the PdfDocument.mergeFiles() method to merge multiple PDF documents into a single document. The detailed steps are as follows.
- Get the paths of the documents to be merged and store them in a String array.
- Call PdfDocument.mergeFiles() method to merge these files. This method also accepts an array of InputStream as the parameter.
- Save the result to a PDF document using PdfDocumentBase.save() method.
- Java
import com.spire.pdf.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfDocumentBase; public class MergePdfs { public static void main(String[] args) { //Get the paths of the documents to be merged String[] files = new String[] { "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-1.pdf", "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-2.pdf", "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-3.pdf"}; //Merge these documents and return an object of PdfDocumentBase PdfDocumentBase doc = PdfDocument.mergeFiles(files); //Save the result to a PDF file doc.save("output.pdf", FileFormat.PDF); } }
Merge the Selected Pages of Different PDFs into One PDF
Spire.PDF for Java offers the PdfDocument.insertPage() method and the PdfDocument.insertPageRange() method to import a page or a page range from one PDF document to another. The following are the steps to combine the selected pages of different PDF documents into a new PDF document.
- Get the paths of the source documents and store them in a String array.
- Create an array of PdfDocument, and load each source document to a separate PdfDocument object.
- Create another PdfDocument object for generating a new document.
- Insert the selected page or page range of the source documents to the new document using PdfDocument.insertPage() method and PdfDocument.insertPageRange() method.
- Save the new document to a PDF file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; public class MergeSelectedPages { public static void main(String[] args) { //Get the paths of the documents to be merged String[] files = new String[] { "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-1.pdf", "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-2.pdf", "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-3.pdf"}; //Create an array of PdfDocument PdfDocument[] docs = new PdfDocument[files.length]; //Loop through the documents for (int i = 0; i < files.length; i++) { //Load a specific document docs[i] = new PdfDocument(files[i]); } //Create a PdfDocument object for generating a new PDF document PdfDocument doc = new PdfDocument(); //Insert the selected pages from different documents to the new document doc.insertPage(docs[0], 0); doc.insertPageRange(docs[1], 1,3); doc.insertPage(docs[2], 0); //Save the document to a PDF file doc.saveToFile("output.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.