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:fr.opensagres.odfdom.converter.pdf.internal.stylable.StylableParagraph.java

License:Open Source License

@SuppressWarnings("unchecked")
private void postProcessLineHeightAndBaseline() {
    // adjust line height and baseline
    Font font = getMostOftenUsedFont();
    if (font == null || font.getBaseFont() == null) {
        font = this.font;
    }//from  w w w . j a  v  a 2  s .co m
    if (font != null && font.getBaseFont() != null) {
        // iText and open office computes proportional line height differently
        // [iText] line height = coefficient * font size
        // [open office] line height = coefficient * (font ascender + font descender + font extra margin)
        // we have to increase paragraph line height to generate pdf similar to open office document
        // this algorithm may be inaccurate if fonts with different multipliers are used in this paragraph
        float size = font.getSize();
        float ascender = font.getBaseFont().getFontDescriptor(BaseFont.AWT_ASCENT, size);
        float descender = -font.getBaseFont().getFontDescriptor(BaseFont.AWT_DESCENT, size); // negative value
        float margin = font.getBaseFont().getFontDescriptor(BaseFont.AWT_LEADING, size);
        float multiplier = (ascender + descender + margin) / size;
        if (multipliedLeading > 0.0f) {
            setMultipliedLeading(getMultipliedLeading() * multiplier);
        }

        // iText seems to output text with baseline lower than open office
        // we raise all paragraph text by some amount
        // again this may be inaccurate if fonts with different size are used in this paragraph
        float itextdescender = -font.getBaseFont().getFontDescriptor(BaseFont.DESCENT, size); // negative
        float textRise = itextdescender + getTotalLeading() - font.getSize() * multiplier;
        ArrayList<Chunk> chunks = getChunks();
        for (Chunk chunk : chunks) {
            Font f = chunk.getFont();
            if (f != null) {
                // have to raise underline and strikethru as well
                float s = f.getSize();
                if (f.isUnderlined()) {
                    f.setStyle(f.getStyle() & ~Font.UNDERLINE);
                    chunk.setUnderline(s * 1 / 17, s * -1 / 7 + textRise);
                }
                if (f.isStrikethru()) {
                    f.setStyle(f.getStyle() & ~Font.STRIKETHRU);
                    chunk.setUnderline(s * 1 / 17, s * 1 / 4 + textRise);
                }
            }
            chunk.setTextRise(chunk.getTextRise() + textRise);
        }
    }
}

From source file:fr.opensagres.poi.xwpf.converter.pdf.internal.elements.StylableParagraph.java

License:Open Source License

/**
 * Adjust iText multiplied leading according the given font.
 * // ww  w . ja v a  2 s . com
 * @param font
 */
public void adjustMultipliedLeading(Font font) {
    if (originMultipliedLeading != null && font != null && font.getBaseFont() != null) {
        // iText and open office computes proportional line height differently
        // [iText] line height = coefficient * font size
        // [MS Word] line height = coefficient * (font ascender + font descender + font extra margin)
        // we have to increase paragraph line height to generate pdf similar to OOXML docx document
        // this algorithm may be inaccurate if fonts with different multipliers are used in this paragraph
        float size = font.getSize();
        float ascender = font.getBaseFont().getFontDescriptor(BaseFont.AWT_ASCENT, size);
        float descender = -font.getBaseFont().getFontDescriptor(BaseFont.AWT_DESCENT, size); // negative value
        float margin = font.getBaseFont().getFontDescriptor(BaseFont.AWT_LEADING, size);
        float multiplier = (ascender + descender + margin) / size;
        super.setMultipliedLeading(originMultipliedLeading * multiplier);
    }
}

From source file:fr.opensagres.poi.xwpf.converter.pdf.internal.FastPdfMapper.java

License:Open Source License

/**
 * Returns true if the iText font exists and false otherwise.
 * /*from ww w .  j av a2  s  .  co m*/
 * @param font
 * @return
 */
private boolean isFontExists(Font font) {
    // FIXME : is it like this to test that font exists?
    return font != null && font.getBaseFont() != null;
}

From source file:fr.opensagres.xdocreport.itext.extension.font.FontGroup.java

License:Open Source License

public static FontGroup getUnicodeGroup(char ch, Font font, Font fontAsian, Font fontComplex) {
    if (font != null && font.getBaseFont() != null) {
        if (font.getBaseFont().charExists(ch)) {
            return WESTERN;
        }/*from  ww  w . j av  a2  s.  c om*/
    }
    if (fontAsian != null && fontAsian.getBaseFont() != null) {
        if (fontAsian.getBaseFont().charExists(ch)) {
            return ASIAN;
        }
    }
    if (fontComplex != null && fontComplex.getBaseFont() != null) {
        if (fontComplex.getBaseFont().charExists(ch)) {
            return COMPLEX;
        }
    }
    return WESTERN;
}

