Itext New Font with Bold and Underline - java

I am trying to add new font to my pdf which I need to make it bold and underlined..
I can add the new Font, but cannot make it bold and underlined at same time.
I tried the following way..
public class PdfGenerator {
private static final String BASE_FONT = "Trebuchet MS";
private static final String BASE_FONT_BOLDITALIC = "Trebuchet MS BI";
private static final String BASE_FONT_BOLD = "Trebuchet MS B";
private static final Font titlefontSmall = FontFactory.getFont(
BASE_FONT_BOLD, 10, Font.UNDERLINE);
static {
String filePath = "..my font directory";
String fontPath = filePath + "\\" + "trebuc.ttf";
String fontPathB = filePath + "\\" + "TREBUCBD.TTF";
String fontPathBI = filePath + "\\" + "TREBUCBI.TTF";
FontFactory.register(fontPath, BASE_FONT);
FontFactory.register(fontPathB, BASE_FONT_BOLD);
FontFactory.register(fontPathBI, BASE_FONT_BOLDITALIC);
}
public void genMyPdf(String filePath) {
try {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(filePath));
document.open();
Paragraph p = new Paragraph("This should be bold & underline",
titlefontSmall);
document.add(p);
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
What am I doing wrong ?

you can define a font object with both styles :
private static final Font SUBFONT = new Font(Font.getFamily("TIMES_ROMAN"), 12, Font.BOLD|Font.UNDERLINE);

Read up on HERE since you are using the IText library.
Basically use chunks then add those chunks to the document.
Chunk underline = new Chunk("Underline. ");
underline.setUnderline(0.1f, -2f); //0.1 thick, -2 y-location
document.add(underline);
I haven't tried it myself so I don't know how it turns out yet. Further reading up on the iText documentation, it seems that you have to define a bold font first and then implement it. THIS TUTORIAL shows an example of bold font usage with iText and making a pdf with bold text. From there, I'm sure you can implement the code above to the bold text and walah!, bold-underlined text :D

You can define your FONT in your class as such:
public final static Font CUSTOM_FONT = new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD | Font.UNDERLINE);
and then use it as :
paragraph.add(new Phrase( " YOUR TEXT HERE ",PDFCreator.CUSTOM_FONT));

try it
Font fontbold = FontFactory.getFont("Times-Roman", 12, Font.BOLD);
document.add(new Paragraph("Times-Roman, Bold", fontbold));
and Font.UNDERLINE for undeline

You can just use the following to get both bold and underline:-
Chunk buyerOrder = new Chunk("Buyer's Order Number", FontFactory.getFont(FontConstants.TIMES_ROMAN,8,Font.BOLD));
buyerOrder.setUnderline(0.1f, -2f);
Hope it helps! Thanks

Related

Write Heart Symbol in pdf using itext java

Trying to write heart symbol in pdf through java code .
This is my input to pdf : ❤️❤️❤️
But pdf generated is empty without anything written.
Using itext to write to pdf.
The Font used is tradegothic_lt_boldcondtwenty.ttf
OutputStream file = new FileOutputStream(fileName);
Document document = new Document(PageSize.A6);
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
PdfLayer nested = new PdfLayer("Layer 1", writer);
PdfContentByte cb = writer.getDirectContent();
cb.beginLayer(nested);
ColumnText ct = new ColumnText(cb);
Font font = getFont();
Phrase para1 = new Phrase("❤️❤️❤️",font);
ct.setSimpleColumn(para1,38,0,260,138,15, Element.ALIGN_LEFT);
ct.go();
cb.endLayer();
document.close();
file.close();
private Font getFont() {
final String methodName = "generatePDF";
LOGGER.entering(CLASSNAME, methodName);
Font font = null;
try {
String filename = tradegothic_lt_boldcondtwenty.ttf;
FontFactory.register(filename, filename);
font = FontFactory.getFont(filename, BaseFont.CP1252, BaseFont.EMBEDDED,11.8f);
} catch(Exception exception) {
LOGGER.logp(Level.SEVERE, CLASSNAME, methodName, "Exception Occurred while fetching the Trade Gothic font." + exception);
font = FontFactory.getFont(FontFactory.HELVETICA_BOLD,11.8f);
}
return font;
}
Phrase para1 has the heart correctly. But not able to see in pdf

Unicode unknown on jboss server [duplicate]

when I want to use a font is iText I do the following:
protected final static Font FONT_SIZE_11_BOLD = new Font(Font.HELVETICA, 11f, Font.BOLD);
and then I can use it whereever I want, as follows:
monthSize11 = new Chunk(month, FONT_SIZE_11_BOLD);
I want to use Arial instead of HELVETICA, but Arial is not directly available.
I mean, I cannot do
new Font(Font.ARIAL, 11f, Font.BOLD);
because Arial is not defined at the Font class, but the Arial.ttf file is at my System under C:\WINDOWS\Fonts.
The question is how I can bind the Arial.ttf file to iText and how can I use it.
Many thnaks in advance.
EDIT: I would like to use own fonts. I mean, I have a file called "myCompany.ttf" where own fonts have been defined and at some places I must use. The problem is not only with Arial.
BaseFont base = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.WINANSI);
Font font = new Font(base, 11f, Font.BOLD);
....
Read more here.
Load it from inside the JAR using a leading slash; otherwise, use the absolute path of your font (C:\...\fonts\Sansation_Regular.ttf). For example:
Font font = FontFactory.getFont("/fonts/Sansation_Regular.ttf",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0.8f, Font.NORMAL, BaseColor.BLACK);
BaseFont baseFont = font.getBaseFont();
The relative path of the font is: 'src/main/resources/fonts'
Using Itext 5.4.5
Example code
Use BaseFont.createFont to create a new Font object.
You can pass any Type1 or TTF font. You will just have to ensure your font file is distributed alongwith.
Refer
BaseFont API
Creating custom fonts using itext is simple
I had written code for the same below
Will definitely help someone
public class CustomFontStyle {
public static void main(String[] args) {
// creation of the document with a certain size and certain margins
// may want to use PageSize.LETTER instead
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
// creation of the different writers
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("CustomFontsStyle.pdf"));
final String NEWLINE = "\n";
document.open();
Phrase phrase = new Phrase();
BaseFont baseFont3 = BaseFont.createFont("Xenotron.ttf", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
Font font2 = new Font(baseFont3, 12);
document.add(new Paragraph("Custom Xenotron Font: ", font2));
phrase.add(NEWLINE);
document.add(phrase);
document.close();
}
catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
}

