java实现将图片插入word文档

server/2024/11/28 18:09:06/

插入图片所用依赖

java"> private static void insertImage(XWPFDocument document, String path) {List<XWPFParagraph> paragraphs = document.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {CTP ctp = paragraph.getCTP();for (int dwI = 0; dwI < ctp.sizeOfBookmarkStartArray(); dwI++) {try {CTBookmark bookmark = ctp.getBookmarkStartArray(dwI);if (!"celue".equalsIgnoreCase(bookmark.getName())) continue;FileInputStream fis = new FileInputStream(new File(path));XWPFRun run = paragraph.createRun();//bus.png为鼠标在word里选择图片时,图片显示的名字,宽度,高度100,100则为像素单元,根据实际需要的大小进行调整即可。run.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG, "target1.jpg", Units.toEMU(400), Units.toEMU(500));} catch (InvalidFormatException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {throw new RuntimeException(e);}}}}

上面代码中XWPFDocument documen 用到的依赖在下方

        <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.15</version></dependency>

下面代码对应的依赖在下方 

java">XWPFRun run = paragraph.createRun();//bus.png为鼠标在word里选择图片时,图片显示的名字,宽度,高度100,100则为像素单元,根据实际需要的大小进行调整即可。run.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG, "target1.jpg", Units.toEMU(400), Units.toEMU(500));

        <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15</version></dependency>

剪裁图片所用依赖

java"> public static void main(String[] args) throws IOException {String wordPath = "D:\\work\\project\\jar\\wordtopdf-server\\wordtopdfByjdk16\\src\\main\\resources\\target1.docx";String destPath = "D:\\work\\project\\jar\\wordtopdf-server\\wordtopdfByjdk16\\src\\main\\resources\\targetA.docx";String picturePath = convertSuffix(wordPath, ".png");wordToImage(wordPath,"png");FileInputStream fis = new FileInputStream(new File(wordPath));XWPFDocument document = new XWPFDocument(new FileInputStream(new File(wordPath)));insertImage(document, picturePath);}private static void insertImage(XWPFDocument document, String path) {List<XWPFParagraph> paragraphs = document.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {CTP ctp = paragraph.getCTP();for (int dwI = 0; dwI < ctp.sizeOfBookmarkStartArray(); dwI++) {try {CTBookmark bookmark = ctp.getBookmarkStartArray(dwI);if (!"celue".equalsIgnoreCase(bookmark.getName())) continue;FileInputStream fis = new FileInputStream(new File(path));XWPFRun run = paragraph.createRun();//bus.png为鼠标在word里选择图片时,图片显示的名字,宽度,高度100,100则为像素单元,根据实际需要的大小进行调整即可。run.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG, "target1.jpg", Units.toEMU(400), Units.toEMU(500));} catch (InvalidFormatException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {throw new RuntimeException(e);}}}}

下面是剪裁图片的测试代码,目前剪完后,图片不对,可能是像素点设置的有问题

