Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iText, What's going on with Font, BaseFont and createFont()?

Tags:

itext

There is a lot of mystery to me about what is going on with font and basefont. Especially when it comes to the constructor. The iText website gives this line as example code for new fonts

 BaseFont unicode = BaseFont.createFont("c:/windows/fonts/arialuni.ttf", 
                        BaseFont.IDENTITY_H, 
                        BaseFont.EMBEDDED);

I can get this call to work:

BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1257, 
                  BaseFont.EMBEDDED);

But if I replace BaseFont.CP1257 with say BaseFont.HELVETICA then it doesn't work and I get a page that says "failed to load pdf document."

I tried looking through the class file and I can't seem to figure out what that second parameter is (I'm assuming it is something like a backup font in case the first font doesn't work, like in HTML) and I can't figure out why some fonts would work and not others.

like image 886
Chase Roberts Avatar asked Jul 06 '12 16:07

Chase Roberts


2 Answers

To load it from inside your jar use the leading slash otherwise, just 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: https://code.google.com/p/jhocr/source/browse/trunk/src/main/java/com/googlecode/jhocr/converter/HocrPageProcessor.java

like image 183
4F2E4A2E Avatar answered Nov 17 '22 20:11

4F2E4A2E


The second parameter is the encoding.

Refer to documentation here for more information.

like image 41
billfredtom Avatar answered Nov 17 '22 20:11

billfredtom