Example usage for org.apache.pdfbox.pdmodel.font PDFont getStringWidth

List of usage examples for org.apache.pdfbox.pdmodel.font PDFont getStringWidth

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.font PDFont getStringWidth.

Prototype

public float getStringWidth(String text) throws IOException 

Source Link

Document

Returns the width of the given Unicode string.

Usage

From source file:airviewer.AnnotationGenerator.java

/**
 * /*from w  ww . j  av a 2  s .c  o m*/
 * @param document
 * @param page
 * @param subtype
 * @param position
 * @param borderColor
 * @param fillColor
 * @param borderWidth
 * @param contents
 * @return 
 */
public static PDAnnotationMarkup makeAnnotation(PDDocument document, PDPage page, String subtype,
        PDRectangle position, PDColor borderColor, PDColor fillColor, float borderWidth, String contents) {
    assert null != document;
    assert null != page;
    assert null != subtype;
    assert null != position;

    PDAnnotationMarkup result = null;

    try {
        if (null != contents && 0 < contents.length()) {
            PDFont font = FONT;
            final float fontSize = FONT_SIZE_PDF_POINTS;
            final float lineSpacing = LINE_SPACE_SIZE_PDF_POINTS;
            float width = max(position.getWidth(),
                    font.getStringWidth(contents) * fontSize / AnnotationGenerator.SIZE_UNITS_PER_PDF_POINT);
            position.setUpperRightX(position.getLowerLeftX() + width);
        }

        PDAnnotationSquareCircle a = new PDAnnotationSquareCircle(subtype);
        a.setAnnotationName(new UID().toString());
        a.setContents(contents);
        a.setRectangle(position);

        if (null != fillColor) {
            a.setInteriorColor(fillColor);
        }

        if (0 < borderWidth) {
            PDBorderStyleDictionary borderStyle = new PDBorderStyleDictionary();
            borderStyle.setWidth(borderWidth);
            a.setBorderStyle(borderStyle);
            if (null != borderColor) {
                a.setColor(borderColor);

            }
        }

        // The following lines are needed for PDFRenderer to render 
        // annotations. Preview and Acrobat don't seem to need these.
        if (null == a.getAppearance()) {
            a.setAppearance(new PDAppearanceDictionary());
            PDAppearanceStream annotationAppearanceStream = AnnotationGenerator.generateAppearanceStream(a,
                    document, page, true);
            a.getAppearance().setNormalAppearance(annotationAppearanceStream);
        }

        result = a;

    } catch (IOException | NullPointerException ex) {
        Logger.getLogger(EllipseAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:airviewer.EllipseAnnotationMaker.java

License:Apache License

/**
 * /*  w  ww.j av a2s.c o  m*/
 * @param document
 * @param arguments(pageNumber, lowerLeftX, lowerLeftY, width, height, contents)
 * @return 
 */
public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) {
    assert null != arguments && arguments.size() == 6;
    assert null != document;

    List<PDAnnotation> result;

    try {
        int pageNumber = parseInt(arguments.get(0));
        float lowerLeftX = parseFloat(arguments.get(1));
        float lowerLeftY = parseFloat(arguments.get(2));
        float width = parseFloat(arguments.get(3));
        float height = parseFloat(arguments.get(4));
        String contents = arguments.get(5);

        PDFont font = PDType1Font.HELVETICA_OBLIQUE;
        final float fontSize = 16.0f; // Or whatever font size you want.
        //final float lineSpacing = 4.0f;
        width = max(width, font.getStringWidth(contents) * fontSize / 1000.0f);
        //final float textHeight = fontSize + lineSpacing;

        try {
            PDPage page = document.getPage(pageNumber);
            PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDColor black = new PDColor(new float[] { 0, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
            borderThick.setWidth(72 / 12); // 12th inch
            PDRectangle position = new PDRectangle();
            position.setLowerLeftX(lowerLeftX);
            position.setLowerLeftY(lowerLeftY);
            position.setUpperRightX(lowerLeftX + width);
            position.setUpperRightY(lowerLeftY + height);

            PDAnnotationSquareCircle aCircle = new PDAnnotationSquareCircle(
                    PDAnnotationSquareCircle.SUB_TYPE_CIRCLE);
            aCircle.setAnnotationName(new UID().toString());
            aCircle.setContents(contents);
            PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE);
            aCircle.setInteriorColor(fillColor);
            aCircle.setColor(red);
            aCircle.setBorderStyle(borderThick);
            aCircle.setRectangle(position);

            result = new ArrayList<>(page.getAnnotations()); // Copy
            page.getAnnotations().add(aCircle);

            // The following lines are needed for PDFRenderer to render 
            // annotations. Preview and Acrobat don't seem to need these.
            if (null == aCircle.getAppearance()) {
                aCircle.setAppearance(new PDAppearanceDictionary());
                PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document);
                position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f);
                position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f);
                position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f);
                position.setUpperRightY(lowerLeftY + height + borderThick.getWidth() * 0.5f);
                annotationAppearanceStream.setBBox(position);
                annotationAppearanceStream.setMatrix(new AffineTransform());
                annotationAppearanceStream.setResources(page.getResources());

                try (PDPageContentStream appearanceContent = new PDPageContentStream(document,
                        annotationAppearanceStream)) {
                    Matrix transform = new Matrix();
                    appearanceContent.transform(transform);
                    appearanceContent.moveTo(lowerLeftX, lowerLeftY + height * 0.5f);
                    appearanceContent.curveTo(lowerLeftX, lowerLeftY + height * 0.75f,
                            lowerLeftX + width * 0.25f, lowerLeftY + height, lowerLeftX + width * 0.5f,
                            lowerLeftY + height);
                    appearanceContent.curveTo(lowerLeftX + width * 0.75f, lowerLeftY + height,
                            lowerLeftX + width, lowerLeftY + height * 0.75f, lowerLeftX + width,
                            lowerLeftY + height * 0.5f);
                    appearanceContent.curveTo(lowerLeftX + width, lowerLeftY + height * 0.25f,
                            lowerLeftX + width * 0.75f, lowerLeftY, lowerLeftX + width * 0.5f, lowerLeftY);
                    appearanceContent.curveTo(lowerLeftX + width * 0.25f, lowerLeftY, lowerLeftX,
                            lowerLeftY + height * 0.25f, lowerLeftX, lowerLeftY + height * 0.5f);
                    appearanceContent.setLineWidth(borderThick.getWidth());
                    appearanceContent.setNonStrokingColor(fillColor);
                    appearanceContent.setStrokingColor(red);
                    appearanceContent.fillAndStroke();
                    appearanceContent.moveTo(0, 0);

                    appearanceContent.beginText();
                    appearanceContent.setNonStrokingColor(black);
                    // Center text vertically, left justified
                    appearanceContent.newLineAtOffset(lowerLeftX + borderThick.getWidth(),
                            lowerLeftY + height * 0.5f - fontSize * 0.5f);
                    appearanceContent.setFont(font, fontSize);
                    appearanceContent.showText(contents);
                    appearanceContent.endText();
                }
                aCircle.getAppearance().setNormalAppearance(annotationAppearanceStream);
            }

        } catch (IOException ex) {
            Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex);
            result = null;
        }
    } catch (NumberFormatException | NullPointerException ex) {
        System.err.println("Non number encountered where floating point number expected.");
        result = null;
    } catch (IOException ex) {
        Logger.getLogger(EllipseAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex);
        result = null;
    }

    return result;
}

