We can create the pdf number of ways(like using Itext, Pdfbox...etc).
Using Itext
Explanation:
In this example, I am just printing the hello-word text message.
1. First, create the document object.
2. Create the PdfWriter object for writing the text into the document. using the file output stream for creating the file.
3. Using the open method to open the file.
4. Using the add and new paragraph methods to add paragraphs in the document.
5. Finally, close the document using the close method.
Using pdf box
Explanation:
1. First, create the document object.
2. Creating the page using the PDPage object.
3. Using the save method to save the pdf file.
4. Finally, close the document using the close method.
Using Itext
- Download the Itext pdf java library file http://www.java2s.com/Code/Jar/i/Downloaditextpdf510jar.htm
- Create the sample java class and add jar file into the project.
Here is the sample java class
package com.pdf; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; /** * * @author Janardhan Randhi */ public class PdfGeneration { public static void main(String[] args) throws IOException { //Creating PDF document object PDDocument document = new PDDocument(); //Creating a blank page PDPage javasnippets = new PDPage(); //Adding the blank page to the document document.addPage(javasnippets); //Saving the document document.save("d://pdf.pdf"); System.out.println("PDF created"); //Closing the document document.close(); } }
Explanation:
In this example, I am just printing the hello-word text message.
1. First, create the document object.
2. Create the PdfWriter object for writing the text into the document. using the file output stream for creating the file.
3. Using the open method to open the file.
4. Using the add and new paragraph methods to add paragraphs in the document.
5. Finally, close the document using the close method.
Using pdf box
- Download the pdf box java library file https://pdfbox.apache.org/download.cgi
- Create the sample java class and add jar file into the project.
package com.pdf; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; /** * * @author Janardhan Randhi */ public class WithItext { public static void main(String[] args) throws DocumentException { Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf")); document.open(); document.add(new Paragraph("Hello World from javasnippets")); document.close(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
1. First, create the document object.
2. Creating the page using the PDPage object.
3. Using the save method to save the pdf file.
4. Finally, close the document using the close method.