Skip to main content

Posts

Showing posts from March, 2022

Read PDF in Java Using iText

In this post we’ll see a Java program to read PDF document using iText library. To know more about iText library and PDF examples check this post- Generating PDF in Java Using iText Tutorial Reading PDFs using iText For reading PDF using iText you need to use the following steps. Create a PDFReader instance, wrap it with in a PDFDocument. Get the number of pages in the PDF that has to be read. Iterate through pages and extract the content of each page using PdfTextExtractor. PDF used for reading. Java Program import java.io.IOException; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfReader; import com.itextpdf.kernel.pdf.canvas.parser.PdfTextExtractor; public class ReadPDF { public static final String READ_PDF = "F://knpcode//result//List.pdf"; public static void main(String[] args) { try { // PDFReader PdfReader reader = new PdfReader(READ_PDF); PdfDocument pdfDoc = new PdfDocument(reader); // get

Merging PDFs in Java Using iText

In this post we’ll see a Java program to merge two PDF documents using iText library. To know more about iText library and PDF examples check this post- Generating PDF in Java Using iText Tutorial Merging PDFs using iText In iText there is a PDFMerger class that can be used for merging PDFs. Using this class you can merge a number of existing documents into one. Following Java program shows how two PDF documents can be merged using iText. import java.io.IOException; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfReader; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.utils.PdfMerger; public class MergePDF { public static final String SRC_PDF1 = "F://knpcode//PDF1.pdf"; public static final String SRC_PDF2 = "F://knpcode//PDF2.pdf"; public static final String MERGED_PDF = "F://knpcode//result//Merged.pdf"; public static void main(String[] args) throws IOException{ PdfDocument pdfDoc

Generating PDF in Java Using iText Tutorial

This iText tutorial shows how to generate PDF in Java using iText. Before going to examples of PDF creation in Java using iText there are few points about iText library. iText ( https://itextpdf.com ) comes with dual licenses commercial as well as open source (AGPL). If you are using AGPL license (which is free) you need to share your entire application for free under the same AGPL license. The examples shown in this post use iText 7 library which is rewritten and API differs from iText 5. Some of the main classes that are used for generating PDF using iText are- Document - Document is the default root element when creating a self-sufficient PDF. PDFDocument - Main enter point to work with PDF document. Paragraph - Creates a Paragraph, initialized with a piece of text. Text - A Text is a piece of text of any length. PdfWriter - Create a PdfWriter writing to the passed outputstream. PdfReader - Reads a PDF document. PdfFontFactory - This class provides helpful

Java Spliterator With Examples

Spliterator in Java, just like Iterator and ListIterator , is used for traversing the elements of a source. How it differs from other iterator implementation is that the Spliterator API is designed to support efficient parallel traversal in addition to sequential traversal . Using Spliterator elements can be partitioned and iterated in parallel. Important points about Java Spliterator Spliterator API is defined using Spliterator interface which is part of java.util package . Spliterator interface was added in Java 8. Source for a Spliterator could be an array, a Collection, an IO channel, or a generator function. Spliterator can be used for both parallel and sequential traversal. When you use Iterator for traversal you have to use two methods- a. hasNext() to ensure that there is next element b. next() method to use that element. Methods in Java Spliterator combine these two methods into one making it more convenient to use. Java Spliterator methods Splite

Convert ArrayList to Array in Java

In this post we’ll see how to convert ArrayList to array in Java. Since internal implementation of ArrayList uses an array internally to store its element so ArrayList class itself provides toArray() method to convert ArrayList to array. There are two overloaded toArray() methods. toArray() - Returns an array containing all of the elements in this list in proper sequence. The returned array will be "safe" in that no references to it are maintained by this list. Returned array is of type Object. toArray(T[] a) - Returns an array containing all of the elements in this list in proper sequence. The runtime type of the returned array is that of the specified array. Though one problem with using these methods to convert ArrayList to array in Java is that the reference of the stored objects are shared between both ArrayList and converted array . Any modification to any stored object will be reflected in other data structure too. Another option is to do the conver

How to Sort Java HashSet

This post shows how to sort a HashSet in Java . Since HashSet is an unordered collection so you will need to convert it to another collection in order to sort a HashSet. There are two options to sort a HashSet by converting it to another collection. Convert HashSet to list and use Collections.sort() method where you can pass List as an argument. Convert HashSet to TreeSet by using constructor of the TreeSet class. Since TreeSet is a SortedSet implementation the elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used. Sorting HashSet using Collections.sort() method If you are sorting HashSet in Java using this way you need to convert HashSet to List and pass it to Collections.sort() method which will sort it as per natural ordering. If you want to sort it in different order you can use a Comparator . Refer How to Sort ArrayList in Java to see sorting of the List by passing a Compara

Java String matches() Method

In this post we’ll see how to use Java String matches() method which tells whether the String matches the given regular expression or not. This method is useful if you have a bunch of Strings and you want to separate specific type of Strings by passing the specified pattern as a regular expression. matches() method in String class boolean matches(String regex) - Tells whether or not this string matches the given regular expression. Method returns true if string matches the given regular expression otherwise false is returned. PatternSyntaxException is thrown if the regular expression's syntax is invalid. matches() method Java examples 1. In the following example there are two strings and matches method is used to match strings with regular expression. Regex .* means any number of characters so .*knpcode.* means any number of characters before and after knpcode. public class StringMatch { public static void main(String[] args) { String str1 = "In technica

Java String replace Method With Examples

In Java String class there are four replace() methods to replace occurrences of character or string with another character or string. String replace(char oldChar, char newChar) - Returns a string resulting from replacing all occurrences of oldChar in this string with newChar. See example . String replace(CharSequence target, CharSequence replacement) - Replaces each substring of this string that matches the target sequence with the specified literal replacement sequence. Note that the replacement starts from the beginning of the string to the end, or example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab". See example . String replaceAll(String regex, String replacement) - Replaces each substring of this string that matches the given regular expression with the given replacement. See example . String replaceFirst(String regex, String replacement) - Replaces the first substring of this

Java String valueOf() Method With Examples

Java string valueOf() method is used to convert values of different data types into their String representations. valueOf() methods in String class valueOf() method in Java String class is overloaded and has following variants- String valueOf(boolean b) - Returns the string representation of the boolean argument. If the argument is true, a string equal to "true" is returned; otherwise, a string equal to "false" is returned. String valueOf(char c) - Returns the string representation of the char argument. String valueOf(int i) - Returns the string representation of the int argument. String valueOf(long l) - Returns the string representation of the long argument. String valueOf(float f) - Returns the string representation of the float argument. String valueOf(double d) - Returns the string representation of the double argument. String valueOf(char[] data) - Returns the string representation of the char array argument. String valueOf(

Create Java Project Using Maven in Eclipse

In this post we’ll see how to create Java project using Maven in Eclipse IDE. For that Maven Eclipse plugin is used which comes pre-installed in Eclipse now. Steps for creating Java Maven project in Eclipse Go to File – New – Maven Project In the "New Maven Project" window check "Create a simple project (skip archetype selection)" and click Next. In the next window enter group id and artifact id. GroupId – This is an Id of project’s group. This ID uniquely identifies the group that may have many sub-projects. For example com.knpcode.spring may contain other projects related to Spring. ArtifactId – This is an Id of the project. This ID uniquely identifies a project, for example SpringXML. GroupId + ArtifactId defines the artifact’s location with in the repository for example com.knpcode.spring.SpringXML Click finish, project structure will be created as shown below. One thing that you may need to change is JRE system library which is Ja

Chained Exception in Java

Using chained exception in Java you can associate one exception with another . Chained exception helps in the scenario where one exception causes another exception. The exception that will be thrown is the second exception in such scenario but you can set the cause of original exception in the second exception so in a way you are chaining the exceptions. For example, you are writing a class where two command line arguments are passed and then you convert those arguments to integer. If you don't pass two arguments that will result in ArrayIndexOutOfBoundsException but the real cause here is not having enough arguments. So you can set the cause as IllegalArgumentException with the appropriate message. Constructors and Methods for chained exception in Java In Throwable class there are two constructors that support chained exception. Throwable(Throwable expObj) – Here expObj signifies the exception that caused the current exception. Throwable(String msg, Throwable