iText doesn't like my special characters

I'm trying to generate a pdf file using iText.
The file gets produced just fine, but I can seem to use special characters like german ä, ö, ...
The sentence I want to be written is (for example)
■ ...ä...ö...
but the output is
■...ä...ö...
(I had to kind of blur the sentences, but I guess you see what I'm talking about...)
Somehow this black block-thing and all "Umlaute" can't be generated ...
The font used is the following:
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
So there should be no problem about the font not having these characters...
I'm using IntelliJ Idea to develop, the encoding of the .java file is set to UTF-8, so there should be no problem too...
I'm kind of lost here; does anyone know what i may do to get it working?
Thanks in advance and greetz
gilaras
---------------UPDATE---------------
So here's (part of) the code:
#Controller
public class Generator {
...
Font font = new Font(Font.FontFamily.TIMES_ROMAN, 9f, Font.BOLD);
...
Paragraph intro = new Paragraph("Ich interessiere mich für ...!", font_12_bold);
Paragraph wantContact = new Paragraph("■ Ich hätte gerne ... ", font);
...
Phrase south = new Phrase("■ Süden □ Ost-West ...");
...
#RequestMapping(value = "/generatePdf", method = RequestMethod.POST)
#ResponseBody
public String generatePdf(HttpServletRequest request) throws IOException, DocumentException, com.lowagie.text.DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
addMetaData(document);
document.open();
addContent(document, request);
document.add(new Paragraph("äöü"));
document.close();
return "";
}
private void addContent(Document document, HttpServletRequest request)
throws DocumentException {
Paragraph preface = new Paragraph();
preface.setAlignment(Element.ALIGN_JUSTIFIED);
addEmptyLine(preface, 1);
preface.add(new Paragraph("Rückantwort", catFont));
addEmptyLine(preface, 2);
preface.add(intro);
addEmptyLine(preface, 1);
if (request.getParameter("dec1").equals("wantContact")) {
preface.add(wantContact);
} else {
...
}
document.add(preface);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
private static void addMetaData(Document document) {
document.addTitle("...");
document.addSubject("...");
document.addKeywords("...");
document.addAuthor("...");
document.addCreator("...");
}
}
I had to take some things out, but I kept some Umlaut-character and other special characters, so that you can see, where the problem occurs ... :-)
You might want to try and embed the font using this technique:
BaseFont times = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(times, 12, Font.BOLD);

