Example usage for com.lowagie.text Font getBaseFont

List of usage examples for com.lowagie.text Font getBaseFont

Introduction

In this page you can find the example usage for com.lowagie.text Font getBaseFont.

Prototype

public BaseFont getBaseFont() 

Source Link

Document

Gets the BaseFont inside this object.

Usage

From source file:com.dlya.facturews.DlyaPdfExporter2.java

License:Open Source License

/**
 * Creates a PDF font./* w  w  w  .  j  a  v  a  2 s.  co  m*/
 * 
 * @param attributes the text attributes of the font
 * @param locale the locale for which to create the font
 * @param setFontLines whether to set underline and strikethrough as font style
 * @return the PDF font for the specified attributes
 */
@SuppressWarnings("deprecation")
protected Font getFont(Map<Attribute, Object> attributes, Locale locale, boolean setFontLines) {
    JRFont jrFont = new JRBaseFont(attributes);

    Exception initialException = null;

    Color forecolor = (Color) attributes.get(TextAttribute.FOREGROUND);

    // use the same font scale ratio as in JRStyledText.getAwtAttributedString
    float fontSizeScale = 1f;
    Integer scriptStyle = (Integer) attributes.get(TextAttribute.SUPERSCRIPT);
    if (scriptStyle != null && (TextAttribute.SUPERSCRIPT_SUB.equals(scriptStyle)
            || TextAttribute.SUPERSCRIPT_SUPER.equals(scriptStyle))) {
        fontSizeScale = 2f / 3;
    }

    Font font = null;
    PdfFont pdfFont = null;
    FontKey key = new FontKey(jrFont.getFontName(), jrFont.isBold(), jrFont.isItalic());

    if (fontMap != null && fontMap.containsKey(key)) {
        pdfFont = pdfFontMap.get(key);
    } else {
        FontInfo fontInfo = FontUtil.getInstance(jasperReportsContext).getFontInfo(jrFont.getFontName(),
                locale);
        if (fontInfo == null) {
            //fontName NOT found in font extensions
            pdfFont = new PdfFont(jrFont.getPdfFontName(), jrFont.getPdfEncoding(), jrFont.isPdfEmbedded());
        } else {
            //fontName found in font extensions
            FontFamily family = fontInfo.getFontFamily();
            FontFace face = fontInfo.getFontFace();
            int faceStyle = java.awt.Font.PLAIN;

            if (face == null) {
                //fontName matches family name in font extension
                if (jrFont.isBold() && jrFont.isItalic()) {
                    face = family.getBoldItalicFace();
                    faceStyle = java.awt.Font.BOLD | java.awt.Font.ITALIC;
                }

                if (face == null && jrFont.isBold()) {
                    face = family.getBoldFace();
                    faceStyle = java.awt.Font.BOLD;
                }

                if (face == null && jrFont.isItalic()) {
                    face = family.getItalicFace();
                    faceStyle = java.awt.Font.ITALIC;
                }

                if (face == null) {
                    face = family.getNormalFace();
                    faceStyle = java.awt.Font.PLAIN;
                }

                //               if (face == null)
                //               {
                //                  throw new JRRuntimeException("Font family '" + family.getName() + "' does not have the normal font face.");
                //               }
            } else {
                //fontName matches face name in font extension; not family name
                faceStyle = fontInfo.getStyle();
            }

            String pdfFontName = null;
            int pdfFontStyle = java.awt.Font.PLAIN;
            if (jrFont.isBold() && jrFont.isItalic()) {
                pdfFontName = family.getBoldItalicPdfFont();
                pdfFontStyle = java.awt.Font.BOLD | java.awt.Font.ITALIC;
            }

            if (pdfFontName == null && jrFont.isBold()) {
                pdfFontName = family.getBoldPdfFont();
                pdfFontStyle = java.awt.Font.BOLD;
            }

            if (pdfFontName == null && jrFont.isItalic()) {
                pdfFontName = family.getItalicPdfFont();
                pdfFontStyle = java.awt.Font.ITALIC;
            }

            if (pdfFontName == null) {
                pdfFontName = family.getNormalPdfFont();
                pdfFontStyle = java.awt.Font.PLAIN;
            }

            if (pdfFontName == null) {
                //in theory, face file cannot be null here
                pdfFontName = (face == null || face.getFile() == null ? jrFont.getPdfFontName()
                        : face.getFile());
                pdfFontStyle = faceStyle;//FIXMEFONT not sure this is correct, in case we inherit pdfFontName from default properties
            }

            //            String ttf = face.getFile();
            //            if (ttf == null)
            //            {
            //               throw new JRRuntimeException("The '" + face.getName() + "' font face in family '" + family.getName() + "' returns a null file.");
            //            }

            pdfFont = new PdfFont(pdfFontName,
                    family.getPdfEncoding() == null ? jrFont.getPdfEncoding() : family.getPdfEncoding(),
                    family.isPdfEmbedded() == null ? jrFont.isPdfEmbedded()
                            : family.isPdfEmbedded().booleanValue(),
                    jrFont.isBold() && ((pdfFontStyle & java.awt.Font.BOLD) == 0),
                    jrFont.isItalic() && ((pdfFontStyle & java.awt.Font.ITALIC) == 0));
        }
    }

    int pdfFontStyle = (pdfFont.isPdfSimulatedBold() ? Font.BOLD : 0)
            | (pdfFont.isPdfSimulatedItalic() ? Font.ITALIC : 0);
    if (setFontLines) {
        pdfFontStyle |= (jrFont.isUnderline() ? Font.UNDERLINE : 0)
                | (jrFont.isStrikeThrough() ? Font.STRIKETHRU : 0);
    }

    try {
        font = FontFactory.getFont(pdfFont.getPdfFontName(), pdfFont.getPdfEncoding(), pdfFont.isPdfEmbedded(),
                jrFont.getFontSize() * fontSizeScale, pdfFontStyle, forecolor);

        // check if FontFactory didn't find the font
        if (font.getBaseFont() == null && font.family() == Font.UNDEFINED) {
            font = null;
        }
    } catch (Exception e) {
        initialException = e;
    }

    if (font == null) {
        byte[] bytes = null;

        try {
            bytes = RepositoryUtil.getInstance(jasperReportsContext)
                    .getBytesFromLocation(pdfFont.getPdfFontName());
        } catch (JRException e) {
            throw //NOPMD
            new JRRuntimeException("Could not load the following font : " + "\npdfFontName   : "
                    + pdfFont.getPdfFontName() + "\npdfEncoding   : " + pdfFont.getPdfEncoding()
                    + "\nisPdfEmbedded : " + pdfFont.isPdfEmbedded(), initialException);
        }

        BaseFont baseFont = null;

        try {
            baseFont = BaseFont.createFont(pdfFont.getPdfFontName(), pdfFont.getPdfEncoding(),
                    pdfFont.isPdfEmbedded(), true, bytes, null);
        } catch (DocumentException e) {
            throw new JRRuntimeException(e);
        } catch (IOException e) {
            throw new JRRuntimeException(e);
        }

        font = new Font(baseFont, jrFont.getFontSize() * fontSizeScale, pdfFontStyle, forecolor);
    }

    return font;
}