java">    public static void main(String[] args) throws IOException {String picturePath = "D:\\work\\project\\jar\\wordtopdf-server\\wordtopdfByjdk16\\src\\main\\resources\\targetA..png";BufferedImage bufferedImage = new BufferedImage(793, 1122, BufferedImage.TYPE_INT_RGB);BufferedImage coverImage = ImageUtils.getCoverImage(bufferedImage);File outputfile  = new File(picturePath);ImageIO.write(coverImage, "png", outputfile);}
java">package com.hx.utils;import lombok.extern.slf4j.Slf4j;import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;@Slf4j
public class ImageUtils {/*** bufferedImage转InputStream*/public static InputStream bufferedImageToInputStream(BufferedImage image) {ByteArrayOutputStream os = new ByteArrayOutputStream();try {ImageIO.write(image, "png", os);InputStream input = new ByteArrayInputStream(os.toByteArray());return input;} catch (IOException e) {}return null;}/*** 获取图片大小信息*/public static Rectangle getImgRect(BufferedImage image) throws IOException {Iterator readers = ImageIO.getImageReadersByFormatName("png");ImageReader reader = (ImageReader) readers.next();InputStream source = bufferedImageToInputStream(image);ImageInputStream iis = ImageIO.createImageInputStream(source);reader.setInput(iis, true);int imageIndex = 0;return new Rectangle(0, 0, reader.getWidth(imageIndex), reader.getHeight(imageIndex));}/*** 图片裁剪,按指定大小裁剪*/public static BufferedImage imageCut(BufferedImage image, Rectangle rect) throws IOException {// 取得图片读入器Iterator readers = ImageIO.getImageReadersByFormatName("png");System.out.println(readers);ImageReader reader = (ImageReader) readers.next();System.out.println(reader);// 取得图片读入流InputStream source = bufferedImageToInputStream(image);ImageInputStream iis = ImageIO.createImageInputStream(source);reader.setInput(iis, true);// 图片参数ImageReadParam param = reader.getDefaultReadParam();int imageIndex = 0;//Rectangle rect = new Rectangle(0, 0, reader.getWidth(imageIndex), 100);param.setSourceRegion(rect);BufferedImage bi = reader.read(0, param);iis.close();source.close();return bi;}/*** 压缩图片,用于高质量图片质量降低,改变图片大小*/public static BufferedImage compressImage(BufferedImage imageByte, int ppi) {BufferedImage smallImage = null;int width = 0, height = 0;if (imageByte == null)return null;InputStream byteInput = bufferedImageToInputStream(imageByte);try {Image image = ImageIO.read(byteInput);int w = image.getWidth(null);int h = image.getHeight(null);// adjust weight and height to avoid image distortiondouble scale = 0;scale = Math.min((float) ppi / w, (float) ppi / h);width = (int) (w * scale);width -= width % 4;height = (int) (h * scale);if (scale >= (double) 1)return imageByte;BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);buffImg.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);//ByteArrayOutputStream out = new ByteArrayOutputStream();//ImageIO.write(buffImg, "png", out);smallImage = buffImg;} catch (IOException e) {e.printStackTrace();}return smallImage;}/*** 将BufferedImage转换为byte[]* @param image* @return*/public static byte[] bufferedImageToByteArray(BufferedImage image) throws IOException{ByteArrayOutputStream os = new ByteArrayOutputStream();ImageIO.write(image, "png", os);return os.toByteArray();}/*    *//*** 将BufferedImage转换pdf*//*public static String imageToPdf(List<BufferedImage> images) throws IOException {log.info("图片转pdf开始===============");String newFile = StrUtil.uuid().replace("-", "") + ".pdf";PdfWriter pdfWriter = new PdfWriter( newFile);PdfDocument pdfDocument = new PdfDocument(pdfWriter);Document document = new Document(pdfDocument);for (BufferedImage image : images) {byte[] data = bufferedImageToByteArray(image);com.itextpdf.layout.element.Image img = new com.itextpdf.layout.element.Image(ImageDataFactory.createPng(data));document.add(img);}document.close();log.info("图片转pdf结束===============");return newFile;}*//*** 获取缩略图图片,用作封面,按长宽比例设备,高度太高裁掉,高度太低补余白*/public static BufferedImage getCoverImage (BufferedImage originalImage) throws IOException {BufferedImage result = null;// 获取图片的长宽int originalWidth = originalImage.getWidth();int originalHeight = originalImage.getHeight();Rectangle rect = ImageUtils.getImgRect(originalImage);if (rect.getHeight() > rect.getWidth()) {rect.setRect(0,0, rect.getWidth(), rect.getWidth() / 1.3);result = ImageUtils.imageCut(originalImage, rect);} else {int newWidth = 800;int newHeight = 600;// 计算缩放比例double scale = Math.min((double) newWidth / originalWidth, (double) newHeight / originalHeight);// 计算调整后的长宽int scaledWidth = (int) (originalWidth * scale);int scaledHeight = (int) (originalHeight * scale);// 创建新的BufferedImage对象,添加余白BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g = resizedImage.createGraphics();Color fillColor = new Color(255, 255, 255); // 白颜色g.setColor(fillColor);g.fillRect(0, 0, newWidth, newHeight);g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);g.dispose();result = resizedImage;}return result;}}


http://www.ppmy.cn/server/145687.html

相关文章

C#基础41-45

41. 利用如下所示的简单迭代方法求方程&#xff1a;cos(x)-x0的一个实根。xn1cos(xn)迭代步骤如下&#xff1a; &#xff08;1&#xff09;取X1初值为0.0&#xff1b; &#xff08;2&#xff09;X0X1&#xff0c;把X1的值赋给X0&#xff1b; &#xff08;3&#xff09;X1COS&am…

基于springboot的登录校验

&#x1f525;基于springboot的登录校验&#x1f525; 文章目录 &#x1f525;基于springboot的登录校验&#x1f525;1. JWT令牌2. 过滤器Filter3. 拦截器Interceptor &#x1f680; 开篇寄语&#xff1a; 还在为Spring Boot项目的登录校验而一筹莫展吗&#xff1f;本篇实战教…

《Opencv》基础操作<1>

目录 一、Opencv简介 主要特点&#xff1a; 应用领域&#xff1a; 二、基础操作 1、模块导入 2、图片的读取和显示 &#xff08;1&#xff09;、读取 &#xff08;2&#xff09;、显示 3、 图片的保存 4、获取图像的基本属性 5、图像转灰度图 6、图像的截取 7、图…

第12章 手写Spring MVC

第十二章 手写Spring MVC 12.1 基本结构搭建 12.1.1 创建Maven模块 12.1.2 引入Servlet依赖 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XM…

iframe温习+应用

文章目录 iframe 一、iframe的优缺点&#xff08;一&#xff09;优点&#xff08;二&#xff09;缺点 二、iframe基础应用&#xff08;一&#xff09;基本语法&#xff08;二&#xff09;在实际场景中的应用 三、iframe在无界微前端中的应用解析&#xff08;一&#xff09;沙箱…

QT QVerticalSpacer控件 全面详解

本系列文章全面的介绍了QT中的57种控件的使用方法以及示例,包括 Button(PushButton、toolButton、radioButton、checkBox、commandLinkButton、buttonBox)、Layouts(verticalLayout、horizontalLayout、gridLayout、formLayout)、Spacers(verticalSpacer、horizontalSpacer)、…

ElasticSearch通过es-head插件安装可视化及相关问题

1.es-head下载地址 GitHub - mobz/elasticsearch-head: A web front end for an elastic search cluster 2.启动 建议使用vscode启动&#xff0c;并安装好node.js环境 npm installnpm run start 通过http://localhost:9100就可以看到本地添加的es库 3.相关问题 3.1跨域问…

Python从0到100(七十三):Python OpenCV-OpenCV实现手势虚拟拖拽

前言&#xff1a; 零基础学Python&#xff1a;Python从0到100最新最全教程。 想做这件事情很久了&#xff0c;这次我更新了自己所写过的所有博客&#xff0c;汇集成了Python从0到100&#xff0c;共一百节课&#xff0c;帮助大家一个月时间里从零基础到学习Python基础语法、Pyth…