How to add new fonts to Itext using java

when I want to use a font is iText I do the following:
protected final static Font FONT_SIZE_11_BOLD = new Font(Font.HELVETICA, 11f, Font.BOLD);
and then I can use it whereever I want, as follows:
monthSize11 = new Chunk(month, FONT_SIZE_11_BOLD);
I want to use Arial instead of HELVETICA, but Arial is not directly available.
I mean, I cannot do
new Font(Font.ARIAL, 11f, Font.BOLD);
because Arial is not defined at the Font class, but the Arial.ttf file is at my System under C:\WINDOWS\Fonts.
The question is how I can bind the Arial.ttf file to iText and how can I use it.
Many thnaks in advance.
EDIT: I would like to use own fonts. I mean, I have a file called "myCompany.ttf" where own fonts have been defined and at some places I must use. The problem is not only with Arial.
BaseFont base = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.WINANSI);
Font font = new Font(base, 11f, Font.BOLD);
....
Read more here.
Load it from inside the JAR using a leading slash; otherwise, use the absolute path of your font (C:\...\fonts\Sansation_Regular.ttf). For example:
Font font = FontFactory.getFont("/fonts/Sansation_Regular.ttf",
BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0.8f, Font.NORMAL, BaseColor.BLACK);
BaseFont baseFont = font.getBaseFont();
The relative path of the font is: 'src/main/resources/fonts'
Using Itext 5.4.5
Example code
Use BaseFont.createFont to create a new Font object.
You can pass any Type1 or TTF font. You will just have to ensure your font file is distributed alongwith.
Refer
BaseFont API
Creating custom fonts using itext is simple
I had written code for the same below
Will definitely help someone
public class CustomFontStyle {
public static void main(String[] args) {
// creation of the document with a certain size and certain margins
// may want to use PageSize.LETTER instead
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
// creation of the different writers
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("CustomFontsStyle.pdf"));
final String NEWLINE = "\n";
document.open();
Phrase phrase = new Phrase();
BaseFont baseFont3 = BaseFont.createFont("Xenotron.ttf", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
Font font2 = new Font(baseFont3, 12);
document.add(new Paragraph("Custom Xenotron Font: ", font2));
phrase.add(NEWLINE);
document.add(phrase);
document.close();
}
catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
}

Inserting greater than or equal symbol in to an iText PDF, ie >=

Does anyone know an easy way to include the greater than or equal symbol in an iText PDF document without resorting to custom fonts?
You need to add the unicode for this character. Also make sure that the char is included in the font you use.
document.add( new Paragraph("\u2265"));
Use the below code for the same. It's work for me.
//symbol for greater or equal then
public void process() throws DocumentException, IOException {
String dest = "/home/ashok/ashok/tmp/hello.pdf";
BaseFont bfont = BaseFont.createFont(
"/home/ashok/ashok/fonts/Cardo-Regular.ttf",
BaseFont.IDENTITY_H,
BaseFont.EMBEDDED);
Font font = new Font(bfont, 12);
try {
Document document=new Document();
PdfWriter.getInstance(document,new
FileOutputStream("/home/ashok/ashok/tmp/hello.pdf"));
document.open();
Chunk chunk = new Chunk("\u2265");
Paragraph p = new Paragraph("Mathematical Operators are ",font);
p.add(chunk);
document.add(p);
p = new Paragraph(" ",font);
chunk = new Chunk("\u2264");
p.add(chunk);
document.add(p);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Categories