Watermark (1)
Java insert text and image watermark to Excel worksheet
2020-08-03 08:55:32 Written by support iceblueThis article will demonstrate how to insert text and image watermark to Excel worksheet in Java applications. The watermark in Excel worksheet could only be viewed under layout view mode.
import com.spire.xls.*; import java.awt.*; import java.awt.image.BufferedImage; import static java.awt.image.BufferedImage.TYPE_INT_ARGB; public class ExcelWatermark { public static void main(String[] args) { //Initialize a new instance of workbook and load the test file Workbook workbook = new Workbook(); workbook.loadFromFile("Sample.xlsx"); //Set the text string and size Font font = new Font("Arial", Font.PLAIN, 40); String watermark = "Draft Version"; for (Worksheet sheet : (Iterable) workbook.getWorksheets()) { //Call DrawText() method to insert the image BufferedImage imgWtrmrk = drawText(watermark, font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth()); //Set the image as header sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk); sheet.getPageSetup().setLeftHeader("&G"); //Set the viewmode as Layout sheet.setViewMode(ViewMode.Layout); } //Save the document workbook.saveToFile("Watermark.xlsx", ExcelVersion.Version2010); } private static BufferedImage drawText (String text, Font font, Color textColor, Color backColor,double height, double width) { //define the width and height of image BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB); Graphics2D loGraphic = img.createGraphics(); //set the font size FontMetrics loFontMetrics = loGraphic.getFontMetrics(font); int liStrWidth = loFontMetrics.stringWidth(text); int liStrHeight = loFontMetrics.getHeight(); //set the text format loGraphic.setColor(backColor); loGraphic.fillRect(0, 0, (int) width, (int) height); loGraphic.translate(((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2); loGraphic.rotate(Math.toRadians(-45)); loGraphic.translate(-((int) width - liStrWidth) / 2, -((int) height - liStrHeight) / 2); loGraphic.setFont(font); loGraphic.setColor(textColor); loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2); loGraphic.dispose(); return img; } }
Effective screenshot of Excel text watermark:
Published in
Watermark
Tagged under