1.主要工作函数,先在doc文档里面插入书签,然后通过WordHandleContext方法将文档内容转成对象去获取Document节点,Document节点可以提取书签名和书签位置,从而在书签位置插入内容
/**
* 手动插入内容
*
* @param doc
* @param pngPath
* @throws Exception
*/
public static void insertImageToPdf(Document doc, String pngPath) throws Exception {
//设置宽高
CombineImagesUtil tt = new CombineImagesUtil();
BufferedImage top = tt.loadImageLocal(pngPath);
if (top!=null){
int width=top.getWidth()/2;
int height=top.getHeight()/2;
for (Bookmark bookmarks : doc.getRange().getBookmarks()) {
if (bookmarks != null) {
switch (bookmarks.getName()) {
case "photo":
DocumentBuilder builder = new DocumentBuilder(doc);
File file = new File(pngPath);
if (file.exists()) {
//移动到书签位置
builder.moveToBookmark(bookmarks.getName());
//设置格式 WrapType.INLINE 参考:https://www.cnblogs.com/zhmlxx/p/14547931.html
builder.insertImage(pngPath, RelativeHorizontalPosition.DEFAULT, 1, RelativeVerticalPosition.MARGIN, 1, width, height, WrapType.INLINE);
}
break;
default:
break;
}
}
}
}
}
2.比较好用的工具,将图片转成BufferedImage对象可以更好的对图片进行修改
/**
* 导入本地图片到缓冲区
*/
public BufferedImage loadImageLocal(String imgName) {
try {
return ImageIO.read(new File(imgName));
} catch (IOException e) {
System.out.println(e.getMessage());
}
return null;
}
public BufferedImage modifyImagetogeter(BufferedImage b, BufferedImage d,int width,int height,int x ,int y) {
try {
Graphics2D graphics2D = d.createGraphics();
// b.g
graphics2D.drawImage(b, x, y, width, height, null);
graphics2D.dispose();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return d;
}
/**
* 生成新图片到本地
*/
public void writeImageLocal(String newImage, BufferedImage img) {
if (newImage != null && img != null) {
try {
File outputfile = new File(newImage);
ImageIO.write(img, "png", outputfile);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}