To Add Paragraph in PDF using iText library is very easy. You can also set spacing between 2 paragraphs. Spacing can be added After/Before each of the paragraphs.
Important Class – com.itextpdf.text.Paragraph
For adding spacing we can use either
a)
setSpacingBefore(float spacing)
b)
setSpacingAfter(float spacing)
For Indentation either Right or left we can use
a)
setIndentationLeft(float indentation)
b)
setIndentationRight(float indentation)
Example
Lets see example on how to add paragraph in PDF using iText. We will have 2 paragraphs created and add a space between these paragraphs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
package com.kscodes.examples.itext; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; public class ParagraphExample { public static void main(String args[]) { // Create a Document object Document document = new Document(); try { // Create a PdfWriter instance and use the document to write the pdf // to a specified location PdfWriter.getInstance(document, new FileOutputStream("K:\\Kscodes\\pdf\\itext-para.pdf")); document.open(); Paragraph para1 = new Paragraph( "Anyone, anywhere can open a PDF file. All you need is the free Adobe Acrobat " + "Reader. Recipients of other file formats sometimes can't open files because they " + "don't have the applications used to create the documents."); Paragraph para2 = new Paragraph("PDF files always display exactly as created, " + "regardless of fonts, software, and operating systems. Fonts, " + "and graphics are not lost due to platform, software, and version incompatibilities."); // Set Indentation Left for 1st Paragraph para1.setIndentationLeft(30f); // Set Indentation Right for 2nd Paragraph para2.setIndentationRight(40f); // Set Spacing Before 2nd paragragh para2.setSpacingBefore(20f); // Add elements to the document document.add(para1); document.add(para2); // close the document document.close(); System.out.println("PDF created at the location !!!"); } catch (Exception e) { System.out.println("Exception occured :: " + e); } } } |
Output