pdfbox-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From chitgoks <chitg...@gmail.com>
Subject watermark position
Date Thu, 09 Mar 2017 07:56:58 GMT
Attached is my current code for watermarking text

I can't figure out which class is needed to ensure that the next call of
showText() will place it at the bottom instead of after the first line of
text.

what i wish to accomplish is to have 1 , 2 or 3 lines of showText() shown
vertically centered, and also a diagonal one like 45 or -45 degrees.

for the diagonal, i tried to use Matrix.getRotateInstance() but its
rotation does not base the point at the center.

Any ideas on what I did wrong?

Please advise. thank you


public class WatermarkTool {

    public static void createWaterMarkPDF(PDDocument pdfDocument) throws
Exception {
        PDFont font = PDType1Font.HELVETICA;
        float fontSize = 80;
        PDPageTree pages = pdfDocument.getPages();

        for (int i=0; i<pages.getCount(); i++) {
            PDPage page = pages.get(i);

            PDPageContentStream cs = new PDPageContentStream(pdfDocument,
page, AppendMode.APPEND, true, true);

            String ts = "Test Line 1";

            Point2D.Float center = new Point2D.Float(0, 0);
            Point2D.Float offset = center;
            Point2D.Float pageCenter = getCenter(page);

            PDExtendedGraphicsState gs = new PDExtendedGraphicsState();
            gs.setNonStrokingAlphaConstant(0.5f);
            cs.setGraphicsStateParameters(gs);
            cs.setNonStrokingColor(255,0,0);
            cs.setFont(font, fontSize);
            cs.beginText();
            //
http://stackoverflow.com/questions/6507124/how-to-center-a-text-using-pdfbox
            float stringWidth = getStringWidth(ts, font, fontSize);
            float textX = pageCenter.x - stringWidth / 2F + offset.x;
            float textY = pageCenter.y + offset.y;
//            double theta = Math.toRadians(-90);
//                cs.setTextMatrix(Matrix.getRotateInstance(theta,
pageCenter.x, pageCenter.y));
//                cs.setTextMatrix(Matrix.getRotateInstance(theta, textX,
textY));
            Matrix matrix = Matrix.getTranslateInstance(textX, textY);
            cs.setTextMatrix(matrix);
            cs.showText(ts);
            cs.showText(ts);
            cs.showText(ts);
            cs.endText();
            cs.close();

        }


    }

    private static Point2D.Float getCenter(PDPage page) {
        PDRectangle pageSize = page.getMediaBox();
        return new Point2D.Float(pageSize.getWidth() / 2F,
pageSize.getHeight() / 2F);
    }

    private static float getStringWidth(String text, PDFont font, float
fontSize) throws IOException {
        return font.getStringWidth(text) * fontSize / 1000F;
    }

}

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message