From source file:com.gtdfree.test.PDFTestFont.java

License:Open Source License

/**
 * Fonts and encoding./*w  ww  .j  a  v a  2  s  .co m*/
 * @param args no arguments needed
 */
public static void main(String[] args) {

    System.out.println("Encodings");

    String[] names = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();

    System.out.println(Arrays.toString(names));

    /*System.out.println("---");
    try {
    System.getProperties().store(System.out, "");
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    System.out.println("---");*/
    //System.out.println(System.getenv());
    //System.out.println("---");

    //String font= System.getProperty("java.home")+"/lib/fonts/LucidaBrightRegular.ttf";
    //String font= "fonts/DejaVuSans.ttf";

    //byte[] ttf= ApplicationHelper.loadResource(font);

    try {
        // step 1
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream("encodingfont.pdf"));
        // step 3
        document.open();
        // step 4
        String all[] = { "Symbol", "ZapfDingbats" };
        Font hex = new Font(Font.HELVETICA, 5);
        for (int z = 0; z < all.length; ++z) {
            String file = all[z];
            document.add(new Paragraph(
                    "Unicode equivalence for the font \"" + file + "\" with the encoding \"" + file + "\"\n"));
            /*char tb[];
            if (z == 0)
               tb = SYMBOL_TABLE;
            else
               tb = DINGBATS_TABLE;*/
            BaseFont bf;
            if (z == 2) {
                bf = BaseFont.createFont(file, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, null, null);
                ;
            } else {
                bf = BaseFont.createFont(file, file, true);
            }
            Font f = new Font(bf, 12);
            PdfPTable table = new PdfPTable(16);
            table.setWidthPercentage(100);
            table.getDefaultCell().setBorderWidth(1);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            for (char k = 0; k < Character.MAX_VALUE; ++k) {
                char c = k;
                if (bf.charExists(c)) {
                    Phrase ph = new Phrase(12, new String(new char[] { c }), f);
                    ph.add(new Phrase(12, "\n" + Integer.toString(c) + "\n" + cst(c), hex));
                    table.addCell(ph);
                } /*
                  else {
                     Phrase ph = new Phrase("\u00a0");
                     ph.add(new Phrase(12, "\n\n" + cst(c), hex));
                     table.addCell(ph);
                  }*/
            }
            document.add(table);
            document.newPage();
        }
        // step 5
        document.close();

        FontFactory.registerDirectories();

        Set<?> s = FontFactory.getRegisteredFonts();

        System.out.println("Fonts: " + s);

        s = FontFactory.getRegisteredFamilies();

        System.out.println("Families: " + s);

        ArrayList<Font> f = new ArrayList<Font>(s.size());

        for (Object name : s) {

            try {
                f.add(FontFactory.getFont(name.toString(), "UTF-8", true, 12, Font.NORMAL, Color.BLACK, true));
            } catch (Exception e) {
                f.add(FontFactory.getFont(name.toString(), "UTF-8", false, 12, Font.NORMAL, Color.BLACK, true));
            }

        }

        Collections.sort(f, new Comparator<Font>() {
            @Override
            public int compare(Font o1, Font o2) {
                return o1.getFamilyname().compareTo(o2.getFamilyname());
            }
        });

        for (Font ff : f) {

            if (ff.getBaseFont() == null) {
                continue;
            }
            System.out.println(ff.getFamilyname() + " " + ff.getBaseFont().isEmbedded());

        }

    } catch (Exception de) {
        de.printStackTrace();
    }
}

