# ItextPdf Layout 7.2.3 Add watermark

ItextPdf Layout 7.2.3 Add watermark

Background introduction

  • Use Itextpdf Layout 7.2.3 , need to add watermark on Pdf
  • Itext 5 Adding watermark has already been mentioned in the previous article, you can read this article: Itext5 common API
  • Use PdfCanvas related methods

Article directory

  • ItextPdf Layout 7.2.3 add watermark
    • background introduction
    • ItextPdf Layout
    • Watermark related properties
    • maven dependencies
    • code example
      • watermark renderings
      • full code
      • color conversion
      • Get font height
    • Method Description
      • saveState()
      • concatMatrix()
      • PdfCanvas
        • drawing method
        • path constructor
        • graphics state method
        • image method
        • graphics state method
        • image method
    • source address

ItextPdf Layout

  • ItextPdf Layout is a specific version or submodule of iTextPdf that handles PDF layout-related functionality.

  • ItextPdf Layout provides a series of functions for creating and controlling PDF layout, such as adding text, images, tables and other elements to PDF pages.

  • It allows you to specify the position, size and style of each element, and you can apply formatting options such as font type, color, alignment and spacing.

Watermark related attributes

Properties
Transparency (0.0f -1.0f)
Watermark font type
Watermark font size (12px unit: pixel)
Watermark font color ( #d9d9d9)
Watermark multiline text line spacing (10 units: mm)
Watermark angle (-30 units: degree)
Watermark horizontal spacing (50 unit: mm) vertical spacing (50 unit: mm)

maven dependencies

  • Add Chinese support, and Itext layout related dependencies
 <!-- pdf Chinese support -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<!--itext-->
<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>core-renderer</artifactId>
    <version>R8</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>layout</artifactId>
    <version>7.2.3</version>
</dependency>

Code sample

Watermark rendering

  • ItextPdf starts to calculate the coordinates with the lower left corner as the origin (0,0)

Complete code

  • ItextPdf 7.2.3 Example of adding watermark
  • You can set whether to print only one watermark or to fill the entire printed page
  • Set the angle of the watermark
  • Set the line spacing, left, right, and center display of multi-line watermarks
  • Set watermark font, color, size
  • Watermark horizontal spacing, vertical spacing
 /**
 * Print page setting watermark
 */
@Test
public void addWaterMark() throws IOException {<!-- -->

    PdfWriter writer = new PdfWriter(new File(UUID. randomUUID() + FILENAME));
    PdfDocument pdfDoc = new PdfDocument(writer);
    Document document = new Document(pdfDoc, PageSize.A4);
    IBlockElement paragraph = new Paragraph("Hello, world!");
    document. add(paragraph);
    String waterMarkContent = "Test watermark\\
Hello";
    int numberOfPages = pdfDoc. getNumberOfPages();

    // angle
    float angle = 0;
    // Horizontal spacing
    float xSpacing = 100;
    // Vertical spacing
    float ySpacing = 100;
    // transparency
    float opacity = 0.5f;
    // Multi-line watermark text line spacing
    float lineSpacing = 0;
    // is it heavy
    Boolean repeat = true;
    // Multi-line watermark text alignment
    String textAlign = "LEFT";
    // watermark size
    float watermarkFontSize = 12;

    PdfFont watermarkFont = PdfFontFactory.createFont("src/main/resources/fonts/STSong.ttf", PdfEncodings.IDENTITY_H);

    float x = xSpacing;
    float y = ySpacing;

    // Split the watermark content into multiple lines by line breaks
    String[] lines = waterMarkContent. split("\\
");
    // text length array
    float[] textLength = new float[lines.length];
    // index of longest text
    int maxLengthIndex = 0;
    for (int i = 0; i < lines. length; i ++ ) {<!-- -->
        textLength[i] = watermarkFont. getWidth(lines[i], watermarkFontSize);
        if (i > 0 & amp; & amp; textLength[i] > textLength[i - 1]) {<!-- -->
            maxLengthIndex = i;
        }
    }

    String tempStr = Arrays. stream(lines). max(Comparator. comparing(String::length)). get();
    for (int i = 1; i <= numberOfPages; i ++ ) {<!-- -->
        PdfPage page = pdfDoc. getPage(i);
        Rectangle pageSize = page. getPageSize();
        float pageWidth = pageSize. getWidth();

        float pageHeight = pageSize. getHeight();
        float watermarkWidth = watermarkFont. getWidth(tempStr, watermarkFontSize);
        float watermarkHeight = getFontHeight(watermarkFont, watermarkFontSize);
        PdfPage firstPage = pdfDoc.getFirstPage();
        PdfCanvas canvas1 = new PdfCanvas(firstPage)
                .setFillColor(ColorConstants.RED)
                .setColor(ColorConstants.RED, true)
                .setExtGState(new PdfExtGState().setFillOpacity(opacity));

        float tempX = (x + watermarkWidth) / 2;
        int rowNum = 1;
        while (y + watermarkHeight < pageHeight) {<!-- -->
            // even-numbered rows are wrongly displayed
            if (rowNum % 2 == 0) {<!-- -->
                x = x - tempX;
            }
            while (x + watermarkWidth < pageWidth) {<!-- -->

                float tempY = y;
                for (int j = 0; j < lines. length; j ++ ) {<!-- -->

                    float textAlignX = 0;
                    // Realize the effect of centering left and right
                    if (j != maxLengthIndex) {<!-- -->
                        float maxLength = textLength[maxLengthIndex];
                        float currentLength = textLength[j];
                        if ("RIGHT".equals(textAlign)) {<!-- -->
                            textAlignX = maxLength - currentLength;
                        } else if ("CENTER".equals(textAlign)) {<!-- -->
                            textAlignX = (maxLength - currentLength) / 2;
                        }
                    }
                    x = x + textAlignX;

                    String line = lines[j];
                    canvas1. saveState()
                            .concatMatrix(new AffineTransform());
                    canvas1.concatMatrix(
                            StrictMath.cos(Math.toRadians(angle)), StrictMath.sin(Math.toRadians(angle)),
                            -StrictMath.sin(Math.toRadians(angle)), StrictMath.cos(Math.toRadians(angle)),
                            x, tempY
                    );
                    canvas1.beginText()
                            .setFontAndSize(watermarkFont, watermarkFontSize)
                            .showText(line)
                            .endText();
                    canvas1. restoreState();
                    // Multi-line text line spacing
                    tempY -= watermarkHeight + lineSpacing;
                }
                x + = watermarkWidth + xSpacing;

                // watermark repeat
                if (!Boolean.TRUE.equals(repeat)) {<!-- -->
                    break;
                }
            }
            // watermark repeat
            if (!Boolean.TRUE.equals(repeat)) {<!-- -->
                break;
            }
            x = xSpacing;
            y + = watermarkHeight * lines. length + ySpacing;
            rowNum++;
        }
    }
    pdfDoc. close();

}

Color conversion

  • #D9D9D9 intercepts the 16 string and obtains the 16 number
/**
 * Get the hexadecimal value of the color
 *
 * @param color #D9D9D9
 * @return int
 */
public static int colorValue(String color) {<!-- -->
    String tempColor = color;
    String[] split = tempColor. split("#");
    if (split. length > 1) {<!-- -->
        tempColor = split[split. length - 1];
    } else {<!-- -->
        tempColor = split[0];
    }
    return Integer. valueOf(tempColor, 16);
}

Get font height

  • Pay attention to use with ItextPdf 7.2.3
/**
 * Get font height
 *
 * @param font font
 * @param fontSize font size
 * @return float
 */
public float getFontHeight(PdfFont font, float fontSize) {<!-- -->
    FontMetrics fontMetrics = font.getFontProgram().getFontMetrics();
    // get font height
    float ascent = fontMetrics.getTypoAscender() * fontSize / fontMetrics.getUnitsPerEm();
    // get font drop height
    float descent = fontMetrics.getTypoDescender() * fontSize / fontMetrics.getUnitsPerEm();
    // calculate line spacing
    float leading = fontMetrics.getTypoAscender() - fontMetrics.getTypoDescender() + fontMetrics.getLineGap();
    // convert line spacing and font size to actual units
    leading *= fontSize / fontMetrics. getUnitsPerEm();
    float lineHeight = ascent - descent + leading;
    // Output font line height
    System.out.println("line height: " + lineHeight);
    return lineHeight;
}

Method Description

saveState()

  • The saveState method is a method in iText, which is used to save the current drawing state. It saves the current drawing state (such as color, font, lineweight, etc.) into a stack so that it can be restored to that state later.

  • By using the saveState and restoreState methods, you can save and restore drawing state when needed to ensure that what is drawn is as expected.

concatMatrix()

  • The concatMatrix method is the method used in iText PDF to concatenate a transformation matrix with the current transformation matrix. With this method, you can apply various transformations, such as translation, rotation, scaling, and skewing, to the content in the PDF document.

PdfCanvas

  • The PdfCanvas class is used to draw graphical elements and content on a PDF document. It provides various methods to draw lines, shapes, text, images, and apply transformations.

Drawing method

  • moveTo(x, y) : Move the current drawing position to the specified coordinates.
  • lineTo(x, y) : Draws a line from the current position to the specified coordinates.
  • rectangle(x, y, width, height) : Draw a rectangle at the specified position and size.
  • circle(x, y, radius) : Draw a circle with a given radius at a specified location.
  • arc(x, y, radius, startAngle, endAngle) : Draws an arc at the specified position, radius and angle.
  • text(x, y, text) : Draw text at the specified position.

Path construction method

  • newPath() : Start a new path.
  • closePath() : Close the current subpath.
  • stroke() : Use the current stroke color and line width to stroke the path.
  • fill() : Fills the path with the current fill color.

Graphics state methods

  • setLineWidth(width) : Sets the line width for subsequent drawing operations.
  • setStrokeColor(color) : Set the stroke color for subsequent drawing operations.
  • setFillColor(color) : Sets the fill color for subsequent drawing operations.
  • concatMatrix(a, b, c, d, e, f) : Connect a transformation matrix to the current transformation matrix.

Image method

  • addImage(image, x, y, width, height) : Add an image to the canvas at the specified position and size.
    Color fill path.

Graphics state methods

  • setLineWidth(width) : Sets the line width for subsequent drawing operations.
  • setStrokeColor(color) : Set the stroke color for subsequent drawing operations.
  • setFillColor(color) : Sets the fill color for subsequent drawing operations.
  • concatMatrix(a, b, c, d, e, f) : Connect a transformation matrix to the current transformation matrix.

Image method

  • addImage(image, x, y, width, height) : Add an image to the canvas at the specified position and size.

Source URL

  • See address: https://gitee.com/Marlon_Brando/JavaTest/tree/master/src/main/java/otherapi/itext/kernellayoutpdf