iText Font Strategy - java

I have a web application that will generate a PDF from data and allow a user to download. We have a custom font so I am registering four font files (regular, bold, italic, and bold italic ttf files).
Is this necessary? Can I just use the regular font file and set the weight/styles through the font class or do I need all the files? It looks like it works ok but I am still learning.
What is a good strategy or pattern for managing these different fonts to put into my documents? Has anyone done much with this from a Java perspective?

You're not telling us how you're registering your fonts, nor how you're using them, so let me tell you how I would work (I'm the original developer of iText). If you're using those 4 fonts, the best way is to register them like this:
BaseFont bfRegular = BaseFont.createFont(regularTTF, BaseFont.IDENTITY_H, BaseFont_EMBEDDED);
BaseFont bfBold = BaseFont.createFont(boldTTF, BaseFont.IDENTITY_H, BaseFont_EMBEDDED);
BaseFont bfItalic = BaseFont.createFont(italicTTF, BaseFont.IDENTITY_H, BaseFont_EMBEDDED);
BaseFont bfBoldItalic = BaseFont.createFont(boldItalicTTF, BaseFont.IDENTITY_H, BaseFont_EMBEDDED);
I'd use these BaseFont instances whenever adding content using low-level operations.
Then I would do:
Font fRegular = new Font(bfRegular, 12);
Font fBold = new Font(bfBold, 12);
Font fItalic = new Font(bfItalic, 12);
Font fBoldItalic = new Font(bfBoldItalic, 12);
I'd use these fonts whenever I need to create a high-level object, such as a Paragraph.
Of course, I may also need something like this:
Font fRegularSmall = new Font(bfRegular, 9);
Font fBoldSmall = new Font(bfBold, 9);
Font fItalicSmall = new Font(bfItalic, 9);
Font fBoldItalicSmall = new Font(bfBoldItalic, 9);
Font fRegularBig = new Font(bfRegular, 20);
Font fBoldBig = new Font(bfBold, 20);
Font fItalicBig = new Font(bfItalic, 20);
Font fBoldItalicBig = new Font(bfBoldItalic, 20);
Usually, I create a helper class in which I create the BaseFont objects only once (they need to be reused), and I create getters for the Font objects.

Related

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());
}
}
}

How to import a custom java.awt.Font from a Font family with multiple TTF files? (An example is included)

I know that you can import a Font in Java with something like this:
File file = new File(fontPath);
Font font = Font.createFont(Font.TRUETYPE_FONT, file);
// alternative:
// Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(file));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
Then you would use for example font.deriveFont(Font.PLAIN, 20); to get the desired style and size.
Example
But now let's look as an example at the font Consolas, there you have four TTF files:
consola.ttf (Plain)
consolab.ttf (Bold)
consolai.ttf (Italic)
consolaz.ttf (Bold & Italic)
Of course you could just import consola.ttf with the method stated above, but then using font.deriveFont(Font.BOLD, 20); isn't the same as using consolab.ttf because the plain font was simply transformed to look like a bold font.
Example Pictures
Here I used the installed font with new Font("Consolas", Font.PLAIN, 20); and new Font("Consolas", Font.BOLD, 20); (as a side note, if the font is installed on the system you also get the right bold font if you use deriveFont(Font.BOLD);):
And this is consola.ttf, imported with createFont and derived bold font (both with size 20 like the example above):
Well when installed it isn't a problem, but I don't expect others to have a custom Font, so I want to put the TTFs into the jar file, so that I can import them during the initialization via getResourceAsStream(path).
Is there a way to import all relevant TTFs and then just call new Font("Custom Font Name", fontStyle, fontSize); so that it's used like an installed font (Picture 1), and that it doesn't looks like a derived 'fake' bold font (Picture 2)?
I'm not sure what exactly is the problem. You got all your TTF files and you have to import and register them. Following tests use DejaVu Sans fonts which are not installed on my system.
Test 1
Font f = Font.createFont(Font.TRUETYPE_FONT, new File("dvs.ttf"));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(f);
Font dvs = new Font("DejaVu Sans", Font.PLAIN, 20);
Here's an image with plain (dvs) and derived bold (dvs.deriveFont(Font.BOLD)) font.
Test 2
Font f = Font.createFont(Font.TRUETYPE_FONT, new File("dvs.ttf"));
Font fb = Font.createFont(Font.TRUETYPE_FONT, new File("dvsb.ttf"));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(f);
ge.registerFont(fb);
Font dvs = new Font("DejaVu Sans", Font.PLAIN, 20);
Font dvsb = new Font("DejaVu Sans", Font.BOLD, 20);
And here's an image with plain (dvs) and truly bold (dvsb) font.
You can confirm that correct file is used by looking at font2DHandle.
I also tested italic and bold italic and both worked as well as Font#createFont(int, InputStream) method.
Above approach works because fonts are mapped by their full name (e.g. Arial, Arial Bold etc.), so as long as your fonts are correctly named you can register multiple members of one family.