From source file:mx.randalf.digital.ocr.hocrtopdf.HocrToPdf.java

License:Open Source License

public void hocrToPdf(File fImg, File fHtml, File fPdf) throws IOException, DocumentException, Exception {
    URL inputHOCRFile = null;/*from   w  w  w. j a  va  2  s  . c  o  m*/
    FileOutputStream outputPDFStream = null;
    // The resolution of a PDF file (using iText) is 72pt per inch
    float pointsPerInch = 72.0f;
    Source source = null;
    StartTag pageTag = null;
    Pattern imagePattern = null;
    Matcher imageMatcher = null;
    // Load the image
    Image pageImage = null;
    float dotsPerPointX;
    float dotsPerPointY;
    float pageImagePixelHeight;
    Document pdfDocument = null;
    PdfWriter pdfWriter = null;
    Font defaultFont = null;
    PdfContentByte cb = null;
    Pattern bboxPattern = null;
    Pattern bboxCoordinatePattern = null;
    StartTag ocrLineTag = null;

    try {
        try {
            inputHOCRFile = new URL("file://" + fHtml.getAbsolutePath());
        } catch (MalformedURLException e) {
            throw e;
        }
        try {
            outputPDFStream = new FileOutputStream(fPdf);
        } catch (FileNotFoundException e) {
            throw e;
        }

        // Using the jericho library to parse the HTML file
        source = new Source(inputHOCRFile);

        // Find the tag of class ocr_page in order to load the scanned image
        pageTag = source.findNextStartTag(0, "class", "ocr_page", false);
        imagePattern = Pattern.compile("image\\s+([^;]+)");
        imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
        if (!imageMatcher.find()) {
            throw new Exception("Could not find a tag of class \"ocr_page\", aborting.");
        }

        try {
            pageImage = Image.getInstance(new URL("file://" + fImg.getAbsolutePath()));
        } catch (MalformedURLException e) {
            throw e;
        }
        dotsPerPointX = pageImage.getDpiX() / pointsPerInch;
        dotsPerPointY = pageImage.getDpiY() / pointsPerInch;
        pageImagePixelHeight = pageImage.getHeight();
        pdfDocument = new Document(
                new Rectangle(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY));
        pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
        pdfDocument.open();

        // first define a standard font for our text
        defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK);

        // Put the text behind the picture (reverse for debugging)
        cb = pdfWriter.getDirectContentUnder();
        //PdfContentByte cb = pdfWriter.getDirectContent();

        pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
        pageImage.setAbsolutePosition(0, 0);
        // Put the image in front of the text (reverse for debugging)
        pdfWriter.getDirectContent().addImage(pageImage);
        //pdfWriter.getDirectContentUnder().addImage(pageImage);

        // In order to place text behind the recognised text snippets we are interested in the bbox property      
        bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
        // This pattern separates the coordinates of the bbox property
        bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
        // Only tags of the ocr_line class are interesting
        ocrLineTag = source.findNextStartTag(0, "class", "ocr_line", false);
        while (ocrLineTag != null) {
            au.id.jericho.lib.html.Element lineElement = ocrLineTag.getElement();
            Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
            if (bboxMatcher.find()) {
                // We found a tag of the ocr_line class containing a bbox property
                Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
                bboxCoordinateMatcher.find();
                int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))),
                        Integer.parseInt((bboxCoordinateMatcher.group(2))),
                        Integer.parseInt((bboxCoordinateMatcher.group(3))),
                        Integer.parseInt((bboxCoordinateMatcher.group(4))) };
                String line = lineElement.getContent().extractText();
                //               float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;

                // Put the text into the PDF
                cb.beginText();
                // Comment the next line to debug the PDF output (visible Text)
                cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                // TODO: Scale the text width to fit the OCR bbox
                cb.setFontAndSize(defaultFont.getBaseFont(), Math.round(bboxHeightPt));
                cb.moveText((float) (coordinates[0] / dotsPerPointX),
                        (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                cb.showText(line);
                cb.endText();
            }
            ocrLineTag = source.findNextStartTag(ocrLineTag.getEnd(), "class", "ocr_line", false);
        }
    } catch (NumberFormatException e) {
        throw e;
    } catch (MalformedURLException e) {
        throw e;
    } catch (FileNotFoundException e) {
        throw e;
    } catch (BadElementException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } catch (DocumentException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    } finally {
        if (pdfDocument != null) {
            pdfDocument.close();
        }
        if (outputPDFStream != null) {
            outputPDFStream.close();
        }
    }
}

From source file:net.sf.jasperreports.engine.export.JRPdfExporter.java

License:LGPL

/**
 *
 *///from w w w.j  ava 2  s  . co  m