From source file:com.krawler.accounting.fontsetting.FontFamily.java

License:Open Source License

public void addFont(FontContext context, Font font) {
    if (font.getBaseFont() == null) {
        BaseFont bf = font.getCalculatedBaseFont(true);
        font = new Font(bf, font.getSize(), font.getCalculatedStyle(), font.getColor());
    }/*from   w  w  w  . j  a v a2  s .  c  o m*/
    fontsMap.put(context, font);
    if (primaryFont == null)
        primaryFont = font;
}

From source file:com.krawler.accounting.fontsetting.FontFamily.java

License:Open Source License

public void addFont(FontContext context, Font font, boolean isPrimary) {
    if (font.getBaseFont() == null) {
        BaseFont bf = font.getCalculatedBaseFont(true);
        font = new Font(bf, font.getSize(), font.getCalculatedStyle(), font.getColor());
    }/*  w  w w.ja  va2s.  c  o m*/
    fontsMap.put(context, font);
    if (isPrimary)
        primaryFont = font;
}

From source file:com.krawler.accounting.fontsetting.FontFamilySelector.java

License:Open Source License

public void addFontFamily(FontFamily fontFamily) {
    Font font = fontFamily.getPrimaryFont();

    if (font.getBaseFont() == null) {
        BaseFont bf = font.getCalculatedBaseFont(true);
        font = new Font(bf, font.getSize(), font.getCalculatedStyle(), font.getColor());
    }//from  ww  w.  ja va2s . c o  m

    families.add(fontFamily);
}