Unicode characters in iText PDF

I need help with iText I look at some Google result and some here but don't find anything that work for me. I need to use polish character in my pdf but i got nothing for no. Here is a code that I think is important if need something else write in comment:
private static Font bigFont = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
another
Paragraph par = new Paragraph(Łabadzak, bigFont);
Can any1 tell me what to do to make that Ł visible in pdf and other polish character
UPDATE
I fund this but dunno how to use it for my project
Polish character in itext PDF
You need a unicode font. Here is an example:
BaseFont bf = BaseFont.createFont("arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Paragraph p = new Paragraph("Şinasi ıssız ile ağaç", new Font(bf, 22));
document.add(p);
http://abdullahakay.blogspot.com/2011/11/java-itext-unicode.html
EDIT:
Here, the font file name arialuni.tff is a static resource directly under /src/main/resources/ and can be any Unicode Font File of your choice. Here's a list of free Unicode Font Files available online.
It depends on used font and encoding. i found something like this:
http://itext-general.2136553.n4.nabble.com/Polish-National-Characters-are-not-getting-displayed-in-the-PDF-created-by-iTExt-td2163833.html
There is example like this:
BaseFont bf = BaseFont.createFont("c:/windows/fonts/arial.ttf",
BaseFont.CP1250, BaseFont.EMBEDDED);
Font font = new Font(bf, 12);
String polish = "\u0104\u0105\u0106\u0107\u0118\u0119";
document.add(new Paragraph(polish, font));
Remember that some fonts does not contain polish national characters.
In case you are using com.itextpdf.kernel package you can use any encoding which is not present in PdfEncodings class
PdfWriter writer ;
writer = new PdfWriter( dest ) ;
PdfDocument pdf = new PdfDocument( writer ) ;
Document document = new Document( pdf ) ;
FontProgram fontProgram = FontProgramFactory.createFont( ) ;
PdfFont font = PdfFontFactory.createFont( fontProgram, "Cp1254" ) ;
document.setFont( font );
for turkish characters I used "Cp1254"

How to set a custom font's size and other attributes (bold, italic, etc) in Java SWING

Usually, when I initialize the fonts I want to use in my SWING applications, I do it this way:
public static final Font TITLEFONT = new Font("Calibri", Font.BOLD, 40);
Now, I have to do it a bit differently since I'm using some custom fonts from a .ttf file. I initialize the font this way:
try
{
InputStream is = OptionsValues.class.getResourceAsStream("fonts//KOMIKAX_.ttf");
TITLEFONT = Font.createFont(Font.TRUETYPE_FONT, is);
}
catch (Exception ex)
{
ex.printStackTrace();
System.err.println("Font not loaded. Using Calibri font.");
TITLEFONT = new Font("Calibri", Font.BOLD, 40);
}
I'm pretty sure it initializes it correctly (I can't tell for sure since it is too small for me to see), but I'd like to know how I can manually set the font's size (and if it's bold / other attributes) when loading a font this way.
Thanks a lot in advance!
createFont returns a Font and you can call deriveFont(...) on this, passing in a float for the point size, or an int and float for Font style and point size. I cannot say whether it will work for your particular situation, but it's worth a try.
e.g.,
InputStream is = OptionsValues.class.getResourceAsStream("fonts//KOMIKAX_.ttf");
TITLEFONT = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(Font.BOLD, 40f);
I'd simply use:
Font.ITALIC
Font.BOLD
Font.PLAIN

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());
}
}
}

Categories