From source file:airviewer.TextAnnotationMaker.java

License:Apache License

/**
 * //from  ww  w.  j  a va2s  .c  o  m
 * @param document
 * @param arguments(pageNumber, lowerLeftX, lowerLeftY);
        
    String contents 
 * @return 
 */
public static List<PDAnnotation> make(PDDocument document, ArrayList<String> arguments) {
    assert null != arguments && arguments.size() == 4;
    assert null != document;

    List<PDAnnotation> result;

    try {
        int pageNumber = parseInt(arguments.get(0));
        float lowerLeftX = parseFloat(arguments.get(1));
        float lowerLeftY = parseFloat(arguments.get(2));

        String contents = arguments.get(3);
        PDFont font = PDType1Font.HELVETICA_OBLIQUE;
        final float fontSize = 16.0f; // Or whatever font size you want.
        final float lineSpacing = 4.0f;
        float width = font.getStringWidth(contents) * fontSize / 1000.0f; // font.getStringWidth(contents) returns thousanths of PS point
        final float textHeight = fontSize + lineSpacing;

        try {
            PDPage page = document.getPage(pageNumber);
            PDColor red = new PDColor(new float[] { 1, 0, 0 }, PDDeviceRGB.INSTANCE);
            PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
            borderThick.setWidth(72 / 12); // 12th inch
            PDRectangle position = new PDRectangle();
            position.setLowerLeftX(lowerLeftX);
            position.setLowerLeftY(lowerLeftY);
            position.setUpperRightX(lowerLeftX + width);
            position.setUpperRightY(lowerLeftY + textHeight);

            PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle(
                    PDAnnotationSquareCircle.SUB_TYPE_SQUARE);
            aSquare.setAnnotationName(new UID().toString());
            aSquare.setContents(contents);
            PDColor fillColor = new PDColor(new float[] { .8f, .8f, .8f }, PDDeviceRGB.INSTANCE);
            aSquare.setInteriorColor(fillColor);
            aSquare.setRectangle(position);
            result = new ArrayList<>(page.getAnnotations()); // copy
            page.getAnnotations().add(aSquare);

            // The following lines are needed for PDFRenderer to render 
            // annotations. Preview and Acrobat don't seem to need these.
            if (null == aSquare.getAppearance()) {
                aSquare.setAppearance(new PDAppearanceDictionary());
                PDAppearanceStream annotationAppearanceStream = new PDAppearanceStream(document);
                position.setLowerLeftX(lowerLeftX - borderThick.getWidth() * 0.5f);
                position.setLowerLeftY(lowerLeftY - borderThick.getWidth() * 0.5f);
                position.setUpperRightX(lowerLeftX + width + borderThick.getWidth() * 0.5f);
                position.setUpperRightY(lowerLeftY + textHeight + borderThick.getWidth() * 0.5f);
                annotationAppearanceStream.setBBox(position);
                annotationAppearanceStream.setMatrix(new AffineTransform());
                annotationAppearanceStream.setResources(page.getResources());

                try (PDPageContentStream appearanceContent = new PDPageContentStream(document,
                        annotationAppearanceStream)) {
                    Matrix transform = new Matrix();
                    appearanceContent.transform(transform);
                    appearanceContent.addRect(lowerLeftX, lowerLeftY, width, textHeight);
                    appearanceContent.setNonStrokingColor(fillColor);
                    appearanceContent.fill();
                    appearanceContent.beginText();

                    // Center text vertically, left justified
                    appearanceContent.newLineAtOffset(lowerLeftX,
                            lowerLeftY + textHeight * 0.5f - fontSize * 0.5f);
                    appearanceContent.setFont(font, fontSize);
                    appearanceContent.setNonStrokingColor(red);
                    appearanceContent.showText(contents);
                    appearanceContent.endText();
                }
                aSquare.getAppearance().setNormalAppearance(annotationAppearanceStream);
            }
            //System.out.println(page.getAnnotations().toString());

        } catch (IOException ex) {
            Logger.getLogger(DocumentCommandWrapper.class.getName()).log(Level.SEVERE, null, ex);
            result = null;
        }
    } catch (NumberFormatException | NullPointerException ex) {
        System.err.println("Non number encountered where floating point number expected.");
        result = null;
    } catch (IOException ex) {
        Logger.getLogger(TextAnnotationMaker.class.getName()).log(Level.SEVERE, null, ex);
        result = null;
    }

    return result;
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFBoxTable.java

License:EUPL

private float getCellWidth(Entry cell) throws IOException, PdfAsException {
    boolean isValue = true;
    switch (cell.getType()) {
    case Entry.TYPE_CAPTION:
        isValue = false;/*from  w  w  w.  ja v a 2s  .com*/
    case Entry.TYPE_VALUE:
        PDFont c = null;
        float fontSize;
        String string = (String) cell.getValue();
        if (isValue) {
            c = valueFont.getFont();//null
            fontSize = valueFont.getFontSize();
        } else {
            c = font.getFont();//null
            fontSize = font.getFontSize();
        }
        if (string == null) {
            string = "";
            cell.setValue(string);
        }
        if (string.contains("\n")) {
            float maxWidth = 0;
            String[] lines = string.split("\n");
            for (int i = 0; i < lines.length; i++) {
                float w = c.getStringWidth(lines[i]) / 1000 * fontSize;
                if (maxWidth < w) {
                    maxWidth = w;
                }
            }
            return maxWidth;
        } else {
            return c.getStringWidth(string) / 1000 * fontSize;
        }
    case Entry.TYPE_IMAGE:
        if (style != null && style.getImageScaleToFit() != null) {
            return style.getImageScaleToFit().getWidth();
        }
        return 80.f;
    case Entry.TYPE_TABLE:
        PDFBoxTable pdfBoxTable = null;
        if (cell.getValue() instanceof Table) {
            pdfBoxTable = new PDFBoxTable((Table) cell.getValue(), this, this.settings, pdfBoxObject);
            cell.setValue(pdfBoxTable);
        } else if (cell.getValue() instanceof PDFBoxTable) {
            pdfBoxTable = (PDFBoxTable) cell.getValue();
        } else {
            throw new IOException("Failed to build PDFBox Table");
        }
        return pdfBoxTable.getWidth();
    default:
        logger.warn("Invalid Cell Entry Type: " + cell.getType());
    }
    return 0;
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFBoxTable.java

License:EUPL

private String[] breakString(String value, float maxwidth, PDFont font, float fontSize) throws IOException {
    String[] words = value.split(" ");
    List<String> lines = new ArrayList<String>();
    String cLineValue = "";
    for (int i = 0; i < words.length; i++) {
        String word = words[i];// w w  w . java 2  s.c o  m
        String[] lineBreaks = word.split("\n");
        if (lineBreaks.length > 1 || word.contains("\n")) {
            for (int j = 0; j < lineBreaks.length; j++) {
                String subword = lineBreaks[j];
                // if (cLine + subword.length() > maxline) {
                if (j == 0 && word.startsWith("\n")) {
                    lines.add(cLineValue.trim());
                    cLineValue = "";
                } else if (j != 0) {
                    lines.add(cLineValue.trim());
                    cLineValue = "";
                }
                // }
                String tmpLine = cLineValue + subword;
                float size = font.getStringWidth(tmpLine) / 1000.0f * fontSize;
                if (size > maxwidth && cLineValue.length() != 0) {
                    lines.add(cLineValue.trim());
                    cLineValue = "";
                }
                cLineValue += subword + " ";
            }
            if (lineBreaks.length == 1) {
                lines.add(cLineValue.trim());
                cLineValue = "";
            }
        } else {
            String tmpLine = cLineValue + word;
            float size = font.getStringWidth(tmpLine) / 1000.0f * fontSize;
            if (size > maxwidth && cLineValue.length() != 0) {
                lines.add(cLineValue.trim());
                cLineValue = "";
            }
            cLineValue += word + " ";
        }
    }
    lines.add(cLineValue.trim());
    return lines.toArray(new String[0]);
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.TableDrawUtils.java

License:EUPL

private static void drawString(PDPage page, PDPageContentStream contentStream, float contentx, float contenty,
        float width, float height, float padding, PDFBoxTable abstractTable, PDDocument doc, Entry cell,
        float fontSize, float textHeight, String valign, String halign, String[] tlines, PDFont textFont,
        PDResources formResources, ISettings settings) throws PdfAsException {
    try {//w ww .j ava 2 s  .c o m
        float ty = contenty - padding;
        float tx = contentx + padding;
        float innerHeight = height - (2 * padding);
        float innerWidth = width - (2 * padding);
        if (Style.BOTTOM.equals(valign)) {
            float bottom_offset = innerHeight - textHeight;
            ty -= bottom_offset;
        } else if (Style.MIDDLE.equals(valign)) {
            float bottom_offset = innerHeight - textHeight;
            bottom_offset = bottom_offset / 2.0f;
            ty -= bottom_offset;
        }

        // calculate the max with of the text content
        float maxWidth = 0;
        for (int k = 0; k < tlines.length; k++) {
            float lineWidth;
            // if (textFont instanceof PDType1Font) {
            lineWidth = textFont.getStringWidth(tlines[k]) / 1000.0f * fontSize;
            /*
             * } else { float fwidth = textFont
             * .getStringWidth("abcdefghijklmnopqrstuvwxyz ") / 1000.0f *
             * fontSize; fwidth = fwidth / (float)
             * "abcdefghijklmnopqrstuvwxyz" .length(); lineWidth =
             * tlines[k].length() * fwidth; }
             */
            if (maxWidth < lineWidth) {
                maxWidth = lineWidth;
            }
        }

        if (Style.CENTER.equals(halign)) {
            float offset = innerWidth - maxWidth;
            if (offset > 0) {
                offset = offset / 2.0f;
                tx += offset;
            }
        } else if (Style.RIGHT.equals(halign)) {
            float offset = innerWidth - maxWidth;
            if (offset > 0) {
                tx += offset;
            }
        }
        float ascent = textFont.getFontDescriptor().getAscent();
        float descent = textFont.getFontDescriptor().getDescent();

        ascent = ascent / 1000.0f * fontSize;
        descent = descent / 1000.0f * fontSize;

        //ty = ty + (descent * (-1));

        logger.debug("Text tx {} ty {} maxWidth {} textHeight {}", tx, ty, maxWidth, textHeight);
        logger.debug("Text ASCENT {} DESCENT {}", ascent, descent);

        logger.debug("Text TRANSFORMED ASCENT {} DESCENT {}", ascent, descent);

        drawDebugLineString(contentStream, tx, ty, maxWidth, textHeight, descent, settings);

        contentStream.beginText();

        if (formResources.getFonts().containsValue(textFont)) {
            String fontID = getFontID(textFont, formResources);
            logger.debug("Using Font: " + fontID);
            contentStream.appendRawCommands("/" + fontID + " " + fontSize + " Tf\n");
        } else {
            contentStream.setFont(textFont, fontSize);
        }

        logger.debug("Writing: " + tx + " : " + (ty - fontSize + (descent * (-1))) + " as " + cell.getType());
        contentStream.moveTextPositionByAmount(tx, (ty - fontSize + (descent * (-1))));

        contentStream.appendRawCommands(fontSize + " TL\n");
        for (int k = 0; k < tlines.length; k++) {
            contentStream.drawString(tlines[k]);
            if (k < tlines.length - 1) {
                contentStream.appendRawCommands("T*\n");
            }
        }

        contentStream.endText();

    } catch (IOException e) {
        logger.warn("IO Exception", e);
        throw new PdfAsException("Error", e);
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFBoxTable.java

License:EUPL

private void normalizeContent(Table abstractTable) throws PdfAsException {
    int rows = abstractTable.getRows().size();
    for (int i = 0; i < rows; i++) {
        ArrayList<Entry> row = this.table.getRows().get(i);
        for (int j = 0; j < row.size(); j++) {
            Entry cell = (Entry) row.get(j);

            switch (cell.getType()) {
            case Entry.TYPE_CAPTION:
            case Entry.TYPE_VALUE:
                String value = (String) cell.getValue();

                //Check if the used value font supports all characters in string
                PDFont f = null;
                try {
                    if (valueFont != null) {
                        f = valueFont.getFont();
                        f.getStringWidth(value);
                    }/*  w w w.  j av a2s. c  o m*/
                } catch (IllegalArgumentException | IOException e) {
                    if (f != null) {
                        logger.warn(
                                "Font " + f.getName() + " doesnt support a character in the value " + value);
                    }
                    cell.setValue(
                            PDFTextNormalizationUtils.normalizeText(value, WinAnsiEncoding.INSTANCE::contains));
                }

                break;
            }
        }
    }
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFBoxTable.java

License:EUPL

private float getCellWidth(Entry cell) throws IOException, PdfAsException {
    boolean isValue = true;
    switch (cell.getType()) {
    case Entry.TYPE_CAPTION:
        isValue = false;//from   w w  w .  j  av  a 2s  . co  m
    case Entry.TYPE_VALUE:
        PDFont c = null;
        float fontSize;
        String string = (String) cell.getValue();
        if (isValue) {
            c = valueFont.getFont();//null
            fontSize = valueFont.getFontSize();
        } else {
            c = font.getFont();//null
            fontSize = font.getFontSize();
        }
        if (string == null) {
            string = "";
            cell.setValue(string);
        }
        if (string.contains(NBSPACE) || string.contains("\n")) {
            float maxWidth = 0;
            string = string.replace(NBSPACE, " ");
            String[] lines = string.split("\n");

            for (int i = 0; i < lines.length; i++) {
                float w = c.getStringWidth(lines[i]) / 1000 * fontSize;
                if (maxWidth < w) {
                    maxWidth = w;
                }
            }
        } else {
            return c.getStringWidth(string) / 1000 * fontSize;
        }
    case Entry.TYPE_IMAGE:
        if (style != null && style.getImageScaleToFit() != null) {
            return style.getImageScaleToFit().getWidth();
        }
        return 80.f;
    case Entry.TYPE_TABLE:
        PDFBoxTable pdfBoxTable = null;
        if (cell.getValue() instanceof Table) {
            pdfBoxTable = new PDFBoxTable((Table) cell.getValue(), this, this.settings, pdfBoxObject);
            cell.setValue(pdfBoxTable);
        } else if (cell.getValue() instanceof PDFBoxTable) {
            pdfBoxTable = (PDFBoxTable) cell.getValue();
        } else {
            throw new IOException("Failed to build PDFBox Table");
        }
        return pdfBoxTable.getWidth();
    default:
        logger.warn("Invalid Cell Entry Type: " + cell.getType());
    }
    return 0;
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFBoxTable.java

License:EUPL

private String[] breakString(String value, float maxwidth, PDFont font, float fontSize) throws IOException {
    String[] words = value.split(" ");
    List<String> lines = new ArrayList<String>();
    String cLineValue = "";
    for (int i = 0; i < words.length; i++) {
        String word = words[i];//w w w .j  a v a  2  s  .  com
        String[] lineBreaks = word.split("\n");
        if (lineBreaks.length > 1) {
            for (int j = 0; j < lineBreaks.length; j++) {
                String subword = lineBreaks[j];
                // if (cLine + subword.length() > maxline) {
                if (j == 0 && word.startsWith("\n")) {
                    lines.add(cLineValue.trim());
                    cLineValue = "";
                } else if (j != 0) {
                    lines.add(cLineValue.trim());
                    cLineValue = "";
                }
                // }
                String tmpLine = cLineValue + subword;
                tmpLine = tmpLine.replace(NBSPACE, " ");

                float size = font.getStringWidth(tmpLine) / 1000.0f * fontSize;
                if (size > maxwidth && cLineValue.length() != 0) {
                    lines.add(cLineValue.trim());
                    cLineValue = "";
                }
                cLineValue += subword + " ";
            }
        } else {
            String tmpLine = cLineValue + word;
            tmpLine = tmpLine.replace(NBSPACE, " ");

            float size = font.getStringWidth(tmpLine) / 1000.0f * fontSize;
            if (size > maxwidth && cLineValue.length() != 0) {
                lines.add(cLineValue.trim());
                cLineValue = "";
            }
            cLineValue += word + " ";
        }
    }
    lines.add(cLineValue.trim());
    for (int i = 0; i < lines.size(); i++) {
        lines.set(i, lines.get(i).replace(NBSPACE, " "));
    }
    return lines.toArray(new String[0]);
}

From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.TableDrawUtils.java

License:EUPL

private static void drawString(PDPage page, PDPageContentStream contentStream, float contentx, float contenty,
        float width, float height, float padding, PDFBoxTable abstractTable, PDDocument doc, Entry cell,
        float fontSize, float textHeight, String valign, String halign, String[] tlines, PDFont textFont,
        PDResources formResources, ISettings settings) throws PdfAsException {
    try {/*  ww w .j a v a2s .co  m*/
        float ty = contenty - padding;
        float tx = contentx + padding;
        float innerHeight = height - (2 * padding);
        float innerWidth = width - (2 * padding);
        if (Style.BOTTOM.equals(valign)) {
            float bottom_offset = innerHeight - textHeight;
            ty -= bottom_offset;
        } else if (Style.MIDDLE.equals(valign)) {
            float bottom_offset = innerHeight - textHeight;
            bottom_offset = bottom_offset / 2.0f;
            ty -= bottom_offset;
        }

        float descent = 0;
        float ascent;
        float lineWidth = 0;
        float txNew = 0;

        if (tlines.length > 1 && Style.LINECENTER.equals(halign)) {

            //Calculate TXs
            ArrayList<Float> calculatedTXs = new ArrayList<>();
            for (int k = 0; k < tlines.length; k++) {

                // if (textFont instanceof PDType1Font) {
                lineWidth = textFont.getStringWidth(tlines[k]) / 1000.0f * fontSize;
                txNew = (innerWidth - lineWidth) / 2.0f;
                logger.debug("calculatedTXNew in k-Loop: {} {}", k, txNew);
                calculatedTXs.add(tx + txNew);

                logger.debug("INNERWIDTH in drawString: " + innerWidth);
                logger.debug("TX in drawString: " + tx);

                ascent = textFont.getFontDescriptor().getAscent();
                descent = textFont.getFontDescriptor().getDescent();
                ascent = ascent / 1000.0f * fontSize;
                descent = descent / 1000.0f * fontSize;

                //ty = ty + (descent * (-1));

                logger.debug("Text txNew {} ty {} lineWidth {} textHeight {}", txNew, ty, lineWidth,
                        textHeight);
                logger.debug("Text ASCENT {} DESCENT {}", ascent, descent);

                logger.debug("Text TRANSFORMED ASCENT {} DESCENT {}", ascent, descent);
                drawDebugLineString(contentStream, txNew, ty, lineWidth, textHeight, descent, settings);
            }

            contentStream.beginText();
            contentStream.setFont(textFont, fontSize);
            txNew = tx + calculatedTXs.get(0);
            logger.debug("Calculated TX0: " + txNew);
            //contentStream.newLineAtOffset(txNew, (ty - fontSize + (descent * (-1))));

            /*
            if (formResources.getFont(COSName.getPDFName(textFont.getName())) != null) {
               String fontID = getFontID(textFont, formResources);
               logger.debug("Using Font: " + fontID);
               contentStream.appendRawCommands("/" + fontID + " " + fontSize
                     + " Tf\n");
            } else {
               contentStream.setFont(textFont, fontSize);
            }
                    
            logger.debug("Writing: " + tx + " : " + (ty - fontSize + (descent * (-1))) + " as "
                  + cell.getType());
            contentStream.moveTextPositionByAmount(tx, (ty - fontSize + (descent * (-1))));
                    
            contentStream.appendRawCommands(fontSize + " TL\n");
            */

            for (int k = 0; k < tlines.length; k++) {
                float offset = calculatedTXs.get(k);
                if (k == 0) {
                    contentStream.newLineAtOffset(offset, (ty - fontSize + (descent * (-1))));

                } else {
                    logger.debug("Calculated TX: {} {} ", k, offset);
                    contentStream.newLineAtOffset(offset, -1 * fontSize);
                } //contentStream.appendRawCommands("T*\n");

                contentStream.showText(tlines[k]);

                contentStream.newLineAtOffset(-1 * offset, 0);
            }
            contentStream.endText();

        } else {
            // calculate the max with of the text content
            float maxWidth = 0;
            for (int k = 0; k < tlines.length; k++) {

                // if (textFont instanceof PDType1Font) {
                lineWidth = textFont.getStringWidth(tlines[k]) / 1000.0f * fontSize;
                /*
                 * } else { float fwidth = textFont
                 * .getStringWidth("abcdefghijklmnopqrstuvwxyz ") / 1000.0f *
                 * fontSize; fwidth = fwidth / (float)
                 * "abcdefghijklmnopqrstuvwxyz" .length(); lineWidth =
                 * tlines[k].length() * fwidth; }
                 */
                if (maxWidth < lineWidth) {
                    maxWidth = lineWidth;
                }
            }

            if (Style.CENTER.equals(halign) || Style.LINECENTER.equals(halign)) {
                float offset = innerWidth - maxWidth;
                if (offset > 0) {
                    offset = offset / 2.0f;
                    tx += offset;
                }
            } else if (Style.RIGHT.equals(halign)) {
                float offset = innerWidth - maxWidth;
                if (offset > 0) {
                    tx += offset;
                }
            }
            ascent = textFont.getFontDescriptor().getAscent();
            descent = textFont.getFontDescriptor().getDescent();

            ascent = ascent / 1000.0f * fontSize;
            descent = descent / 1000.0f * fontSize;

            //ty = ty + (descent * (-1));

            logger.debug("Text tx {} ty {} maxWidth {} textHeight {}", tx, ty, maxWidth, textHeight);
            logger.debug("Text ASCENT {} DESCENT {}", ascent, descent);

            logger.debug("Text TRANSFORMED ASCENT {} DESCENT {}", ascent, descent);

            drawDebugLineString(contentStream, tx, ty, maxWidth, textHeight, descent, settings);

            contentStream.beginText();

            contentStream.setFont(textFont, fontSize);
            contentStream.newLineAtOffset(tx, (ty - fontSize + (descent * (-1))));
            /*
            if (formResources.getFont(COSName.getPDFName(textFont.getName())) != null) {
               String fontID = getFontID(textFont, formResources);
               logger.debug("Using Font: " + fontID);
               contentStream.appendRawCommands("/" + fontID + " " + fontSize
                     + " Tf\n");
            } else {
               contentStream.setFont(textFont, fontSize);
            }
                    
            logger.debug("Writing: " + tx + " : " + (ty - fontSize + (descent * (-1))) + " as "
                  + cell.getType());
            contentStream.moveTextPositionByAmount(tx, (ty - fontSize + (descent * (-1))));
                    
            contentStream.appendRawCommands(fontSize + " TL\n");
            */

            if (textFont.willBeSubset()) {
                logger.debug("Font will be subset!");
            }

            for (int k = 0; k < tlines.length; k++) {
                contentStream.showText(tlines[k]);
                if (k < tlines.length - 1) {
                    contentStream.newLineAtOffset(0, -1 * fontSize);
                    //contentStream.appendRawCommands("T*\n");
                }
            }

            contentStream.endText();
        }

    } catch (IOException e) {
        logger.warn("IO Exception", e);
        throw new PdfAsException("Error", e);
    }
}