From source file:com.krawler.accounting.fontsetting.FontFamilySelector.java

License:Open Source License

public Phrase process(String text, FontContext context, Color color, Float size, Integer style) {
    int fsize = families.size();
    if (fsize == 0)
        throw new IndexOutOfBoundsException("No font is defined.");
    if (text == null)
        text = "";
    char cc[] = text.toCharArray();
    int len = cc.length;
    StringBuffer sb = new StringBuffer();
    Font font = null;
    int lastidx = -1;
    Phrase ret = new Phrase();
    for (int k = 0; k < len; ++k) {
        char c = cc[k];
        if (c == '\n' || c == '\r') {
            sb.append(c);//from  w w  w . ja v  a 2 s .c  om
            continue;
        }

        if (Utilities.isSurrogatePair(cc, k)) {
            int u = Utilities.convertToUtf32(cc, k);
            for (int f = 0; f < fsize; ++f) {
                font = (Font) families.get(f).getPrimaryFont();
                if (font.getBaseFont().charExists(u)) {
                    if (lastidx != f) {
                        if (sb.length() > 0 && lastidx != -1) {
                            FontFamily fm = families.get(lastidx);
                            Font fnt = fm.getFont(context);
                            applyPropertiesToFont(fnt, color, size, style);
                            Chunk ck = new Chunk(sb.toString(), fnt);
                            ret.add(ck);
                            sb.setLength(0);
                        }
                        lastidx = f;
                    }
                    sb.append(c);
                    sb.append(cc[++k]);
                    break;
                }
            }
        } else {
            for (int f = 0; f < fsize; ++f) {
                font = (Font) families.get(f).getPrimaryFont();
                if (font.getBaseFont().charExists(c)) {
                    if (lastidx != f) {
                        if (sb.length() > 0 && lastidx != -1) {
                            FontFamily fm = families.get(lastidx);
                            Font fnt = fm.getFont(context);
                            applyPropertiesToFont(fnt, color, size, style);
                            Chunk ck = new Chunk(sb.toString(), fnt);
                            ret.add(ck);
                            sb.setLength(0);
                        }
                        lastidx = f;
                    }
                    sb.append(c);
                    break;
                }
            }
        }
    }
    if (sb.length() > 0) {
        FontFamily fm = families.get(lastidx == -1 ? 0 : lastidx);
        Font fnt = fm.getFont(context);
        applyPropertiesToFont(fnt, color, size, style);
        Chunk ck = new Chunk(sb.toString(), fnt);
        ret.add(ck);
    }
    return ret;
}

From source file:com.krawler.common.fontsettings.FontFamilySelector.java

License:Open Source License

public Phrase process(String text, FontContext context, Color color, Float size, Integer style) {
    int fsize = families.size();
    if (fsize == 0)
        throw new IndexOutOfBoundsException("No font is defined.");
    if (text == null)
        text = "";
    char cc[] = text.toCharArray();
    int len = cc.length;
    StringBuffer sb = new StringBuffer();
    Font font = null;
    int lastidx = -1;
    Phrase ret = new Phrase();
    for (int k = 0; k < len; ++k) {
        char c = cc[k];
        if (c == '\n' || c == '\r') {
            sb.append(c);//from   w ww .ja v a  2 s .c o  m
            continue;
        }
        if (Utilities.isSurrogatePair(cc, k)) {
            int u = Utilities.convertToUtf32(cc, k);
            for (int f = 0; f < fsize; ++f) {
                font = (Font) families.get(f).getPrimaryFont();
                if (font.getBaseFont().charExists(u)) {
                    if (lastidx != f) {
                        if (sb.length() > 0 && lastidx != -1) {
                            FontFamily fm = families.get(lastidx);
                            Font fnt = fm.getFont(context);
                            applyPropertiesToFont(fnt, color, size, style);
                            Chunk ck = new Chunk(sb.toString(), fnt);
                            ret.add(ck);
                            sb.setLength(0);
                        }
                        lastidx = f;
                    }
                    sb.append(c);
                    sb.append(cc[++k]);
                    break;
                }
            }
        } else {
            for (int f = 0; f < fsize; ++f) {
                font = (Font) families.get(f).getPrimaryFont();
                if (font.getBaseFont().charExists(c)) {
                    if (lastidx != f) {
                        if (sb.length() > 0 && lastidx != -1) {
                            FontFamily fm = families.get(lastidx);
                            Font fnt = fm.getFont(context);
                            applyPropertiesToFont(fnt, color, size, style);
                            Chunk ck = new Chunk(sb.toString(), fnt);
                            ret.add(ck);
                            sb.setLength(0);
                        }
                        lastidx = f;
                    }
                    sb.append(c);
                    break;
                }
            }
        }
    }
    if (sb.length() > 0) {
        FontFamily fm = families.get(lastidx == -1 ? 0 : lastidx);
        Font fnt = fm.getFont(context);
        applyPropertiesToFont(fnt, color, size, style);
        Chunk ck = new Chunk(sb.toString(), fnt);
        ret.add(ck);
    }
    return ret;
}

