Example usage for org.apache.pdfbox.util Matrix getTranslateInstance

List of usage examples for org.apache.pdfbox.util Matrix getTranslateInstance

Introduction

In this page you can find the example usage for org.apache.pdfbox.util Matrix getTranslateInstance.

Prototype

public static Matrix getTranslateInstance(float tx, float ty) 

Source Link

Document

Convenience method to create a translating instance.

Usage

From source file:Bulletin.myPdf.java

public float TextCentered(String text, PDFont font, int size, float X, float Y, float rowHeight) {
    try {//from ww w. j  av  a2 s  . c  om
        this.cos.beginText();
        this.cos.setFont(font, Math.round(textScale * size));
        float dtw = 0.5f * getTextWidth(font, text, size);
        float dth = 0.3f * getFontHeight(font, size);
        int nbLines = text.split("#").length;
        Y += 0.5f * (nbLines - 1) * rowHeight;

        for (String line : text.split("#")) {
            if (line.length() == 0) {
                continue;
            }
            //                System.out.println("X="+X+" Y="+Y);
            //                System.out.println("dtw="+dtw+" dth="+dth);
            Matrix M = Matrix.getTranslateInstance(X, Y);
            M.concatenate(Matrix.getRotateInstance(this.textAngle, 0, 0));
            M.concatenate(Matrix.getTranslateInstance(-dtw, -dth));

            this.cos.setTextMatrix(M);
            this.cos.showText(this.fix(line));
            //                this.cos.showText(new String(Base64.getDecoder().decode(line), "UTF-8"));

            Y -= rowHeight;
        }
        this.cos.endText();
        this.cos.stroke();

    } catch (IOException ex) {
        Logger.getLogger(Bulletin2.class.getName()).log(Level.SEVERE, null, ex);
    }
    return rowHeight;
}

From source file:Bulletin.myPdf.java

public float TextLeft(String text, PDFont font, int size, float X, float Y, float rowHeight) {
    try {/*from  www .ja  va  2  s .  co  m*/
        this.cos.beginText();
        this.cos.setFont(font, Math.round(textScale * size));
        float dth = 0.3f * getFontHeight(font, size);
        int nbLines = text.split("#").length;
        Y += 0.5f * (nbLines - 1) * rowHeight;

        for (String line : text.split("#")) {
            if (line.length() == 0) {
                continue;
            }
            //                System.out.println("X="+X+" Y="+Y);
            //                System.out.println("dtw="+dtw+" dth="+dth);
            Matrix M = Matrix.getTranslateInstance(X, Y);
            M.concatenate(Matrix.getRotateInstance(this.textAngle, 0, 0));
            M.concatenate(Matrix.getTranslateInstance(0, -dth));

            this.cos.setTextMatrix(M);
            this.cos.showText(this.fix(line));
            //                this.cos.showText(new String(Base64.getDecoder().decode(line), "UTF-8"));
            Y -= rowHeight;
        }
        this.cos.endText();
        this.cos.stroke();

    } catch (IOException ex) {
        Logger.getLogger(Bulletin2.class.getName()).log(Level.SEVERE, null, ex);
    }
    return rowHeight;
}

From source file:Bulletin.myPdf.java

public float Text(String text, PDFont font, int size, float X, float Y, float rowHeight) {
    try {/*from   www . j  a  v  a 2 s .co  m*/
        for (String line : text.split("#")) {

            this.cos.beginText();
            Matrix M = Matrix.getTranslateInstance(X, Y);
            this.cos.setTextMatrix(M);
            this.cos.setFont(font, Math.round(textScale * size));

            this.cos.showText(this.fix(line));
            //                this.cos.showText(new String(Base64.getDecoder().decode(line), "UTF-8"));

            Y -= rowHeight;
            this.cos.endText();
            this.cos.stroke();
        }
    } catch (IOException ex) {
        Logger.getLogger(Bulletin2.class.getName()).log(Level.SEVERE, null, ex);
    }
    return rowHeight;
}

From source file:Bulletin.test.java