protected Font getFont(Map attributes) {
    JRFont jrFont = new JRBaseFont(attributes);

    Exception initialException = null;

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

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

    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,
                    fileResolver);
        } 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:org.oss.pdfreporter.font.FontManager.java

License:Open Source License

@Override
IFontPeer getFontInternal(String fontname) {
    boolean embedded = false;
    String encoding = "CP1252";
    if (loadedFonts.containsKey(fontname)) {
        Alias alias = loadedFonts.get(fontname);
        fontname = alias.getName();//from   w  w w.  ja va 2 s  .c  o m
        encoding = alias.getEncoding();
        embedded = alias.isEmbed();
    }
    Font font;
    try {
        font = FontFactory.getFont(fontname, encoding, embedded, Font.UNDEFINED, Font.UNDEFINED, null);
    } catch (Exception e) {
        throw new RuntimeException("Unable to load Font: " + fontname + " with encoding:  " + encoding, e);
    }
    if (font == null) {
        throw new RuntimeException("Font: " + fontname + " not found.");
    }
    return new FontPeer(font.getBaseFont());
}

From source file:org.pz.platypus.plugin.html.HtmlFont.java

License:Open Source License

/**
 * Creates an iText Font object based on the class fields
 * @param f the PdfFont containing the parameters for the font
 * @return the iText Font object/*  w  ww  .  j  a v  a  2s .  co  m*/
 */
Font createFont(final HtmlFont f) {
    int style = 0;
    //       Color col  = new Color( color.getR(), color.getG(), color.getB() );
    Font font;

    String iTextFontName = createItextFontName(f);
    if (!isBase14Font(f.typeface)) {
        style = computeItextStyle();
    }

    try {
        font = FontFactory.getFont(iTextFontName, BaseFont.CP1252, BaseFont.EMBEDDED, size, style);
    } catch (Exception ex) {
        System.out.println("Exception in PdfFont.createFont() for FontFactory.getFont() for " + iTextFontName);
        font = null;
    }

    if (font == null || font.getBaseFont() == null) {
        gdd.logWarning("iText could not find font for: " + iTextFontName + ". Using Times-Roman");
        font = FontFactory.getFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED, size, style);
    }

    return (font);
}

From source file:org.pz.platypus.plugin.pdf.PdfFontFactory.java

License:Open Source License

/**
 * Creates an iText Font object based on a passed-in PdfFont
 *
 * @param f the PdfFont containing the parameters for the font
 * @return the iText Font object/*w  w  w  . j  a v  a2s. co m*/
 */
public Font createItextFont(final PdfFont f) {
    PdfFont pf = f;

    int style = 0;

    Font font = null;

    if (pf == null) {
        pf = new PdfFont(pdfData);
    }

    Color col = new Color(pf.getColor().getR(), pf.getColor().getG(), pf.getColor().getB());
    String iTextFontName = createItextFontName(pf);

    if (!isBase14Font(pf.getFace())) {
        style = computeItextStyle(pf);
        font = getIdentityHFont(iTextFontName, pf.getSize(), style, col);
    }

    if (font == null) { //TODO: identify when this would be the case.
        font = getCp1252Font(iTextFontName, pf.getSize(), style, col);
    }

    if (font == null || font.getBaseFont() == null) { //TODO: Make error msg use literals
        gdd.logWarning("iText could not find font for: " + iTextFontName + ". Using Times-Roman");
        font = FontFactory.getFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED, pf.getSize(),
                style, col);
    }

    // #if debug
    //        Set fonts = FontFactory.getRegisteredFonts();
    //        Set families = FontFactory.getRegisteredFamilies();

    return (font);
}

From source file:org.pz.platypus.plugin.rtf.RtfFont.java

License:Open Source License

/**
 * Creates an iText Font object based on the class fields
 * @param f the PdfFont containing the parameters for the font
 * @return the iText Font object/*from ww w  .  j a  va 2  s. co m*/
 */
Font createFont(final RtfFont f) {
    int style = 0;
    //       Color col  = new Color( color.getR(), color.getG(), color.getB() );
    Font font = null;

    String iTextFontName = createItextFontName(f);
    if (iTextFontName == null) { // if the font is not in the fontlist nor is it a Base14 font
        f.typeface = DefaultValues.FONT_TYPEFACE;
        iTextFontName = BaseFont.TIMES_ROMAN;
    }

    if (!isBase14Font(f.typeface)) {
        style = computeItextStyle();
        font = getIdentityHFont(iTextFontName, size, style);
    }

    if (font == null) {
        font = getCp1252Font(iTextFontName, size, style);
    }

    if (font == null || font.getBaseFont() == null) { //TODO: Make error msg use literals
        gdd.logWarning("iText could not find font for: " + iTextFontName + ". Using Times-Roman");
        font = FontFactory.getFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED, size, style);
    }

    return (font);
}