Using the iText framework we have seen how to add text/paragraphs to PDF files. Now we will see how we can add various fonts and colors to the text that is added. Lets see an example on how to Add Fonts in PDF using iText.
Important class – com.itextpdf.text.Font
For setting font color use either
a)
setColor(BaseColor color)
b)
setColor(int red, int green, int blue)
For setting size of the font use
a)
setSize(float size)
For setting font style i.e (normal, bold, italic, oblique, underline, line-through) use
a)
setStyle(String style)
Example
In this example we take two paragraphs and add various fonts, colors and styles to them.
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 54 55 56 57 |
package com.kscodes.examples.itext; import java.io.FileOutputStream; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.Font; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfWriter; public class FontExample { 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-font.pdf")); document.open(); Font font1 = new Font(BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1250, true)); font1.setColor(BaseColor.DARK_GRAY); font1.setSize(16); String text1 = "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 para1 = new Paragraph(text1, font1); Font font2 = new Font(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, true)); font2.setColor(BaseColor.RED); font2.setSize(14); font2.setStyle("underline"); String text2 = "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."; Paragraph para2 = new Paragraph(text2, font2); // 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