public static void test2() {
    try {//from www  .j  a  v  a 2 s. c  o  m
        PDDocument document = new PDDocument();
        PDPage page = new PDPage(PDRectangle.A4);
        PDPageContentStream cos = null;
        try {
            cos = new PDPageContentStream(document, page);
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }

        float X = 501.4f;
        float Y = 556.0f;
        //            String text = "HALLO";
        //            String text = "HALLO#HOE#GAAT#HET";
        //            String text = "HALLO#HOE#GAAT";
        String text = "Non atteints";
        int rh = 10;

        cos.moveTo(X, Y - 50);
        cos.lineTo(X, Y + 50);
        cos.stroke();
        cos.moveTo(X - 50, Y);
        cos.lineTo(X + 50, Y);
        cos.stroke();

        cos.beginText();
        cos.setFont(PDType1Font.HELVETICA, 6);
        float dtw = 0.5f * getTextWidth(PDType1Font.HELVETICA, text, 6);
        float dth = 0.0f * getFontHeight(PDType1Font.HELVETICA, 6);
        int nbLines = text.split("#").length;

        Y += 0.5f * (nbLines - 1) * rh;

        for (String line : text.split("#")) {
            Matrix M = Matrix.getTranslateInstance(X, Y);
            M.concatenate(Matrix.getRotateInstance(Math.toRadians(0), 0, 0));
            M.concatenate(Matrix.getTranslateInstance(-dtw, -dth));
            cos.setTextMatrix(M);
            cos.showText(line);
            Y -= rh;
        }
        cos.close();
        document.addPage(page);
        document.save("/tmp/test.pdf");
        document.close();

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

From source file:com.przemo.pdfmanipulate.PDFBuilder.java

private static void renderForm(Formularz form, PDDocument doc) throws IOException {
    int i = 0;/*  www.j av  a2s . c o m*/
    PDFont f = PDType1Font.HELVETICA;
    float fontSize = 17.0f;
    for (FormPage page : form.getPages()) {
        PDPage pag = doc.getPage(i);
        PDRectangle pageSize = pag.getMediaBox();
        try (PDPageContentStream contentStream = new PDPageContentStream(doc, pag,
                PDPageContentStream.AppendMode.APPEND, false)) {
            contentStream.setFont(f, fontSize);
            contentStream.beginText();
            contentStream.setNonStrokingColor(Color.black);
            for (Pole p : page.getPola()) {
                int x = p.getPozycjaX();
                if (p.isRightAlign()) {
                    x -= f.getStringWidth(p.getWartosc()) / 1000 * fontSize;
                }
                contentStream
                        .setTextMatrix(Matrix.getTranslateInstance(x, pageSize.getHeight() - p.getPozycjaY()));
                contentStream.showText(p.getWartosc());
            }
            contentStream.endText();
        }
        i++;
    }

}

From source file:com.repeatability.pdf.PDFTextStreamEngine.java

License:Apache License

/**
 * This will initialise and process the contents of the stream.
 *
 * @param page the page to process/*from   ww  w .  j a v  a2  s  .c o m*/
 * @throws java.io.IOException if there is an error accessing the stream.
 */
@Override
public void processPage(PDPage page) throws IOException {
    this.pageRotation = page.getRotation();
    this.pageSize = page.getCropBox();

    if (pageSize.getLowerLeftX() == 0 && pageSize.getLowerLeftY() == 0) {
        translateMatrix = null;
    } else {
        // translation matrix for cropbox
        translateMatrix = Matrix.getTranslateInstance(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY());
    }
    super.processPage(page);
}

From source file:com.repeatability.pdf.PDFTextStreamEngine.java

License:Apache License

/**
 * This method was originally written by Ben Litchfield for PDFStreamEngine.
 *//*w w w.j  av  a2  s . co  m*/
@Override
protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode, Vector displacement)
        throws IOException {
    //
    // legacy calculations which were previously in PDFStreamEngine
    //

    PDGraphicsState state = getGraphicsState();
    Matrix ctm = state.getCurrentTransformationMatrix();
    float fontSize = state.getTextState().getFontSize();
    float horizontalScaling = state.getTextState().getHorizontalScaling() / 100f;
    Matrix textMatrix = getTextMatrix();

    BoundingBox bbox = font.getBoundingBox();
    if (bbox.getLowerLeftY() < Short.MIN_VALUE) {
        // PDFBOX-2158 and PDFBOX-3130
        // files by Salmat eSolutions / ClibPDF Library
        bbox.setLowerLeftY(-(bbox.getLowerLeftY() + 65536));
    }
    // 1/2 the bbox is used as the height todo: why?
    float glyphHeight = bbox.getHeight() / 2;

    // sometimes the bbox has very high values, but CapHeight is OK
    PDFontDescriptor fontDescriptor = font.getFontDescriptor();
    if (fontDescriptor != null) {
        float capHeight = fontDescriptor.getCapHeight();
        if (capHeight != 0 && capHeight < glyphHeight) {
            glyphHeight = capHeight;
        }
    }

    // transformPoint from glyph space -> text space
    float height;
    if (font instanceof PDType3Font) {
        height = font.getFontMatrix().transformPoint(0, glyphHeight).y;
    } else {
        height = glyphHeight / 1000;
    }

    float displacementX = displacement.getX();
    // the sorting algorithm is based on the width of the character. As the displacement
    // for vertical characters doesn't provide any suitable value for it, we have to 
    // calculate our own
    if (font.isVertical()) {
        displacementX = font.getWidth(code) / 1000;
        // there may be an additional scaling factor for true type fonts
        TrueTypeFont ttf = null;
        if (font instanceof PDTrueTypeFont) {
            ttf = ((PDTrueTypeFont) font).getTrueTypeFont();
        } else if (font instanceof PDType0Font) {
            PDCIDFont cidFont = ((PDType0Font) font).getDescendantFont();
            if (cidFont instanceof PDCIDFontType2) {
                ttf = ((PDCIDFontType2) cidFont).getTrueTypeFont();
            }
        }
        if (ttf != null && ttf.getUnitsPerEm() != 1000) {
            displacementX *= 1000f / ttf.getUnitsPerEm();
        }
    }
    // (modified) combined displacement, this is calculated *without* taking the character
    // spacing and word spacing into account, due to legacy code in TextStripper
    float tx = displacementX * fontSize * horizontalScaling;
    float ty = displacement.getY() * fontSize;

    // (modified) combined displacement matrix
    Matrix td = Matrix.getTranslateInstance(tx, ty);

    // (modified) text rendering matrix
    Matrix nextTextRenderingMatrix = td.multiply(textMatrix).multiply(ctm); // text space -> device space
    float nextX = nextTextRenderingMatrix.getTranslateX();
    float nextY = nextTextRenderingMatrix.getTranslateY();

    // (modified) width and height calculations
    float dxDisplay = nextX - textRenderingMatrix.getTranslateX();
    float dyDisplay = height * textRenderingMatrix.getScalingFactorY();

    //
    // start of the original method
    //

    // Note on variable names. There are three different units being used in this code.
    // Character sizes are given in glyph units, text locations are initially given in text
    // units, and we want to save the data in display units. The variable names should end with
    // Text or Disp to represent if the values are in text or disp units (no glyph units are
    // saved).

    float glyphSpaceToTextSpaceFactor = 1 / 1000f;
    if (font instanceof PDType3Font) {
        glyphSpaceToTextSpaceFactor = font.getFontMatrix().getScaleX();
    }

    float spaceWidthText = 0;
    try {
        // to avoid crash as described in PDFBOX-614, see what the space displacement should be
        spaceWidthText = font.getSpaceWidth() * glyphSpaceToTextSpaceFactor;
    } catch (Throwable exception) {
        LOG.warn(exception, exception);
    }

    if (spaceWidthText == 0) {
        spaceWidthText = font.getAverageFontWidth() * glyphSpaceToTextSpaceFactor;
        // the average space width appears to be higher than necessary so make it smaller
        spaceWidthText *= .80f;
    }
    if (spaceWidthText == 0) {
        spaceWidthText = 1.0f; // if could not find font, use a generic value
    }

    // the space width has to be transformed into display units
    float spaceWidthDisplay = spaceWidthText * textRenderingMatrix.getScalingFactorX();

    // use our additional glyph list for Unicode mapping
    unicode = font.toUnicode(code, glyphList);

    // when there is no Unicode mapping available, Acrobat simply coerces the character code
    // into Unicode, so we do the same. Subclasses of PDFStreamEngine don't necessarily want
    // this, which is why we leave it until this point in PDFTextStreamEngine.
    if (unicode == null) {
        if (font instanceof PDSimpleFont) {
            char c = (char) code;
            unicode = new String(new char[] { c });
        } else {
            // Acrobat doesn't seem to coerce composite font's character codes, instead it
            // skips them. See the "allah2.pdf" TestTextStripper file.
            return;
        }
    }

    // adjust for cropbox if needed
    Matrix translatedTextRenderingMatrix;
    if (translateMatrix == null) {
        translatedTextRenderingMatrix = textRenderingMatrix;
    } else {
        translatedTextRenderingMatrix = Matrix.concatenate(translateMatrix, textRenderingMatrix);
        nextX -= pageSize.getLowerLeftX();
        nextY -= pageSize.getLowerLeftY();
    }

    processTextPosition(new TextPosition(pageRotation, pageSize.getWidth(), pageSize.getHeight(),
            translatedTextRenderingMatrix, nextX, nextY, dyDisplay, dxDisplay, spaceWidthDisplay, unicode,
            new int[] { code }, font, fontSize, (int) (fontSize * textMatrix.getScalingFactorX())));
}

From source file:com.yiyihealth.tools.test.DrawPrintTextLocations.java

License:Apache License

private void stripPage(int page) throws IOException {
    PDFRenderer pdfRenderer = new PDFRenderer(document);
    image = pdfRenderer.renderImage(page, SCALE);

    PDPage pdPage = document.getPage(page);
    PDRectangle cropBox = pdPage.getCropBox();

    // flip y-axis
    flipAT = new AffineTransform();
    flipAT.translate(0, pdPage.getBBox().getHeight());
    flipAT.scale(1, -1);/*from ww  w.  j av  a  2s  .  com*/

    // page may be rotated
    rotateAT = new AffineTransform();
    int rotation = pdPage.getRotation();
    if (rotation != 0) {
        PDRectangle mediaBox = pdPage.getMediaBox();
        switch (rotation) {
        case 90:
            rotateAT.translate(mediaBox.getHeight(), 0);
            break;
        case 270:
            rotateAT.translate(0, mediaBox.getWidth());
            break;
        case 180:
            rotateAT.translate(mediaBox.getWidth(), mediaBox.getHeight());
            break;
        default:
            break;
        }
        rotateAT.rotate(Math.toRadians(rotation));
    }

    g2d = image.createGraphics();
    g2d.setStroke(new BasicStroke(0.1f));
    g2d.scale(SCALE, SCALE);

    setStartPage(page + 1);
    setEndPage(page + 1);

    Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
    writeText(document, dummy);

    // beads in green
    g2d.setStroke(new BasicStroke(0.4f));
    List<PDThreadBead> pageArticles = pdPage.getThreadBeads();
    for (PDThreadBead bead : pageArticles) {
        PDRectangle r = bead.getRectangle();
        GeneralPath p = r
                .transform(Matrix.getTranslateInstance(-cropBox.getLowerLeftX(), cropBox.getLowerLeftY()));

        Shape s = flipAT.createTransformedShape(p);
        s = rotateAT.createTransformedShape(s);
        g2d.setColor(Color.green);
        g2d.draw(s);
    }

    g2d.dispose();

    String imageFilename = filename;
    int pt = imageFilename.lastIndexOf('.');
    imageFilename = imageFilename.substring(0, pt) + "-marked-" + (page + 1) + ".png";
    ImageIO.write(image, "png", new File(imageFilename));
}

From source file:de.rototor.pdfbox.graphics2d.PdfBoxGraphics2DTestBase.java

License:Apache License

@SuppressWarnings("SpellCheckingInspection")
void exportGraphic(String dir, String name, GraphicsExporter exporter) {
    try {//w  ww.  j  a v a  2s . com
        PDDocument document = new PDDocument();

        PDFont pdArial = PDFontFactory.createDefaultFont();

        File parentDir = new File("target/test/" + dir);
        // noinspection ResultOfMethodCallIgnored
        parentDir.mkdirs();

        BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D imageGraphics = image.createGraphics();
        exporter.draw(imageGraphics);
        imageGraphics.dispose();
        ImageIO.write(image, "PNG", new File(parentDir, name + ".png"));

        for (Mode m : Mode.values()) {
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);

            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            PdfBoxGraphics2D pdfBoxGraphics2D = new PdfBoxGraphics2D(document, 400, 400);
            PdfBoxGraphics2DFontTextDrawer fontTextDrawer = null;
            contentStream.beginText();
            contentStream.setStrokingColor(0, 0, 0);
            contentStream.setNonStrokingColor(0, 0, 0);
            contentStream.setFont(PDType1Font.HELVETICA_BOLD, 15);
            contentStream.setTextMatrix(Matrix.getTranslateInstance(10, 800));
            contentStream.showText("Mode " + m);
            contentStream.endText();
            switch (m) {
            case FontTextIfPossible:
                fontTextDrawer = new PdfBoxGraphics2DFontTextDrawer();
                registerFots(fontTextDrawer);
                break;
            case DefaultFontText: {
                fontTextDrawer = new PdfBoxGraphics2DFontTextDrawerDefaultFonts();
                registerFots(fontTextDrawer);
                break;
            }
            case ForceFontText:
                fontTextDrawer = new PdfBoxGraphics2DFontTextForcedDrawer();
                registerFots(fontTextDrawer);
                fontTextDrawer.registerFont("Arial", pdArial);
                break;
            case DefaultVectorized:
            default:
                break;
            }

            if (fontTextDrawer != null) {
                pdfBoxGraphics2D.setFontTextDrawer(fontTextDrawer);
            }

            exporter.draw(pdfBoxGraphics2D);
            pdfBoxGraphics2D.dispose();

            PDFormXObject appearanceStream = pdfBoxGraphics2D.getXFormObject();
            Matrix matrix = new Matrix();
            matrix.translate(0, 20);
            contentStream.transform(matrix);
            contentStream.drawForm(appearanceStream);

            matrix.scale(1.5f, 1.5f);
            matrix.translate(0, 100);
            contentStream.transform(matrix);
            contentStream.drawForm(appearanceStream);
            contentStream.close();
        }

        document.save(new File(parentDir, name + ".pdf"));
        document.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}