通过http://t.csdn.cn/CzmeR这篇文章的引导,写出了一个ofd文件加图片水印的工具类,分享给大家参考。
1、引入ofdrw
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
<scope>provided</scope>
</dependency>
<!-- ofdrw -->
<dependency>
<groupId>org.ofdrw</groupId>
<artifactId>ofdrw-full</artifactId>
<version>1.6.4</version>
</dependency>
2、工具类编写
import java.nio.file.Path;
import ch.qos.logback.core.net.SyslogOutputStream;
import com.itextpdf.text.BadElementException;
import org.ofdrw.core.annotation.pageannot.AnnotType;
import org.ofdrw.core.basicType.ST_Box;
import org.ofdrw.font.FontName;
import org.ofdrw.layout.OFDDoc;
import org.ofdrw.layout.edit.Annotation;
import org.ofdrw.layout.element.canvas.FontSetting;
import org.ofdrw.reader.OFDReader;
import com.itextpdf.text.Image;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class OfdUtil {
/**
* @param inputFile 输入路径
* @param outputFile 输出路径
* @param imgPath 图片路径
* @param dhzwz 加章位置: 1左上角、0中间、2右上角
*/
public static String waterMark(String inputFile, String outputFile,String imgPath,String dhzwz) throws IOException, BadElementException {
Path srcP = Paths.get(inputFile);
Path outP = Paths.get(outputFile);
//Image img = null;
Image img = Image.getInstance(imgPath);
Path imgPath1 = Paths.get(imgPath);
try (OFDReader reader = new OFDReader(srcP);
OFDDoc ofdDoc = new OFDDoc(reader, outP)) {
Double width = ofdDoc.getPageLayout().getWidth();
Double height = ofdDoc.getPageLayout().getHeight();
Annotation annotation = new Annotation(new ST_Box(0d, 0d, width, height), AnnotType.Watermark, ctx -> {
FontSetting setting = new FontSetting(8, FontName.SimSun.font());
ctx.setFillColor(170, 160, 165)
.setFont(setting)
.setGlobalAlpha(0.4);
// 图片水印
if(dhzwz.equals("1")) {//左上角
ctx.drawImage(imgPath1, 0, 5, img.getWidth()/3.5, img.getHeight()/3.5);
}else if (dhzwz.equals("0")) {//居中
ctx.drawImage(imgPath1, width/2-img.getWidth()/3.5/2, 5, img.getWidth()/3.5, img.getHeight()/3.5);
}else if (dhzwz.equals("2")) {//右上角
ctx.drawImage(imgPath1, width-img.getWidth()/3.5, 5, img.getWidth()/3.5, img.getHeight()/3.5);
}else {//默认居中
ctx.drawImage(imgPath1, width/2-img.getWidth()/3.5/2, 5, img.getWidth()/3.5, img.getHeight()/3.5);
}
});
int Pages = reader.getNumberOfPages()+1;
//循环添加图片
for (int i = 0; i < Pages; i++) {
ofdDoc.addAnnotation(i, annotation);
}
}
System.out.println("ofd加章新位置:" + outP.toAbsolutePath().toString());
return outP.toAbsolutePath().toString();
}
public static void main(String[] args) throws BadElementException, IOException {
String outP = waterMark("D:/xiazai/txt_1.ofd","D:/xiazai/txt_3.ofd","D:/tomcat-guanshi/apache-tomcat-7.0.86-rizhao/webapps/water/1604043783722.jpg","2");
System.out.println("main生成文档位置:" +outP);
}
}
3、效果示例