Watermarks are statements that are always used in various documents, are a means of preventing counterfeiting, and set watermarks on letters. You can do it or import photos. The following content is converted into a PDF document through Java How to add a watermark effect, that is, share a text watermark with an image watermark.
Added text watermark:
import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;
public class Textwatermark {
public static void main(String[] args) {
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("Sample.pdf");
PdfPageBase page = pdf.getPages().get(0);
//use insertWatermark()to insert the watermark
insertWatermark(page, "E-ICEBLUE");
pdf.saveToFile("out/textWaterMark.pdf");
}
static void insertWatermark(PdfPageBase page, String watermark) {
Dimension2D dimension2D = new Dimension();
dimension2D.setSize(page.getCanvas().getClientSize().getWidth() / 2, page.getCanvas().getClientSize().getHeight() / 3);
PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
brush.getGraphics().setTransparency(0.3F);
brush.getGraphics().save();
brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2);
brush.getGraphics().rotateTransform(-45);
brush.getGraphics().drawString(watermark, new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.getViolet(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
brush.getGraphics().restore();
brush.getGraphics().setTransparency(1);
Rectangle2D loRect = new Rectangle2D.Float();
loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize());
page.getCanvas().drawRectangle(brush, loRect);
}
}
Add image watermark:
import com.spire.pdf.*;
import java.awt.geom.Rectangle2D;
public class watermark {
public static void main(String[] args) {
PdfDocument doc = new PdfDocument();
doc.loadFromFile("Sample.pdf");
PdfPageBase page = doc.getPages().get(0);
page.setBackgroundImage("logo.png ");
Rectangle2D.Float rect = new Rectangle2D.Float();
rect.setRect(280, 300, 150, 150);
page.setBackgroundRegion(rect);
doc.saveToFile("output/imageWaterMark.pdf");
doc.close();
}
}
Recommended Posts