From source file:com.krawler.common.fontsettings.FontFamilySelector.java

License:Open Source License

public Chunk processChunk(String text, FontContext context, Color color, Float size, Integer style) {
    Chunk ck = null;//from   w w w .  j a  v a2 s. c  o  m
    int fsize = families.size();
    if (fsize == 0)
        throw new IndexOutOfBoundsException("No font is defined.");
    if (text == null)
        text = "";
    char cc[] = text.toCharArray();
    int len = cc.length;
    StringBuffer sb = new StringBuffer();
    Font font = null;
    int lastidx = -1;
    for (int k = 0; k < len; ++k) {
        char c = cc[k];
        if (c == '\n' || c == '\r') {
            sb.append(c);
            continue;
        }
        if (Utilities.isSurrogatePair(cc, k)) {
            int u = Utilities.convertToUtf32(cc, k);
            for (int f = 0; f < fsize; ++f) {
                font = (Font) families.get(f).getPrimaryFont();
                if (font.getBaseFont().charExists(u)) {
                    if (lastidx != f) {
                        if (sb.length() > 0 && lastidx != -1) {
                            FontFamily fm = families.get(lastidx);
                            Font fnt = fm.getFont(context);
                            applyPropertiesToFont(fnt, color, size, style);
                        }
                        lastidx = f;
                    }
                    sb.append(c);
                    sb.append(cc[++k]);
                    break;
                }
            }
        } else {
            for (int f = 0; f < fsize; ++f) {
                font = (Font) families.get(f).getPrimaryFont();
                if (font.getBaseFont().charExists(c)) {
                    if (lastidx != f) {
                        if (sb.length() > 0 && lastidx != -1) {
                            FontFamily fm = families.get(lastidx);
                            Font fnt = fm.getFont(context);
                            applyPropertiesToFont(fnt, color, size, style);
                        }
                        lastidx = f;
                    }
                    sb.append(c);
                    break;
                }
            }
        }
    }
    if (sb.length() > 0) {
        FontFamily fm = families.get(lastidx == -1 ? 0 : lastidx);
        Font fnt = fm.getFont(context);
        applyPropertiesToFont(fnt, color, size, style);
        ck = new Chunk(sb.toString(), fnt);
    }
    return ck;
}

From source file:corner.orm.tapestry.jasper.exporter.CornerPdfExporter.java

License:Apache License

/**
 * ?,,./*from   ww  w  .jav  a  2 s.  c o  m*/
 * @see net.sf.jasperreports.engine.export.JRPdfExporter#getFont(java.util.Map)
 */
