Search code examples
javafontspdfbox

Can I get load a PDFont from a font name as string?


I wondered if there is a way to load a PDType1Font by the font name. In the 1.8.x versions, you could just load a font by a string static PDType1Font getStandardFont(String name) A convenience method to get one of the standard 14 font from name. Is there a way to do this in the 2.0.x versions?


Solution

  • The code does still exist in TextToPDF.java however it is all private. I would follow the suggestion of mkl: Just add a PdfUtil.java to your code where you do the following:

    public class PdfUtils{
    
     private static final Map<String, PDType1Font> STANDARD_14 = new HashMap<String, PDType1Font>();
    
     static{
        STANDARD_14.put(PDType1Font.TIMES_ROMAN.getBaseFont(), PDType1Font.TIMES_ROMAN);
        STANDARD_14.put(PDType1Font.TIMES_BOLD.getBaseFont(), PDType1Font.TIMES_BOLD);
        STANDARD_14.put(PDType1Font.TIMES_ITALIC.getBaseFont(), PDType1Font.TIMES_ITALIC);
        STANDARD_14.put(PDType1Font.TIMES_BOLD_ITALIC.getBaseFont(), PDType1Font.TIMES_BOLD_ITALIC);
        STANDARD_14.put(PDType1Font.HELVETICA.getBaseFont(), PDType1Font.HELVETICA);
        STANDARD_14.put(PDType1Font.HELVETICA_BOLD.getBaseFont(), PDType1Font.HELVETICA_BOLD);
        STANDARD_14.put(PDType1Font.HELVETICA_OBLIQUE.getBaseFont(), PDType1Font.HELVETICA_OBLIQUE);
        STANDARD_14.put(PDType1Font.HELVETICA_BOLD_OBLIQUE.getBaseFont(), PDType1Font.HELVETICA_BOLD_OBLIQUE);
        STANDARD_14.put(PDType1Font.COURIER.getBaseFont(), PDType1Font.COURIER);
        STANDARD_14.put(PDType1Font.COURIER_BOLD.getBaseFont(), PDType1Font.COURIER_BOLD);
        STANDARD_14.put(PDType1Font.COURIER_OBLIQUE.getBaseFont(), PDType1Font.COURIER_OBLIQUE);
        STANDARD_14.put(PDType1Font.COURIER_BOLD_OBLIQUE.getBaseFont(), PDType1Font.COURIER_BOLD_OBLIQUE);
        STANDARD_14.put(PDType1Font.SYMBOL.getBaseFont(), PDType1Font.SYMBOL);
        STANDARD_14.put(PDType1Font.ZAPF_DINGBATS.getBaseFont(), PDType1Font.ZAPF_DINGBATS);
     }
     
     private PdfUtils(){}
    
     public static PDType1Font getStandardFont(String name){
      return STANDARD_14.get(name);
     }
    }