How to choose the optimal size for a font?

后端 未结 2 2051
梦如初夏
梦如初夏 2020-12-21 18:10

I\'m creating a pdf document with a grid table based on the PdfPTable in itextpdf. The input data arrives as a java String[][] with all the cells filled. For each column, I

相关标签:
2条回答
  • 2020-12-21 18:51

    Simple use follow syntax.

    PdfPTable table = new PdfPTable(1);
    table.setWidthPercentage(100);
    table.addCell(new Phrase("Name", FontFactory.getFont(
                        FontFactory.HELVETICA, 8, Font.BOLD)));
    
    0 讨论(0)
  • 2020-12-21 19:12

    I've read your question three times, and I don't understand it.

    Let me try to rephrase it: Given a certain available width, how do I define the font size for a snippet of text, so that it matches the available width.

    First you need a BaseFont object. For instance:

    BaseFont bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    

    Now you can ask the base font for the width of this String in 'normalized 1000 units' (these are units used in 'Glyph space'; see ISO-32000-1 for more info):

    float glyphWidth = bf.getWidth("WHAT IS THE WIDTH OF THIS STRING?");
    

    Now we can convert these 'normalized 1000 units' to an actual size in points (actually user units, but let's assume that 1 user unit = 1 pt for the sake of simplicity).

    For instance: the width of the text "WHAT IS THE WIDTH OF THIS STRING?" when using Courier with size 16pt is:

     float width = glyphWidth * 0.001f * 16f;
    

    Your question is different: you want to know the font size for a given width. That's done like this:

     float fontSize = 1000 * width / glyphwidth;
    

    I hope this answers your question. If not, please rephrase.

    0 讨论(0)
提交回复
热议问题