protected Font getFont(Map attributes) {
    JRFont jrFont = new JRBaseFont(attributes);

    Exception initialException = null;

    Color forecolor = (Color) attributes.get(TextAttribute.FOREGROUND);
    /*
    if (forecolor == null)
    {
       forecolor = Color.black;
    }
    */

    Font font = null;
    PdfFont pdfFont = null;
    FontKey key = new FontKey(jrFont.getFontName(), jrFont.isBold(), jrFont.isItalic());

    if (fontMap != null && fontMap.containsKey(key)) {
        pdfFont = (PdfFont) fontMap.get(key);
    } else {
        pdfFont = new PdfFont(jrFont.getPdfFontName(), jrFont.getPdfEncoding(), jrFont.isPdfEmbedded(),
                jrFont.isBold(), jrFont.isItalic());
    }

    try {
        font = FontFactory.getFont(pdfFont.getPdfFontName(), pdfFont.getPdfEncoding(), pdfFont.isPdfEmbedded(),
                jrFont.getFontSize(),
                (pdfFont.isPdfSimulatedBold() ? Font.BOLD : 0)
                        | (pdfFont.isPdfSimulatedItalic() ? Font.ITALIC : 0)
                        | (jrFont.isUnderline() ? Font.UNDERLINE : 0)
                        | (jrFont.isStrikeThrough() ? Font.STRIKETHRU : 0),
                forecolor);

        // check if FontFactory didn't find the font
        if (font.getBaseFont() == null && font.family() == Font.UNDEFINED) {
            font = null;
        }
    } catch (Exception e) {
        initialException = e;
    }

    if (font == null) {
        byte[] bytes = null;

        try {
            bytes = JRLoader.loadBytesFromLocation(pdfFont.getPdfFontName(), classLoader, urlHandlerFactory);
        } catch (JRException e) {
            throw new JRRuntimeException("Could not load the following font : " + "\npdfFontName   : "
                    + pdfFont.getPdfFontName() + "\npdfEncoding   : " + pdfFont.getPdfEncoding()
                    + "\nisPdfEmbedded : " + pdfFont.isPdfEmbedded(), initialException);
        }

        BaseFont baseFont = null;

        try {
            baseFont = BaseFont.createFont(pdfFont.getPdfFontName(), pdfFont.getPdfEncoding(),
                    pdfFont.isPdfEmbedded(), true, bytes, null);
        } catch (DocumentException e) {
            throw new JRRuntimeException(e);
        } catch (IOException e) {
            throw new JRRuntimeException(e);
        }

        font = new Font(baseFont, jrFont.getFontSize(),
                ((pdfFont.isPdfSimulatedBold()) ? Font.BOLD : 0)
                        | ((pdfFont.isPdfSimulatedItalic()) ? Font.ITALIC : 0)
                        | (jrFont.isUnderline() ? Font.UNDERLINE : 0)
                        | (jrFont.isStrikeThrough() ? Font.STRIKETHRU : 0),
                forecolor);
    }

    return font;
}

From source file:de.cuseb.bilderbuch.pdf.PdfController.java

License:Open Source License

@RequestMapping(value = "/pdf", method = RequestMethod.GET)
public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) {

    try {/*  w ww .j  a  va2s. c  om*/
        PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest");
        httpServletResponse.setContentType("application/pdf");

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream());
        writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB);

        //document.addAuthor(pdfRequest.getAuthor());
        //document.addTitle(pdfRequest.getTitle());
        document.setPageSize(
                new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148)));
        document.open();

        FontFactory.defaultEmbedding = true;
        FontFactory.register("IndieRock.ttf", "IndieRock");
        Font font = FontFactory.getFont("IndieRock");
        BaseFont baseFont = font.getBaseFont();
        PdfContentByte cb = writer.getDirectContent();

        Iterator<PdfPage> pages = pdfRequest.getPages().iterator();
        while (pages.hasNext()) {

            PdfPage page = pages.next();
            if (page.getImage() != null) {

                Image image = Image.getInstance(new URL(page.getImage().getUrl()));
                image.setDpi(300, 300);
                image.setAbsolutePosition(0f, 0f);
                image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight());
                document.add(image);

                cb.saveState();
                cb.beginText();
                cb.setColorFill(Color.WHITE);
                cb.moveText(10f, 10f);
                cb.setFontAndSize(baseFont, 18);
                cb.showText(page.getSentence());
                cb.endText();
                cb.restoreState();

                if (pages.hasNext()) {
                    document.newPage();
                }
            }
        }
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}