标题

  • Java关于创建文件(夹)核心代码提醒
  • 关于Pdf转图片
  • 图片转Pdf
  • Word转Pdf
  • Word转Html
  • HTML转Word
  • html内容转.html文件
  • 读取.html文件内容,进行修改,重命名在重新写回
  • Html转Pdf
  • java使用itext把含图片的html转为pdf
  • PDF转Html
  • [Java 将 XML 转为 Excel](https://www.e-iceblue.cn/spirexlsjavaconversion/convert-xml-to-excel-using-java.html)
  • Excel转XML
  • Excel转PDF
  • Excel转图片
  • Excel转Word
  • Word转图片
  • [ java导出文件压缩包这块可以看看】=]
  • excle导入导出数据的处理(包括多个sheet页,各种样式的设定等内容)
  • 在线预览篇
  • Word转html实现在线预览
  • 课外补充:
  • java实现图片转base64字符串 java实现实base64字符串转图片
  • java-指定图片像素大小,图片剪裁工具
  • [ java 修改图片的像素大小,清晰度]()



如果你遇到NoClassDefFoundError戳我

Java关于创建文件(夹)核心代码提醒

想知道更多文件操作工具类戳我

// jpg文件转出路径
                File file = new File(outputFilePath + Integer.valueOf(i+1) + ".jpg");
                if (!file.getParentFile().exists()) {
                    // 不存在则创建父目录及子文件
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }

关于Pdf转图片

Pdf文件转图片方法一
1、maven依赖                                                2、转换代码
(生成图片清晰,效率1秒转3页的样子)

<!--  Pdf文件转图片方式1所需maven依赖包:start-->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!--  Pdf文件转图片方式1所需maven依赖包:end-->
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class PdfToImgOne {
    /**
     *  pdfToImageFile("E:\\pdf\\1.pdf", "E:\\pdf\\img\\");
     * @param inputFilePath :Pdf地址:"E:\\pdf\\1.pdf"
     * @param outputFilePath :转图片后图片保存地址:"E:\\pdf\\img\\"
     * @throws Exception
     */
    static  void pdfToImageFile(String inputFilePath, String outputFilePath) throws Exception {
        long currentTimeMillisStart = System.currentTimeMillis();
        PDDocument doc = null;
        ByteArrayOutputStream os = null;
        InputStream stream = null;
        OutputStream out = null;
        try {
            // pdf路径
            stream = new FileInputStream(inputFilePath);
            // 加载解析PDF文件
            doc = PDDocument.load(stream);
            PDFRenderer pdfRenderer = new PDFRenderer(doc);
            PDPageTree pages = doc.getPages();
            int pageCount = pages.getCount();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
                os = new ByteArrayOutputStream();
                ImageIO.write(bim, "jpg", os);
                byte[] dataList = os.toByteArray();
                // jpg文件转出路径
                File file = new File(outputFilePath + Integer.valueOf(i + 1) + ".jpg");
                if (!file.getParentFile().exists()) {
                    // 不存在则创建父目录及子文件
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }
                out = new FileOutputStream(file);
                out.write(dataList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (doc != null) doc.close();
            if (os != null) os.close();
            if (stream != null) stream.close();
            if (out != null) out.close();
        }
        long currentTimeMillisEnd = System.currentTimeMillis();
        System.out.println("18页的Pdf转换完成耗时:"
                +(currentTimeMillisEnd - currentTimeMillisStart)/1000);//18页的Pdf转换完成耗时:6
    }
}

Java使用icepdf将pdf文件按页转成图片方法二
1、maven依赖                                                2、转换代码

(生成图片不够清晰,效率1秒转2页的样子)但是人家可以旋转生成的图片,生成图片进行放大也是清晰的

<!--  Pdf文件转图片方式2所需maven依赖包:start-->
        <dependency>
            <groupId>org.icepdf.os</groupId>
            <artifactId>icepdf-core</artifactId>
            <version>6.1.2</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.media</groupId>
                    <artifactId>jai-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--  Pdf文件转图片方式2所需maven依赖包:end-->
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

public class PdfToImgTwo {
    /**
     * 将指定的pdf文件转换为指定路径的图片
     * tranfer("E:\\pdf\\1.pdf","E:\\pdf\\img\\",0.0f,1);
     *
     * @param filepath  原文件路径,
     * @param imagepath 图片生成路径,
     * @param rotation  图片旋转,取值只能是 0.0f, 90.0f, 180.0f, 270.0f.
     * @param zoom      缩略图显示倍数,1表示不缩放,0.3则缩小到30%  这个参数太大直接影响转换速度 1 是最快的
     */
    public static void tranfer(String filepath, String imagepath, float rotation, float zoom) throws PDFException, PDFSecurityException, IOException {
        long currentTimeMillisStart = System.currentTimeMillis();
        Document document = null;
        document = new Document();
        document.setFile(filepath);
        int maxPages = document.getPageTree().getNumberOfPages();
        for (int i = 0; i < maxPages; i++) {
            BufferedImage img = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, zoom);
            Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
            ImageWriter writer = (ImageWriter) iter.next();
            File outFile = new File(imagepath + Integer.valueOf(i + 1) + ".jpg");
            FileOutputStream out = new FileOutputStream(outFile);
            ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
            writer.setOutput(outImage);
            writer.write(new IIOImage(img, null, null));
        }
        long currentTimeMillisEnd = System.currentTimeMillis();
        System.out.println("18页的Pdf转换完成耗时:"
                + (currentTimeMillisEnd - currentTimeMillisStart) / 1000);//18页的Pdf转换完成耗时:11
    }

    public static void main(String[] args) throws PDFException, PDFSecurityException, IOException {
        tranfer("E:\\pdf\\1.pdf", "E:\\pdf\\img\\", 0.0f, 2);
    }
}

Java使用icepdf将pdf文件按页转成图片方法三

<dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.1</version>
        </dependency>
package com.cbit.server.modules.report;

import com.google.common.collect.Lists;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PdfToImgTest {
    public static void main(String[] args) {
        //这块你注意 两个绝对路径,如果不存在记得做相关处理呦
        pdfToImage("D:\\downloadFile\\测试.pdf","D:\\downloadFile\\测试.png");
    }

    /**
     * pdf转图片
     *
     * @param pdfPath pdf绝对路径,如果不存在调用此方法前请做相关处理
     * @param imgPath 图片输出路径,如果不存在调用此方法前请做相关处理
     */
    public static void pdfToImage(String pdfPath, String imgPath) {
        File file = new File(pdfPath);
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            List<BufferedImage> picList = Lists.newArrayList();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 500); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                picList.add(image);
            }
            //ImageIO.write((RenderedImage) picList, "png", new File("D:\\Users\\tongweiqi\\Desktop\\asd\\9-7"+"\\"+"测试问题"+"_"+"."+"png"));
            yPic(picList, imgPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将宽度相同的图片,竖向追加在一起 ##注意:宽度必须相同
     *
     * @param picList 文件流数组
     * @param outPath 输出路径
     */
    public static void yPic(List<BufferedImage> picList, String outPath) {// 纵向处理图片
        if (picList == null || picList.size() <= 0) {
            System.out.println("图片数组为空!");
            return;
        }
        try {
            // 总高度
            int height = 0,
                    // 总宽度
                    width = 0,
                    // 临时的高度 , 或保存偏移高度
                    offsetHeight = 0,
                    // 临时的高度,主要保存每个高度
                    tmpHeight = 0,
                    // 图片的数量
                    picNum = picList.size();
            // 保存每个文件的高度
            int[] heightArray = new int[picNum];
            // 保存图片流
            BufferedImage buffer = null;
            // 保存所有的图片的RGB
            List<int[]> imgRgb = new ArrayList<int[]>();
            // 保存一张图片中的RGB数据
            int[] tmpImgRgb;
            for (int i = 0; i < picNum; i++) {
                buffer = picList.get(i);
                // 图片高度
                heightArray[i] = offsetHeight = buffer.getHeight();
                if (i == 0) {
                    // 图片宽度
                    width = buffer.getWidth();
                }
                // 获取总高度
                height += offsetHeight;
                // 从图片中读取RGB
                tmpImgRgb = new int[width * offsetHeight];
                tmpImgRgb = buffer.getRGB(0, 0, width, offsetHeight, tmpImgRgb, 0, width);
                imgRgb.add(tmpImgRgb);
            }
            // 设置偏移高度为0
            offsetHeight = 0;
            // 生成新图片
            BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < picNum; i++) {
                tmpHeight = heightArray[i];
                if (i != 0) {
                    // 计算偏移高度
                    offsetHeight += tmpHeight;
                }
                // 写入流中
                imageResult.setRGB(0, offsetHeight, width, tmpHeight, imgRgb.get(i), 0, width);
            }
            File outFile = new File(outPath);
            // 写图片
            ImageIO.write(imageResult, "png", outFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

图片转Pdf

这块需要你导入一些jar包依赖

java 写数据入pdf java实现pdf转excel_java PDF与图片互转、

import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.color.DeviceGray;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.property.TextAlignment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

public class ImgToPdfOne {
    /**
     * 这块转成的pdf中图片大小可在方法内自己修改定义,
     * imgToPdf("E:\\pdf\\test\\1.jpg", "E:\\pdf\\test\\1.pdf");
     * @param imgFilePath    图片路径地址
     * @param outputFilePath 生成pdf文件地址 必须先创建此文件,不然报错
     */
    public static void imgToPdf(String imgFilePath, String outputFilePath) {
        try {
            long currentTimeMillisStart = System.currentTimeMillis();
            File createPdf = new File(outputFilePath);
            if (!createPdf.getParentFile().exists()) {
                // 不存在则创建父目录及子文件
                createPdf.getParentFile().mkdirs();
                try {
                    createPdf.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outputFilePath));
            Document doc = new Document(pdfDoc);
            Image image = new Image(ImageDataFactory.create(imgFilePath));
            image.scaleToFit(400, 700);
            PdfFormXObject template = new PdfFormXObject(
                    new Rectangle(image.getImageScaledWidth(), image.getImageScaledHeight()));
            Canvas canvas = new Canvas(template, pdfDoc).add(image);
//            String watermark = "Welcome to yiibai.com";//这句话会打印在图片上 不支持中文 有长度限制
            String watermark = "";
            //下面图片格式可调整
            canvas.setFontColor(DeviceGray.RED).showTextAligned(watermark, 100, 160, TextAlignment.CENTER);
            // Adding template to document
            Image image1 = new Image(template);
            doc.add(image1);
            doc.close();
            long currentTimeMillisEnd = System.currentTimeMillis();
            System.out.println("Pdf图片转换完成耗时:"
                    + (currentTimeMillisEnd - currentTimeMillisStart) / 1000);//Pdf图片转换完成耗时:0
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        imgToPdf("E:\\pdf\\test\\1.jpg", "E:\\pdf\\test\\1.pdf");
    }
}

下面这个图片转Pdf挺强大,可以把文件夹下多个图片写入一个Pdf中,你还可以设置写入图片的大小,位置,唯一一个缺点好像最后总是多一个空白页。
需要引入一个jar包。( 添加必须的iText.jar;)

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImgToPdfTwo {
    /**
     * 把一个文件下的指定图片格式的所有图片,批量写入pdf
     */
    public void imgToPdfTwo() {
        //创建一个文档对象
        Document doc = new Document();
        try {
            //定义输出文件的位置  需要提前创建1.pdf文件来存截图
            PdfWriter.getInstance(doc, new FileOutputStream("E:\\pdf\\test\\1.pdf"));
            //开启文档
            doc.open();
            //设定字体 为的是支持中文
//            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//             Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
            //向文档中加入图片
            String path = "E:\\pdf\\test\\";//图片所在的文件夹
            //遍历该文件下的文件
            File file = new File(path);
            File[] files = file.listFiles();//获取到所有文件遍历自己想要操作的文件
            //如果只是遍历一张图片直接把路径写死即可 灵活应用
            //  Image jpg1 = Image.getInstance("E:\\pdf\\test\\1.jpg");
            for (int i = 0; i < files.length; i++) {
                File file1 = files[i];
                //根据后缀判断是否是图片
                String[] imgTrue = file1.getName().split("\\.");
                if ("jpg".equals(imgTrue[1])) {
                    //取得图片~~~图片格式:
                    System.out.println("---" + file1.getName());
                    Image jpg1 = Image.getInstance(path + "/" + imgTrue[0] + ".jpg"); //原来的图片的路径
                    //获得图片的高度
                    float heigth = jpg1.height();
                    float width = jpg1.width();
                    System.out.println("原图片heigth" + i + "----" + heigth);
                    System.out.println("原图片width" + i + "-----" + width);
                    //合理压缩,h>w,按w压缩,否则按w压缩
//                int percent=getPercent(heigth, width); //图片小时基本效果就是把原图片放到pdf中
                    //统一按照宽度压缩
                    int percent = getPercent2(heigth, width);
                    //设置图片居中显示
                    jpg1.setAlignment(Image.MIDDLE);
                    //直接设置图片的大小~~~~~~~第三种解决方案,按固定比例压缩
//                jpg1.scaleAbsolute(210.0f, 297.0f);
                    //按百分比显示图片的比例
                    jpg1.scalePercent(percent);//表示是原来图像的比例;
                    //todo 可设置图像高和宽的比例
                    //jpg1.scalePercent(50, 100);
                    doc.add(jpg1);
                }
            }
            //关闭文档并释放资源
            doc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 第一种解决方案
     * 在不改变图片形状的同时,判断,如果h>w,则按h压缩,否则在w>h或w=h的情况下,按宽度压缩
     *
     * @return
     */
    public int getPercent(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        if (h > w) {
            p2 = 297 / h * 100;
        } else {
            p2 = 210 / w * 100;
        }
        p = Math.round(p2);
        return p;
    }

    /**
     * 第二种解决方案,统一按照宽度压缩
     * 这样来的效果是,所有图片的宽度是相等的,自我认为给客户的效果是最好的
     */
    public int getPercent2(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }

    /**
     * 第三种解决方案,就是直接压缩,不安像素比例,全部压缩到固定值,如210*297
     *
     * @param args
     */
    public static void main(String[] args) {
        ImgToPdfTwo pt = new ImgToPdfTwo();
        pt.imgToPdfTwo();
    }
}

Word转Pdf

方法一,缺陷:doc文件转pdf(目前最大支持21页),好像转换少了最后一页,自己注意

java 写数据入pdf java实现pdf转excel_PDF与HTML互转_02


项目远程仓库

aspose-words 这个需要配置单独的仓库地址才能下载,不会配置的可以去官网直接下载jar引入项目代码中。

<repositories>
        <repository>
            <id>AsposeJavaAPI</id>
            <name>Aspose Java API</name>
            <url>https://repository.aspose.com/repo/</url>
        </repository>
    </repositories>


  <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>3.0.0-RC1</version>
        </dependency>
        <dependency>
            <groupId>com.github.jai-imageio</groupId>
            <artifactId>jai-imageio-jpeg2000</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>21.9</version>
            <type>pom</type>
        </dependency>
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.pdfparser.PDFStreamParser;
import org.apache.pdfbox.pdfwriter.ContentStreamWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDStream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

  /**
     *         doc2pdf("C:\\Users\\雷神\\Desktop\\JAVA开发工程师新.docx"
     *         ,"E:\\pdf\\html\\pdf\\","JAVA开发工程师新");
     * @param wordPath word 文件绝对路径
     * @param outPutPdfPath  pdf保存路径
     * @param newName pdf名
     */
    //doc文件转pdf(目前最大支持21页)
    public static void doc2pdf(String wordPath,String outPutPdfPath,String newName) {
        long old = System.currentTimeMillis();
        try {
            //新建一个pdf文档
            String pdfPath = outPutPdfPath + newName+".pdf";
            File file = new File(pdfPath);
            FileOutputStream os = new FileOutputStream(file);
            //Address是将要被转化的word文档
            Document doc = new Document(wordPath);
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
//            doc.save(os, SaveFormat.PDF);
            doc.save(os, SaveFormat.PDF);
            os.close();
            //去除水印
            removeWatermark(new File(pdfPath));
            //转化用时
            long now = System.currentTimeMillis();
            System.out.println("Word 转 Pdf 共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            System.out.println("Word 转 Pdf 失败...");
            e.printStackTrace();
        }
        }


    //替换pdf文本内容
    public static void replaceText(PDPage page, String searchString, String replacement) throws IOException {
        PDFStreamParser parser = new PDFStreamParser(page);
        List<?> tokens = parser.parse();
        for (int j = 0; j < tokens.size(); j++) {
            Object next = tokens.get(j);
            if (next instanceof Operator) {
                Operator op = (Operator) next;
                String pstring = "";
                int prej = 0;
                if (op.getName().equals("Tj")) {
                    COSString previous = (COSString) tokens.get(j - 1);
                    String string = previous.getString();
                    string = string.replaceFirst(searchString, replacement);
                    previous.setValue(string.getBytes());
                } else if (op.getName().equals("TJ")) {
                    COSArray previous = (COSArray) tokens.get(j - 1);
                    for (int k = 0; k < previous.size(); k++) {
                        Object arrElement = previous.getObject(k);
                        if (arrElement instanceof COSString) {
                            COSString cosString = (COSString) arrElement;
                            String string = cosString.getString();

                            if (j == prej) {
                                pstring += string;
                            } else {
                                prej = j;
                                pstring = string;
                            }
                        }
                    }
                    if (searchString.equals(pstring.trim())) {
                        COSString cosString2 = (COSString) previous.getObject(0);
                        cosString2.setValue(replacement.getBytes());
                        int total = previous.size() - 1;
                        for (int k = total; k > 0; k--) {
                            previous.remove(k);
                        }
                    }
                }
            }
        }
        List<PDStream> contents = new ArrayList<>();
        Iterator<PDStream> streams = page.getContentStreams();
        while (streams.hasNext()) {
            PDStream updatedStream = streams.next();
            OutputStream out = updatedStream.createOutputStream(COSName.FLATE_DECODE);
            ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
            tokenWriter.writeTokens(tokens);
            contents.add(updatedStream);
            out.close();
        }
        page.setContents(contents);
    }

    //移除图片水印
    public static void removeImage(PDPage page, String cosName) {
        PDResources resources = page.getResources();
        COSDictionary dict1 = resources.getCOSObject();
        resources.getXObjectNames().forEach(e -> {
            if (resources.isImageXObject(e)) {
                COSDictionary dict2 = dict1.getCOSDictionary(COSName.XOBJECT);
                if (e.getName().equals(cosName)) {
                    dict2.removeItem(e);
                }
            }
            page.setResources(new PDResources(dict1));
        });
    }


    //移除文字水印
    public static boolean removeWatermark(File file) {
        try {
            //通过文件名加载文档
            PDDocument document = Loader.loadPDF(file);
            PDPageTree pages = document.getPages();
            Iterator<PDPage> iter = pages.iterator();
            while (iter.hasNext()) {
                PDPage page = iter.next();
                //去除文字水印
                replaceText(page, "Evaluation Only. Created with Aspose.Words. Copyright 2003-2021 Aspose Pty Ltd.", "");
                replaceText(page, "Created with an evaluation copy of Aspose.Words. To discover the full versions of our APIs please", "");
                replaceText(page, "visit: https://products.aspose.com/words/", "");
//                replaceText(page, "Created with an evaluation copy of Aspose.Words. To discover the full", "");
//                replaceText(page, "versions of our APIs please visit: https://products.aspose.com/words/", "");
//                replaceText(page, "This document was truncated here because it was created in the Evaluation", "");

            //去除图片水印
                removeImage(page, "X1");

            }
            document.removePage(document.getNumberOfPages() - 1);
            file.delete();
            document.save(file);
            document.close();
            return true;
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }

    }

方法二:亲测好用
我们需要引入一个jar,2个dll文件 引入jar文件和dll文件 , jar文件的引入就不多说了,
关于dll文件,放在jdk文件下面的bin目录下

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;

import java.io.File;

  /**
     *   wordToPdfSecond("C:\\Users\\雷神\\Desktop\\JAVA开发工程师新.docx","E:\\pdf\\html\\pdf\\开发工程师新2.pdf");
     * @param wordFile
     * @param pdfFile
     */
    public static void wordToPdfSecond(String wordFile,String pdfFile){
        // 开始时间
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        try {
            // 打开word
            app = new ActiveXComponent("Word.Application");
            // 设置word不可见,很多博客下面这里都写了这一句话,其实是没有必要的,因为默认就是不可见的,如果设置可见就是会打开一个word文档,对于转化为pdf明显是没有必要的
            //app.setProperty("Visible", false);
            // 获得word中所有打开的文档
            Dispatch documents = app.getProperty("Documents").toDispatch();
            System.out.println("打开文件: " + wordFile);
            // 打开文档
            Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
            // 如果文件存在的话,不会覆盖,会直接报错,所以我们需要判断文件是否存在
            File target = new File(pdfFile);
            if (target.exists()) {
                target.delete();
            }
            System.out.println("另存为: " + pdfFile);
            // 另存为,将文档报错为pdf,其中word保存为pdf的格式宏的值是17
            Dispatch.call(document, "SaveAs", pdfFile, 17);
            // 关闭文档
            Dispatch.call(document, "Close", false);
            // 结束时间
            long end = System.currentTimeMillis();
            System.out.println("转换成功,用时:" + (end - start)/1000.0 + "ms");
        } catch (Exception e) {
            System.out.println("转换失败" + e.getMessage());
        } finally {
            // 关闭office
            app.invoke("Quit", 0);
        }
    }

下面这个我没有亲自尝试,感兴趣可以试试
JAVA-Word转PDF各种版本实现方式–亲测有效Java Word转为PDF/Html/图片(基于Spire.Cloud.SDK for Java)

Word转Html

Java在线预览(word转html)–强势推荐 上面这篇博客我试了下两大缺陷 它只能支持.doc,不认.docx 而且就算你把.docx重命名为.doc它也不认,它默认会把html文件生成在同一目录下,包括图片信息,文字内容等,所以不能随意切换目录,不然你打开html文件信息内容不全。

这块Word转Html方法分两个 一个转.doc 一个转.docx

<dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.14</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-scratchpad</artifactId>
      <version>3.14</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.14</version>
    </dependency>
    <dependency>
      <groupId>fr.opensagres.xdocreport</groupId>
      <artifactId>xdocreport</artifactId>
      <version>1.0.6</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>3.14</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>ooxml-schemas</artifactId>
      <version>1.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.directory.studio/org.apache.commons.io -->
    <dependency>
      <groupId>org.apache.directory.studio</groupId>
      <artifactId>org.apache.commons.io</artifactId>
      <version>2.4</version>
    </dependency>

下面这个仅支持.doc文件转HTML

import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;


public class Word2007ToHtml {

    /**
     * wordToHtmlFile("C:\\Users\\雷神\\Desktop\\开发工程师新111.doc","E:\\pdf\\html\\22\\","abc");
     * 这个的缺陷就是它只认 .doc文档  你修改docx为doc依旧不行 ,也就是文件出生的时候就是doc
     *
     * @param wordFilePath
     * @param outHtmlFilePath
     * @param htmlName
     * @throws Throwable
     */
    public static void wordToHtmlFile(String wordFilePath, String outHtmlFilePath, String htmlName) throws Throwable {
        System.out.println("开始转换html");
        long currentTimeMillisStart = System.currentTimeMillis();
        InputStream input = new FileInputStream(wordFilePath);
        HWPFDocument wordDocument = new HWPFDocument(input);
        // 实例化WordToHtmlConverter,为图片等资源文件做准备
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .newDocument());
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
            @Override
            public String savePicture(byte[] content, PictureType pictureType,
                                      String suggestedName, float widthInches, float heightInches) {
                return suggestedName;
            }
        });

        wordToHtmlConverter.processDocument(wordDocument);
        // 处理图片,会在同目录下生成并保存图片
        List pics = wordDocument.getPicturesTable().getAllPictures();
        if (pics != null) {
            for (int i = 0; i < pics.size(); i++) {
                Picture pic = (Picture) pics.get(i);
                try {
                    pic.writeImageContent(new FileOutputStream(outHtmlFilePath
                            + pic.suggestFullFileName()));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outStream);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        outStream.close();
        String content = new String(outStream.toByteArray());
        FileUtils.writeStringToFile(new File(outHtmlFilePath, htmlName + ".html"), content, "utf-8");
        long currentTimeMillisEnd = System.currentTimeMillis();
        System.out.println("转换完成耗时:" + (currentTimeMillisEnd - currentTimeMillisStart) / 1000.0);
    }

    public static void main(String[] args) throws Throwable {
        wordToHtmlFile("C:\\Users\\雷神\\Desktop\\设计文档模板\\JAVA开发工程师新111.doc", "E:\\pdf\\html\\22\\", "abc");
    }
}

跟上面一样要求只不过这个特点是:图片转为base64

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.Base64;

/**
     * 仅仅支持 .doc  格式效果不错 推荐使用
     *wordToHTMLDoc("C:\\Users\\雷神\\Desktop\\设计文档模板\\全国农险平台电子化服务系统-概要设计说明书.doc",
     *  "C:\\Users\\雷神\\Downloads\\itext-5.3.5\\", "111");
     * @param docxFilePath
     * @param outputFilePath html保存路径
     * @param outputFileName 新生成的html名称
     */
    public static void wordToHTMLDoc(String docxFilePath, String outputFilePath, String outputFileName) throws IOException, ParserConfigurationException, TransformerException {
        // docx to html
        // 1) 加载XWPFDocument及文件
        InputStream stream = new FileInputStream(docxFilePath);
        HWPFDocument wordDocument = new HWPFDocument(stream);
        WordToHtmlConverter converter = new WordToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        // 对HWPFDocument进行转换
        converter.setPicturesManager(new PicturesManager() {
            @Override
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName,
                                      float widthInches, float heightInches) {
                String type = pictureType.name();
                final Base64.Encoder encoder = Base64.getEncoder();
                return "data:image/" + type + ";base64," + new String(encoder.encodeToString(content));
            }
        });
        converter.processDocument(wordDocument);

        Document htmlDocument = converter.getDocument();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outStream);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");// 编码格式
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");// 是否用空白分割
        serializer.setOutputProperty(OutputKeys.METHOD, "html");// 输出类型
        serializer.transform(domSource, streamResult);
        outStream.close();
        String templateContent = new String(outStream.toByteArray());
        System.out.println(templateContent);
        //将HTML文件内容写入文件中
        FileOutputStream fileoutputstream = new FileOutputStream(outputFilePath + outputFileName + ".html");// 建立文件输出流
        byte tag_bytes[] = templateContent.getBytes();
        fileoutputstream.write(tag_bytes);
        fileoutputstream.close();
    }

下面这个仅仅支持.docx转html

import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
    /**
     *         word2007ToHtml("C:\\Users\\雷神\\Desktop\\设计文档模板\\JAVA开发工程师新.docx", "E:\\pdf\\html\\22\\", "wo");
     * @param filepath
     * @param targetFilePath
     * @param targetFileName
     * @throws Exception
     */

    public static void word2007ToHtml(String filepath, String targetFilePath, String targetFileName) throws Exception {
        String imagePathStr = targetFilePath + "/image/";
        OutputStreamWriter outputStreamWriter = null;
        try {
            XWPFDocument document = new XWPFDocument(new FileInputStream(filepath));
            XHTMLOptions options = XHTMLOptions.create();
            // 存放图片的文件夹
            options.setExtractor(new FileImageExtractor(new File(imagePathStr)));
            // html中图片的路径
            options.URIResolver(new BasicURIResolver("image"));
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(targetFilePath+targetFileName+".html"), "utf-8");
            XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
            xhtmlConverter.convert(document, outputStreamWriter, options);
        } finally {
            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }
        }
    }

这个是图片转为base64 就不用上面还生成在本地了,比上面更好用 推荐使用。
在上面pom的基础上在增加一个依赖

<dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.7.3</version>
        </dependency>
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.util.Base64;
import java.util.List;

 /**
 	 * wordToHTML("C:\\Users\\雷神\\Desktop\\设计文档模板\\舱-汇总.docx"
 	 * ,"C:\\Users\\雷神\\Downloads\\itext-5.3.5\\","999");

     * 仅仅支持 .docx  格式效果不错 推荐使用
     * @param docxFilePath "C:\\Users\\雷神\\Desktop\\设计文档模板\\基金管理信息系统-内网端需求规格说明书V1.0.0-20210604-登录、综合事项、系统管理、驾驶舱-汇总.docx"
     * @param outputFilePath html保存路径
     * @param outputFileName 新生成的html名称
     */
    public static void wordToHTML(String docxFilePath,String outputFilePath,String outputFileName)throws IOException{
        // docx to html
        // 1) 加载XWPFDocument及文件
        InputStream stream = new FileInputStream(docxFilePath);
        XWPFDocument document = document = new XWPFDocument(stream);
        List<XWPFPictureData> list = document.getAllPictures();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(document, outputStream, null);

        String s = new String(outputStream.toByteArray());
        org.jsoup.nodes.Document doc = Jsoup.parse(s);
        Elements elements = doc.getElementsByTag("img");
        if (elements != null && elements.size() > 0 && list != null) {
            for (Element element : elements) {
                String src = element.attr("src");
                for (XWPFPictureData data : list) {
                    if (src.contains(data.getFileName())) {
                        String type = src.substring(src.lastIndexOf(".") + 1);
                        final Base64.Encoder encoder = Base64.getEncoder();
                        String base64 = "data:image/" + type + ";base64," + new String(encoder.encodeToString(data.getData()));
                        element.attr("src", base64);
                        break;
                    }
                }
            }
        }
        document.close();
        String templateContent = doc.toString();
        //将HTML文件内容写入文件中
        FileOutputStream fileoutputstream = new FileOutputStream(outputFilePath+outputFileName+".html");// 建立文件输出流
        byte tag_bytes[] = templateContent.getBytes();
        fileoutputstream.write(tag_bytes);
        fileoutputstream.close();
    }

下面这个也是只支持.docx 但是转成的效果样式有些不太友好,不知道智能换行,不推荐
还需要导入一个jar包

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
     * word转HTML
     *word2HTML( "C:\\Users\\雷神\\Desktop\\JAVA开发工程师新.docx",     "E:\\pdf\\html\\22\\htmlhha.html");
     * @param docPath
     * @param savePath
     */
    public static void word2HTML(String docPath, String savePath) {
        try {
            String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
            ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
            License license = new License();
            license.setLicense(is);
            Document document = new Document(docPath);
            document.save(new FileOutputStream(new File(savePath)), SaveFormat.HTML);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

下面两个网址好像转换好点,没试过,因为看要注册获取密钥,一月800,超过次数可能会出问题,就没有尝试
如何在 Java 中将 DOCX 转换为 HTML网址1如何在 Java 中将 DOCX 转换为 HTML网址2

HTML转Word

注意:亲测好用,默认转.doc 可自己改为.docx
相关jar包下载

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
 * 将html文档转为doc
 * @author soildwang
 *
 */
public class Test {

    /**
     * 读取html文件到word 可以转 ".doc"及".docx" 默认转".doc" 需要时候可改
     * @param filepath    html文件的路径
     * @param outPutWordPath word保存路径
     * @param newWordName 生成word名称
     * @return
     * @throws Exception
     */
    public boolean writeWordFile(String filepath,String outPutWordPath,String newWordName) throws Exception {
        boolean flag = false;
        ByteArrayInputStream bais = null;
        FileOutputStream fos = null;
        String path =  outPutWordPath;
        try {
            if (!"".equals(path)) {
                File fileDir = new File(path);
                if (fileDir.exists()) {
                    String content = readFile(filepath);
                    //  content=new String(content.getBytes(), "UTF-8");
                    //System.out.println("content====="+content);
                    byte b[] = content.getBytes();
                    bais = new ByteArrayInputStream(b);
                    POIFSFileSystem poifs = new POIFSFileSystem();
                    DirectoryEntry directory = poifs.getRoot();
                    DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
                    //fos = new FileOutputStream(path +newWordName+ ".doc");
                    fos = new FileOutputStream(path +newWordName+ ".docx");
                    poifs.writeFilesystem(fos);
                    bais.close();
                    fos.close();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null) fos.close();
            if(bais != null) bais.close();
        }
        return flag;
    }

    /**
     * 读取html文件到字符串
     * @param filename
     * @return
     * @throws Exception
     */
    public String readFile(String filename) throws Exception {
        StringBuffer buffer = new StringBuffer("");
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(filename));
            buffer = new StringBuffer();
            while (br.ready())
                buffer.append((char) br.read());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(br!=null) br.close();
        }
        return buffer.toString();
    }

    public static void main(String[] args) throws Exception {
        new Test().writeWordFile("D:\\appinstall\\weixin\\file\\JAVA开发工程师新11.html"
        ,"D:\\appinstall\\weixin\\file\\","lxd");
    }
}

html内容转.html文件

这块核心思想就是动态组装html内容。
html内容转.html文件(无图片)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


    /**
     * Java根据html模板创建生成 .html文件
     * @param templateContent  html内容
     * @param htmlFile 生成html文件保存路径
     *  如:"E:\\pdf\\html\\a.html"(注意指明生成html的名称,不用创建a.html)
     */

    public static void createHtml(String templateContent, String htmlFile){
        try{
            //将HTML文件内容写入文件中
            FileOutputStream fileoutputstream = new FileOutputStream(htmlFile);// 建立文件输出流
            byte tag_bytes[] = templateContent.getBytes();
            fileoutputstream.write(tag_bytes);
            fileoutputstream.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

html内容转.html文件(有图片)
需要动态获取图片,那源模板就得有图片路径的占位符,然后把占位符换成图片路径即可,没啥技术点。(你可以在编写html内容通过传参替换,也可以在上面方法基础上加个图片路径参数,把占位符内容替换)

读取.html文件内容,进行修改,重命名在重新写回

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


    /**
     * MakeHtml("E:\\pdf\\html\\22\\a.html","E:\\pdf\\html\\1.jpg","E:\\pdf\\html\\22\\","b");
     * @Description: 重新创建html
     * @param    filePath 原模板文件路径到文件名
     * @param    imagePath 需要显示图片的路径
     * @param    disrPath  生成html的存放路径
     * @param    fileName  生成html名字
     */
    public static void MakeHtml(String filePath,String imagePath,String disrPath,String fileName ){
        try {
            String img = "<image src="+'"'+imagePath+'"'+"/>";
//            System.out.print("文件输入路径:\n"+filePath);
            String templateContent = "";
            FileInputStream fileinputstream = new FileInputStream(filePath);// 读取模板文件
            int lenght = fileinputstream.available();
            byte bytes[] = new byte[lenght];
            fileinputstream.read(bytes);
            fileinputstream.close();
            templateContent = new String(bytes);
            System.out.println(templateContent);
            templateContent = templateContent.replaceAll("###title###", img);
            System.out.println("---------------开始(修改)替换--------------");
            System.out.println(templateContent);

            String fileame = fileName + ".html";
            fileame = disrPath+ File.separator + fileame;// 生成的html文件保存路径。
            FileOutputStream fileoutputstream = new FileOutputStream(fileame);// 建立文件输出流
            System.out.println("文件输出路径:\n"+fileame);
            byte tag_bytes[] = templateContent.getBytes();
            fileoutputstream.write(tag_bytes);
            fileoutputstream.close();
        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }

Html转Pdf

这个博客还行,主要HtmlUtils,提供变动方法,然后动态拼接,思想挺好可以学学。
设置中文字体,ttf文件夹下SimSum-01和Dengb ttf文件分别支持细字体和粗字体,缺一不可。
ttf字体下载地址:

<!--将html转换成pdf-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>2.0.2</version>
        </dependency>

java使用itext把含图片的html转为pdf

MAVEN 依赖

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.4.2</version>
</dependency>
<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>core-renderer</artifactId>
    <version>R8</version>
</dependency>

下面这个博文很强大,介绍的很全面一定要看
PDF技术(四)-Java实现Html转PDF文件WKHtmlToPdf工具的官网下载地址: 现在基本上都用这几种方式:基于IText、、基于FlyingSaucer、基于WKHtmlToPdf、基于pd4ml
我们系统使用的是WKHtmlToPdf 所以我就以这个举例了。
没有HTML中需要的字体会出现乱码情况
这块需要的字体及转换插件戳我下载 对参数配置感兴趣的请参考:
附上常用命令表;

/**
 * 先说思想
 * 第一步你的准备好了 WKHtmlToPdf插件
 * 第二步你先的有弄好的HTML文件
 * 第三步你需要创建要生成的PDF目录,
 * 第四步接着写一个CustomWKHtmlToPdfUtil工具类
 * 调用工具类方法即可
 * 这里面核心的无非就是 工具类  ,我这里大概说一下,它需要3个核心参数,根据需求不够再加
 * 参数:HTML路径、PDF路径 、插件路径
 */

2个工具类

import java.io.File;

public class CustomWKHtmlToPdfUtil {
    // wkhtmltopdf在系统中的路径  下面是我windows下插件的存放的路径
    private static String toPdfTool = "D:/Users/Desktop/wkhtmltopdf.exe";

    /**
     * @param srcPath  html的绝对路径
     * @param destPath 存放PDF的绝对路径
     * @param path     插件的路径
     * @param flag     我自己定义的,因为有的业务规则不同,为了通用,不同的走自己特有的即可
     * 是每个命令的最后一定要加空格,不然会出现命令粘连的问题,很基础,很难发现。
     * @return
     */
    public static boolean convert(String srcPath, String destPath, String path, String flag) {
        File file = new File(destPath);
        File parent = file.getParentFile();
        // 如果pdf保存路径不存在,则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }
        StringBuilder cmd = new StringBuilder();
        if (System.getProperty("os.name").indexOf("Windows") == -1) {
            // 非windows 系统
            toPdfTool = path;
        }
        cmd.append(toPdfTool);
        //TODO cmd中还可以配置很多参数,根据自己需求去百度往里面填充即可
        cmd.append(" --encoding \"utf-8\" ");
        //需要加页签
        if ("1".equals(flag)) {
            //设置在中心位置的页脚内容
            cmd.append(" --footer-center 第[page]页/共[topage]页");
            //页脚字体大小
            cmd.append(" --footer-font-size 5");
            // 由于页码乱码 下面指定字体后却不乱码了,原理不清楚
            cmd.append(" --footer-font-name '黑体'");
            /**
             * cmd.append(" --header-line");//页眉下面的线
             * cmd.append(" --margin-top 3cm ");//设置页面上边距 (default 10mm)
             * cmd.append(" --header-spacing 5 ");// (设置页眉和内容的距离,默认0)
             * cmd.append(" --footer-line");//* 显示一条线在页脚内容上)
             * cmd.append(" --footer-spacing 5 ");// (设置页脚和内容的距离)
             */
            cmd.append(" ");
        }
        cmd.append(srcPath);
        cmd.append(" ");
        cmd.append(destPath);
        boolean result = true;
//        System.out.println("html 转 PDF命令为:"+cmd.toString());
        try {
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            ClearBufferThread error = new ClearBufferThread(proc.getErrorStream());
            ClearBufferThread output = new ClearBufferThread(proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
            System.out.println("转换PDF成功");

        } catch (Exception e) {
            result = false;
            System.out.println("转换PDF失败" + e.getMessage());

        }
        return result;
    }

}




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ClearBufferThread extends Thread {
    private InputStream is;

    public ClearBufferThread(InputStream is) {
        this.is = is;
    }

    @Override
    public void run() {
        try {
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

接下来就是在service中使用了,因为将来都是要部署到服务器上的 所以你路径肯定的配置不能写死了对吧,所以下面这块代码肯定是不能直接用的,改一下自己对应的系统配置即可。
如果你只是想在本地玩玩的话就忽略下面路径配置,直接给你本地路径即可,没啥说的。
如何配置路径参数:我这里是配置yml文件
下面跟本内容无关,吐槽一下同时反思自己要尽量规范开发
【注意我这块本来都是要配置在report下的,这块是要字体的,不然找不到字体会乱码的
但是同事之前的字体都在notice下配置好了,我没必要在配置字体放到report下】这块更合理的做法是,把公用配置都抽离出来作为共享配置,不然我这模块去你底下拿路径就感觉怪怪的,
比如说我们开发一般都是把公用方法放在一个utils目录下,然后各自模块去调用公用方法,他这个就是在自己工作路径下创建了个utils,我想用还的去它工作路径下调用,虽然结果上没有问题,但是多少有点凌乱,万一别人不知道你下面有现成的方法,又写了一个自己的,就无法达到公用效果。

notice:
  htmlSrc: ${CE_HTMLSRC:/usr/local/html}
  pdfSrc: ${CE_PDFSRC:/usr/local/pdf}
  appSrc: ${CE_APPSRC:/usr/local/wkhtmltox/bin/wkhtmltopdf}
  gb2312font: ${CE_GB2312FONT:/usr/local/font/FSGB2312.ttf}
  fzxsfont: ${CE_FZXSFONT:/usr/local/font/FZ.ttf}
  heitifont: ${CE_HEITI:/usr/local/font/heiti.ttf}

report:
  htmlSrc: ${EPORT_HTMLSRC:/usr/local/payReport/html}
  pdfSrc: ${EPORT_PDFSRC:/usr/local/payReport/pdf}
  imgUri: ${EPORT_IMGURI:/usr/local/logoimg/jnbg_logo.png}

参数配置好了如何取呢?

@Value("${notice.appSrc}")
    private String linuxSrc;

    @Value("${report.htmlSrc}")
    private String htmlSrc;

    @Value("${report.pdfSrc}")
    private String pdfSrc;

    @Value("${report.imgUri}")
    private String imgUri;

    @Value("${notice.gb2312font}")
    private String gb2312font;


    @Value("${notice.fzxsfont}")
    private String fzxsfont;


    @Value("${notice.heitifont}")
    private String heitifont;

java 写数据入pdf java实现pdf转excel_PDF与HTML互转_03

//把html中的字体路径参数配置活,避免到时候缺少字体乱码呦
 			templateContent = templateContent.replaceAll("\\$\\{gb2312font}", gb2312font);
            templateContent = templateContent.replaceAll("\\$\\{fzxsfont}", fzxsfont);
            templateContent = templateContent.replaceAll("\\$\\{heitifont}", heitifont);
            templateContent = templateContent.replaceAll("\\$\\{jnbgLogo}", imgUri);


			//先把两个地址的路径确定出来,掉工具类要的就是这两个路径
            String htmlPath = htmlSrc + File.separator + linuxFileId + ".html";
            String pdfPath = pdfSrc + File.separator + linuxFileId + ".pdf";
			//我这里是通过HTML内容生成HTML文件,已经有文件的话请忽略
            //HTML模板生成HTML文件----------开始
            FileUtil.createDirectory(htmlSrc);//检查HTML的路径是否存在,不存在则创建
            createHtml(templateContent, htmlPath);//HTML内容转HTML文件的方法(此文已有)
            //HTML模板生成HTML文件----------结束
            //HTML生成PDF----------开始
            FileUtil.createDirectory(pdfSrc);//检查PDF的路径是否存在,不存在则创建
            //调用工具类的方法即可转化  参数:linuxSrc是插件路径,
            //那个"1"是我这个需求的特殊条件,用来判断的,如果是"1"我要加页签的需求,
            //具体在工具类中可以看出,
            boolean convert = CustomWKHtmlToPdfUtil.convert(htmlPath, pdfPath, linuxSrc, "1");
            if (!convert) {
                throw new RRException("html转pdf异常");
            }
//            System.out.println("HTML:" + htmlSrc + File.separator + payReportName + ".html");
//            System.out.println("PDF:" + pdfSrc + File.separator + payReportName + ".pdf");
            //HTML生成PDF----------结束

PDF转Html

Java 将 XML 转为 Excel

Excel转XML

Excel转PDF

Excel转图片

Excel转Word

Word转图片

还需要 aspose-words-15.8.0-jdk16.jar: 这个效率还是效果都不错 就是第一页照片有个水印,我想通过给word加个空白页来解决,没找到方法暂时未解决。
后来不用上面那个jar包,用这个jar包可去水印

import com.aspose.words.Document;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.SaveFormat;

import java.io.File;
import java.io.FileOutputStream;

/**
     * doc2Img("C:\\Users\\雷神\\Desktop\\设计文档模板\\JAVA开发工程师新.doc", "C:\\Users\\雷神\\Downloads\\itext-5.3.5\\");
     * word文档转图片
     * @param inPath 传入文档地址
     * @param outDir 输出的图片文件夹地址
     */
    public static void doc2Img(String inPath, String outDir) {
        try {
            System.out.println(inPath + " -> " + outDir);
            long old = System.currentTimeMillis();
            // word文档
            Document doc = new Document(inPath);
            // 支持RTF HTML,OpenDocument, PDF,EPUB, XPS转换
            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);
            int pageCount = doc.getPageCount() ;
            for (int i = 0; i < pageCount; i++) {
                File file = new File(outDir + "/" + (i+1) + ".jpg");
                FileOutputStream os = new FileOutputStream(file);
                options.setPageIndex(i);
                doc.save(os, options);
                os.close();
            }
            long now = System.currentTimeMillis();
            System.out.println("convert OK! " + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

使用Java读取PDF文件,并转成String类型字符串返回java后台实现pdf下载导出java 调用itext 把html转成pdf文档HTML转PDF工具(wkhtmltopdf)介绍,支持widows和linux

java实现HTML页面转PDF亲测好用

java开发html转pdf示例(转载)java将html的图文转化为PDF文件输出前端和java后台将HTML转换成pdf

java使用itext把含图片的html转为pdf

itext html转pdf 图片,itext2.0.8 将 HTML 转换成 PDF, 完美 CSS, 带图片, 自动分页

PDF技术(四)-Java实现Html转PDF文件java网页直接转成PDF(样式不缺失)Java实现HTML(带图片)转PDF的解决方案

java:将html生成图片的所有方法比较java 将html生成图片_java通过html生成pdf,支持css和图片以及横向打印java将html内容生成pdf(无水印)java导出生成word之XML方式使用jpedal解析PDF到XMLJava与XML(PDF)

[ java导出文件压缩包这块可以看看】=]

excle导入导出数据的处理(包括多个sheet页,各种样式的设定等内容)

在线预览篇

Word转html实现在线预览

课外补充:

word内容制定替换

原图

java 写数据入pdf java实现pdf转excel_java PDF与图片互转、_04

效果图

java 写数据入pdf java实现pdf转excel_PDF与HTML互转_05

这一块我就不详细说了,给个源码自己去玩吧。

java实现图片转base64字符串 java实现实base64字符串转图片

/**
 * java实现图片转base64字符串  java实现实base64字符串转图片
 */
    /*** base64编码字符串转换为图片
     * @param imgStr base64编码字符串
     * @param path 图片路径 * @return
     */
    public static boolean base64StrToImage(String imgStr, String path) {
        if (imgStr == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            //文件夹不存在则自动创建
            File tempFile = new File(path);
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(tempFile);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }



    /**
     * 图片转base64字符串
     *
     * @param imgFile 图片路径
     * @return
     */
    public static String imageToBase64Str(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    public static void main(String[] args) {
       String str = imageToBase64Str("C:\\Users\\Desktop\\1.jpg");
       System.out.println(str);
       base64StrToImage(str, "C:\\Users\\Desktop\\test\\31.jpg");
      
    }

java-指定图片像素大小,图片剪裁工具

方法一:代码有点多,亲测可用
相关jar包下载,需不需要jar忘了

package util.pig;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
	//获取文件名.之前的内容不包括.
	public static String getSimpleFileName(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(0, pos);
	}
	//获取.之后的内容 不包括.
	public static String getFileExtend(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos+1, fileName.length());
	}

	public static void getAllSubFiles(String dirPath, String fileType, List<String> fileList) {
		File dir = new File(dirPath);
		if (dir.isFile()) {
			if (fileType == null) {
				fileList.add(dir.getPath());
			} else {
				if (dir.getPath().endsWith(fileType)) {
					fileList.add(dir.getPath());
				}
			}
			return;
		}
		File[] files = dir.listFiles();
		if (files != null) {
			for (File file : files) {
				if (file != null) {
					if (file.isFile()) {
						if (fileType == null) {
							fileList.add(file.getPath());
						} else {
							if (file.getName().endsWith(fileType.toLowerCase()) || file.getName().endsWith(fileType.toUpperCase())) {
								fileList.add(file.getPath());
							}
						}
					}else{
						getAllSubFiles(file.getPath(), fileType, fileList);
					}
				}
			}
		}
	}

}
package util.pig;


import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class TransImage {
    public static void main(String[] args) {
        resizeImage("C:\\Users\\p\\Desktop\\待处理\\1.jpeg", "C:\\Users\\p\\Desktop\\待处理\\", 900, 1000, "uu", "jpg");
    }

    /**
     *  resizeImage("C:\\Users\\p\\Desktop\\待处理\\1.jpeg",
     *  "C:\\Users\\p\\Desktop\\待处理\\", 900, 1000, "uu", "jpg");
     * @param srcImageFilePath 图片地址绝对路径
     * @param desImageFilePath 图片生成路径
     * @param width   图片宽 自定义
     * @param height  图片高 自定义
     * @param imgName 图片名称 可选参数,不给走默认
     * @param imgType 图片类型,不给就是原图片类型
     * @return
     */
    public static boolean resizeImage(String srcImageFilePath, String desImageFilePath, int width, int height, String imgName, String imgType) {
        long startTime = System.currentTimeMillis();
        boolean success = false;
        try {
            File srcFile = new File(srcImageFilePath);
            BufferedImage bi = ImageIO.read(srcFile);
            int scaledWidth = 0, scaledHeight = 0;
            if (width > 0 && height <= 0) {
                scaledHeight = width * bi.getHeight() / bi.getWidth();
                scaledWidth = width;
            } else if (height > 0 && width <= 0) {
                scaledWidth = height * bi.getWidth() / bi.getHeight();
                scaledHeight = height;
            } else if (height > 0 && width > 0) {
                scaledHeight = height;
                scaledWidth = width;
            } else {
                throw new Exception("宽高必须至少设置其中一个!");
            }
            if (null == imgType || "".equals(imgType)) {
                imgType = FileUtil.getFileExtend(srcFile.getName());
            }
            if ("".equals(imgName) || null == imgName) {
                //源文件图片叫1.jpeg   生成后叫  1(900×1000).jpeg   宽高不同而不同
                File desFile = new File(desImageFilePath, FileUtil.getSimpleFileName(srcFile.getName())
                        + "(" + scaledWidth + "×" + scaledHeight + ")" +"."+ imgType);
                success = ImageIO.write(createResizedCopy(bi, scaledWidth, scaledHeight), "jpg", desFile);
            } else {
                File desFile = new File(desImageFilePath, imgName +"."+ imgType);
                success = ImageIO.write(createResizedCopy(bi, scaledWidth, scaledHeight), "jpg", desFile);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("图片转换像素完成,用时" + (endTime - startTime) / 1000.0 + "s");
        return success;

    }

    public static BufferedImage createResizedCopy(Image originalImage, int scaledWidth,
                                                  int scaledHeight) {
        BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = scaledBI.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.drawImage(originalImage.getScaledInstance(scaledWidth, scaledHeight,
                Image.SCALE_SMOOTH), 0, 0, null);
        g.dispose();
        return scaledBI;
    }
}

方法二:推荐使用

注意输出路径包括文件名及文件类型

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;


public class Changepic {
    public static void main(String[] args) {
//        changeSize(1080,2080,"D:\\image\\5.jpg");
        updateSize(1080, 1080, "C:\\Users\\p\\Desktop\\待处理\\ceshi1.jpg", "C:\\Users\\p\\Desktop\\待处理\\ceshi2.png");
    }

    /**
     *   updateSize(1080, 1080, "C:\\Users\\p\\Desktop\\待处理\\ceshi1.jpg",
     *   "C:\\Users\\p\\Desktop\\待处理\\ceshi2.png");
     * 修改图片的尺寸,根据原图和需要修改的尺寸生成一个新的图片
     * @param newWidth   自定义宽
     * @param newHeight 自定义高
     * @param path 图片绝对路径
     * @param savepath 图片保存路径 指定文件名及格式 如:ceshi2.png、ceshi2.jpg 等
     * @return
     */
    public static boolean updateSize(int newWidth, int newHeight, String path, String savepath) {
        try {

            File file = new File(path);
            //字节流转图片对象
            Image bi = ImageIO.read(file);
            //构建图片流
            BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            //绘制改变尺寸后的图
            tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null);
            //输出流
            //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            //encoder.encode(tag);
            File outfile = new File(savepath);
            if (!outfile.exists()) {
                outfile.createNewFile();
            }
            ImageIO.write(tag, "JPG", outfile);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 改变图片的尺寸,直接在原图基础上进行修改
     *
     * @param newWidth, newHeight, path
     * @return boolean
     */
    public static boolean changeSize(int newWidth, int newHeight, String path) {
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(path));

            //字节流转图片对象
            Image bi = ImageIO.read(in);
            //构建图片流
            BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            //绘制改变尺寸后的图
            tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null);
            //输出流
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
            //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            //encoder.encode(tag);
            ImageIO.write(tag, "PNG", out);
            in.close();
            out.close();
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}

java 修改图片的像素大小,清晰度

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.*;


public class Changepic {
    public static void main(String[] args) throws IOException {

//        updateSize(1080, 1080, "C:\\Users\\p\\Desktop\\待处理\\ceshi1.jpg", "C:\\Users\\p\\Desktop\\待处理\\ceshi2.png");
        compressPictureByQality(new File("C:\\Users\\p\\Desktop\\待处理\\ceshi1.jpg"), 0.85f, "jpg");
    }

    /**
     * 改变图片 像素
     * compressPictureByQality(new File("C:\\Users\\p\\Desktop\\待处理\\ceshi1.jpg"), 0.85f, "jpg");
     * @param file
     * @param qality    参数qality是取值0~1范围内  清晰程度  数值越小分辨率越低
     * @param imageType 图片写出类型 比如 jpg  要与 file文件类型一致
     * @return
     * @throws IOException
     */
    public static File compressPictureByQality(File file, float qality, String imageType) throws IOException {
        BufferedImage src = null;
        FileOutputStream out = null;
        ImageWriter imgWrier;
        ImageWriteParam imgWriteParams;
        System.out.println("开始设定压缩图片参数");

        // 指定写图片的方式为 jpg
        imgWrier = ImageIO.getImageWritersByFormatName(imageType).next();
        imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(
                null);
        // 要使用压缩,必须指定压缩方式为MODE_EXPLICIT
        imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        // 这里指定压缩的程度,参数qality是取值0~1范围内,
        imgWriteParams.setCompressionQuality(qality);
        imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
        ColorModel colorModel = ImageIO.read(file).getColorModel();// ColorModel.getRGBdefault();
        imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
                colorModel, colorModel.createCompatibleSampleModel(32, 32)));

        System.out.println("结束设定压缩图片参数");
        if (!file.exists()) {
            System.out.println("Not Found Img File,文件不存在");
            throw new FileNotFoundException("Not Found Img File,文件不存在");
        } else {
            System.out.println("图片转换前大小" + file.length() + "字节");
            src = ImageIO.read(file);
            //todo 如果你不想覆盖,而是输出到指定文件夹 则打开 fileOut ,一般是覆盖需求,所以我就不把这个写成活参数了
//            File fileOut = new File("C:\\Users\\p\\Desktop\\待处理\\hh1.jpg");
//            out = new FileOutputStream(fileOut);
            out = new FileOutputStream(file);
            imgWrier.reset();
            // 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何
            // OutputStream构造
            imgWrier.setOutput(ImageIO.createImageOutputStream(out));
            // 调用write方法,就可以向输入流写图片
            imgWrier.write(null, new IIOImage(src, null, null),
                    imgWriteParams);
            out.flush();
            out.close();
//            System.out.println("图片转换后大小" + fileOut.length() + "字节");
            System.out.println("图片转换后大小" + file.length() + "字节");
            return file;
        }
    }
}

获取图片的像素(宽、高), 按自定义宽修改: 按自定义宽高修改: 批量修改:

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import javax.imageio.ImageIO;
public class TestAlterImg {
    // todo 获取图片的像素(宽、高), 按自定义宽修改:  按自定义宽高修改: 批量修改:
    /**
     *  getPixel("C:\\Users\\p\\Desktop\\待处理\\uu.jpg");
     * 功能:获取图片像素
     * * @param filePath 图片路径
     */
    public static void getPixel(String filePath){
        File file = new File(filePath);
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int width = bi.getWidth(); // 像素
        int height = bi.getHeight(); // 像素
        System.out.println("width=" + width + ",height=" + height + ".");
    }

    /**
     * resizeImage("C:\\Users\\p\\Desktop\\待处理\\uu.jpg",
     * "C:\\Users\\p\\Desktop\\待处理\\picture.jpg",1100);
     * 更改图片像素  按图片的原比例进行修改:
     * @param srcPath  源图片路径
     * @param desPath  修改大小后图片路径
     * @param scaleSize 图片的修改比例,目标宽度
     */
    public static void resizeImage(String srcPath, String desPath,int scaleSize) throws IOException {

        File srcFile = new File(srcPath);
        Image srcImg = ImageIO.read(srcFile);
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(srcFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        float width = bi.getWidth(); // 像素
        float height = bi.getHeight(); // 像素
        float scale=width/scaleSize;
        BufferedImage buffImg = null;
        buffImg = new BufferedImage(scaleSize, (int)(height/scale), BufferedImage.TYPE_INT_RGB);
        //使用TYPE_INT_RGB修改的图片会变色
        buffImg.getGraphics().drawImage(
                srcImg.getScaledInstance(scaleSize, (int)(height/scale), Image.SCALE_SMOOTH), 0,
                0, null);

        ImageIO.write(buffImg, "JPEG", new File(desPath));
    }

    /**
     * resizeImage("C:\\Users\\p\\Desktop\\待处理\\uu.jpg",
     * "C:\\Users\\p\\Desktop\\待处理\\picture.jpg",800,1800);
     * 按自定义宽高修改:
     * @param srcPath 原图片路径
     * @param desPath  转换大小后图片路径
     * @param width   转换后图片宽度
     * @param height  转换后图片高度
     */
    public static void resizeImage(String srcPath, String desPath,
                                   int width, int height) throws IOException {

        File srcFile = new File(srcPath);
        Image srcImg = ImageIO.read(srcFile);
        BufferedImage buffImg = null;
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //使用TYPE_INT_RGB修改的图片会变色
        buffImg.getGraphics().drawImage(
                srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0,
                0, null);

        ImageIO.write(buffImg, "JPEG", new File(desPath));
    }

    /**
     *  getFiles("C:\\Users\\p\\Desktop\\待处理\\",
     *     "C:\\Users\\p\\Desktop\\待处理\\file\\",150);
     * @param path  源图片文件夹路径
     * @param modPath  修改大小后图片文件夹路径
     * @param scaleSize 图片的修改比例,目标宽度
     */
    public static void getFiles(String path,String modPath,int scaleSize) throws IOException {
        ArrayList<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();
        //循环读取目录下图片
        //todo 在Windows系统获取的文件路径由于其中的\往往不能直接在代码中使用, 因此介绍一下如何替换字符串中的\(反斜杠):
        //对String对象使用.replaceAll("\\\\","/")即可将所有\替换为/,进而方便文件的使用。
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                String fileType = tempList[i].getName().substring(tempList[i].getName().indexOf(".") + 1);
                String allType ="bmp,jpg,jpeg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF";
                if (allType.toLowerCase(Locale.ROOT).contains(fileType.toLowerCase(Locale.ROOT))) {
//                    System.out.println("文件:" + tempList[i].getName()+"\n"+tempList[i].getAbsolutePath());
//                    System.out.println("文件:" + tempList[i].getName()+"\n"+tempList[i].getAbsolutePath().replaceAll("\\\\","/"));
                    resizeImage(tempList[i].getAbsolutePath().replaceAll("\\\\","/")
                            ,modPath.replaceAll("\\\\","/")+tempList[i].getName(),scaleSize);
                    files.add(tempList[i].toString());
                }

            }
            if (tempList[i].isDirectory()) {
                  System.out.println("文件夹:" + tempList[i]);
            }
        }
        System.out.println(path+"下文件数量:"+files.size());
    }

    /**
     *  getFiles("C:\\Users\\p\\Desktop\\待处理\\",
     *     "C:\\Users\\p\\Desktop\\待处理\\file\\",150);
     * @param path  源图片文件夹路径
     * @param modPath  修改大小后图片文件夹路径
     * @param width 图片的修改比例,目标宽度
     * @param height 图片的修改比例,目标高度
     */
    public static void getFiles(String path,String modPath,int width, int height) throws IOException {
        ArrayList<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();
        //循环读取目录下图片
        //todo 在Windows系统获取的文件路径由于其中的\往往不能直接在代码中使用, 因此介绍一下如何替换字符串中的\(反斜杠):
        //对String对象使用.replaceAll("\\\\","/")即可将所有\替换为/,进而方便文件的使用。
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                String fileType = tempList[i].getName().substring(tempList[i].getName().indexOf(".") + 1);
                String allType ="bmp,jpg,jpeg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF";
                if (allType.toLowerCase(Locale.ROOT).contains(fileType.toLowerCase(Locale.ROOT))) {
//                    System.out.println("文件:" + tempList[i].getName()+"\n"+tempList[i].getAbsolutePath());
//                    System.out.println("文件:" + tempList[i].getName()+"\n"+tempList[i].getAbsolutePath().replaceAll("\\\\","/"));
                    resizeImage(tempList[i].getAbsolutePath().replaceAll("\\\\","/")
                            ,modPath.replaceAll("\\\\","/")+tempList[i].getName(),1200,1500);
                    files.add(tempList[i].toString());
                }

            }
            if (tempList[i].isDirectory()) {
                System.out.println("文件夹:" + tempList[i]);
            }
        }
        System.out.println(path+"下文件数量:"+files.size());
    }



}

或者

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 图像压缩工具
 *
 * @author lhj
 */
public class ImageSizer {
    public static void main(String[] args) throws IOException {
        imageZip(new File("C:\\Users\\p\\Desktop\\待处理\\file\\33.jpeg"),
                new File("C:\\Users\\p\\Desktop\\待处理\\file\\33.jpeg"),
                1100,1200,1f);
    }
    /**
     * 压缩图片方法
     * imageZip(new File("C:\\Users\\p\\Desktop\\待处理\\ceshi1 - 副本.jpg"),
     *    new File("C:\\Users\\p\\Desktop\\待处理\\ceshi1 - 副本1.jpg"),
     *      1100,1200,0.8f);
     * @param oldFile       将要压缩的图片
     * @param maxWidth      不能超过的最大压缩宽
     * @param maxHeight     不能超过的最大压缩长
     * @param uqualityality 压缩清晰度 <b>建议为1.0</b>
     * @param destFile     压缩图片后,添加的扩展名
     * @return
     * @throws IOException
     */

    public static void imageZip(File oldFile, File destFile, int maxWidth, int maxHeight, float uqualityality) throws IOException {
        FileOutputStream out = null;
        try {
            // 文件不存在时
            if (!oldFile.exists()){
                System.out.println("文件不存在时");
                return;
            }

            /** 对服务器上的临时文件进行处理 */
            Image srcFile = ImageIO.read(oldFile);
            int new_w = 0, new_h = 0;
            // 获取图片的实际大小 高度
            int h = (int) srcFile.getHeight(null);
            // 获取图片的实际大小 宽度
            int w = (int) srcFile.getWidth(null);
            // 为等比缩放计算输出的图片宽度及高度
            if ((((double) w) > (double) maxWidth) || (((double) h) > (double) maxHeight)) {
                // 为等比缩放计算输出的图片宽度及高度
                double rateW = ((double) srcFile.getWidth(null)) / (double) maxWidth * 1.0;
                double rateH = ((double) srcFile.getHeight(null)) / (double) maxHeight * 1.0;
                // 根据缩放比率大的进行缩放控制
                //double rate = rateW > rateH ? rateW : rateH;
                double rate;
                char zipType;
                if (rateW > rateH) {
                    rate = rateW;
                    zipType = 'W';
                } else {
                    rate = rateH;
                    zipType = 'H';
                }
                new_w = (int) (((double) srcFile.getWidth(null)) / rate);
                new_h = (int) (((double) srcFile.getHeight(null)) / rate);

                double rate2 = 0;
                if (zipType == 'W' && new_h > maxHeight) {
                    rate = (double) new_h / (double) maxHeight * 1.0;
                } else if (zipType == 'H' && new_w > maxWidth) {
                    rate = (double) new_w / (double) maxWidth * 1.0;
                }
                if (rate2 != 0) {
                    new_w = (int) (((double) new_w) / rate);
                    new_h = (int) (((double) new_h) / rate);
                    System.out.println("2次修改宽高。");
                }
            } else {
                new_w = w;
                new_h = h;
            }

            if (new_w < 1)
                throw new IllegalArgumentException("image width " + new_w + " is out of range");
            if (new_h < 1)
                throw new IllegalArgumentException("image height " + new_h + " is out of range");

            /** 宽,高设定 */
            BufferedImage tag = new BufferedImage(new_w, new_h,
                    BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(srcFile, 0, 0, new_w, new_h, null);

            out = new FileOutputStream(destFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
            /** 压缩质量 */
            jep.setQuality(uqualityality, true);
            encoder.encode(tag, jep);
            out.close();
            srcFile.flush();
        } finally {
            if (out != null) out.close();
        }
    }

}

此方法用于压缩图片,保持原有的高宽

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class CompressPicTools {
    public static final long minLength = 200 * 1024;        // 低于200KB的文件不做压缩处理

    /**
     * todo 此方法用于压缩图片,保持原有的高宽
     * @param inputDir       输入图文件夹路径
     * @param outputDir      输出图文件夹路径
     * @param inputFileName  输入图文件名
     * @param outputFileName 输出图文件名
     * @return 返回需要的文件名
     */
    public static String compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName) {
        float quality = 0.9f;        // 压缩质量      0-1的取值范围
        try {
            // 获取源文件,如果源文件小于200KB,不做压缩处理
            File file = new File(inputDir + "\\" + inputFileName);
            if (file.exists()) {
                if (minLength > file.length()) {
                    System.out.println("源文件小于200KB,不做压缩处理");
                    return inputFileName;
                } else if (4200 * 1024 < file.length()) {//大于4.2M
                    quality = 0.6f;
                } else if (3200 * 1024 < file.length()) {//大于3.2M
                    quality = 0.75f;
                } else if (2200 * 1024 < file.length()) {//大于2.2M
                    quality = 0.85f;
                }else {
                    System.out.println("为了保证图片质量不做压缩处理");
                }

                Image img = ImageIO.read(file);
                int newWidth = img.getWidth(null);
                int newHeight = img.getHeight(null);
                BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);

                tag.getGraphics().drawImage(
                        img.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH), 0, 0, null);
                FileOutputStream out = new FileOutputStream(outputDir + "\\" + outputFileName);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
                /** 压缩质量 */
                jep.setQuality(quality, true);
                encoder.encode(tag, jep);
//                encoder.encode(tag);
                out.close();
//                String dstName = outputDir +"\\"+ outputFileName;
//                String formatName = dstName.substring(dstName.lastIndexOf(".") + 1);
//                ImageIO.write(tag, /*"GIF"*/ formatName /* format desired */ , new File(dstName) /* target */ );

                // 压缩完成后,删除源文件
//                file.delete();
            } else {
                System.err.println("压缩文件不存在");
                return "压缩文件不存在";
            }

        } catch (IOException ex) {
            System.out.println(ex);
            ex.printStackTrace();
            return inputFileName;
        }
        return outputFileName;
    }

    public static List<String> getFiles(String path) {
        List<String> names = new ArrayList<>();
        File file = new File(path);
        String name = "";
        // 如果这个路径是文件夹
        if (file.isDirectory()) {
            // 获取路径下的所有文件
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                // 如果还是文件夹 递归获取里面的文件 文件夹
                if (files[i].isDirectory()) {
                    System.out.println("目录:" + files[i].getPath());
                    getFiles(files[i].getPath());
                } else {
                    System.out.println("文件:" + files[i].getName());
                    name = files[i].getName();
                    names.add(name);
                }
            }
        } else {
            System.out.println("文件:" + file.getPath());
            name = file.getName();
            names.add(name);
        }
        return names;
    }


    public static void main(String[] args) throws IOException {
//        String inputDir = "D:\\allImg\\";//输入文件路径
//        String outputDir = "D:\\allImg\\";//输出文件路径
//        String inputFileName = "20210421134619.jpg";//输入文件名
//        String outputFileName = "20210421134620.jpg";//输出文件名
//        String fileName = compressPic(inputDir, outputDir, inputFileName, outputFileName);
//        System.out.println(fileName);
        String inputDir = "C:\\Users\\p\\Desktop\\待处理\\file";//输入文件路径
        String outputDir = inputDir;//输出文件路径
        List<String> files = getFiles(inputDir);
        for (String name : files) {
            String inputFileName = name;//输入文件名
            String outputFileName = name;//输出文件名
            compressPic(inputDir, outputDir, inputFileName, outputFileName);
        }

    }
}

java更改图片格式,,更改图片大小,生成缩略图

JAVA图片处理工具类, 生成缩略图,给图片添加图片、文字水印,可设置大小、位置、透明度

修改图片分辨率、简单获取图片像素的方法
依赖

<dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.10.5</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.15</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>31.0.1-jre</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacv-platform</artifactId>
            <version>1.5.5</version>
        </dependency>
import cn.hutool.core.util.IdUtil;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.bytedeco.javacpp.Loader;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;


/**
 * 修改图片分辨率 @Version: V1.0
 * java编程简单获取图片像素的方法
 */
public class ModifyImageResolution {
    /**
     * 修改图片分辨率(效率不怎么理想)
     *
     * @param imagePath 原图片地址
     * @param outputDir 输出目录
     * @param width     宽度
     * @param height    高度
     * @return 图片地址
     * @throws Exception 异常
     */
    public static String modifyResolution(
            String imagePath, String outputDir, Integer width, Integer height) throws Exception {
        List<String> paths = Splitter.on(".").splitToList(imagePath);
        String ext = paths.get(paths.size() - 1);
        if (!Arrays.asList("jpg", "png").contains(ext)) {
            throw new Exception("format error");
        }
        String resultPath =
                Joiner.on(File.separator).join(Arrays.asList(outputDir, IdUtil.simpleUUID() + "." + ext));
        String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
        ProcessBuilder builder =
                new ProcessBuilder(
                        ffmpeg,
                        "-i",
                        imagePath,
                        "-vf",
                        MessageFormat.format("scale={0}:{1}", String.valueOf(width), String.valueOf(height)),
                        resultPath);
        builder.inheritIO().start().waitFor();
        return resultPath;
    }

    /**
     * java编程简单获取图片像素的方法
     */

    public static void getImgWithAndHeight(String tarImgPath) {
        File file = new File(tarImgPath);
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int width = bi.getWidth(); // 像素
        int height = bi.getHeight(); // 像素
        System.out.println("width=" + width + ",height=" + height + ".");
    }


    public static void main(String[] args) throws Exception {
        getImgWithAndHeight("C:\\Users\\雷神\\Desktop\\临时学习目录\\Work\\2.jpg");
        System.out.println(
                modifyResolution(
                        "C:\\Users\\雷神\\Desktop\\临时学习目录\\Work\\2.jpg", "C:\\Users\\雷神\\Desktop\\临时学习目录\\Work", 2000, 1000));
    }
}

改变图片像素DPI

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author lxd
 * @version 1.0
 * @date 2022/8/26 15:31
 */
public class DD {
    public static void main(String[] args) {
        try {
            //注:下面两个方法是一个类型的,如果想更换图片输出位置可设置FileOutputStream即可
            //方法1:
            File file = compressPictureByQality(new File("C:\\Users\\雷神\\Desktop\\临时学习目录\\Work\\1.jpg"), 0.5f, "jpg");
            handleDpi(file, 100, 100);
            //方法2:
            String path = "C:\\Users\\雷神\\Desktop\\临时学习目录\\Work\\2053767.jpg";
            File file1 = new File(path);
            handleDpi(file1, 100, 100);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 改变图片 像素
     *
     * @param file
     * @param qality 参数qality是取值0~1范围内  清晰程度  数值越小分辨率越低
     * @param imageType 图片写出类型 比如 jpg
     * @return
     * @throws IOException
     */
    public static File compressPictureByQality(File file, float qality, String imageType) throws IOException {
        BufferedImage src = null;
        FileOutputStream out = null;
        ImageWriter imgWrier;
        ImageWriteParam imgWriteParams;
//        logger.info("开始设定压缩图片参数");
        // 指定写图片的方式为 jpg
        imgWrier = ImageIO.getImageWritersByFormatName(imageType).next();
        imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(
                null);
        // 要使用压缩,必须指定压缩方式为MODE_EXPLICIT
        imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        // 这里指定压缩的程度,参数qality是取值0~1范围内,
        imgWriteParams.setCompressionQuality(qality);
        imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
        ColorModel colorModel = ImageIO.read(file).getColorModel();// ColorModel.getRGBdefault();
        imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
                colorModel, colorModel.createCompatibleSampleModel(32, 32)));
//        logger.info("结束设定压缩图片参数");
        if (!file.exists()) {
//            logger.info("Not Found Img File,文件不存在");
            throw new FileNotFoundException("Not Found Img File,文件不存在");
        } else {
//            logger.info("图片转换前大小" + file.length() + "字节");
            src = ImageIO.read(file);
            out = new FileOutputStream(file);
            imgWrier.reset();
            // 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何
            // OutputStream构造
            imgWrier.setOutput(ImageIO.createImageOutputStream(out));
            // 调用write方法,就可以向输入流写图片
            imgWrier.write(null, new IIOImage(src, null, null),
                    imgWriteParams);
            out.flush();
            out.close();
//            logger.info("图片转换后大小" + file.length() + "字节");
            return file;
        }
    }



    /**
     * 改变图片DPI
     *
     * @param file
     * @param xDensity
     * @param yDensity
     */
    public static void handleDpi(File file, int xDensity, int yDensity) {
        try {
            BufferedImage image = ImageIO.read(file);
            JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(file));
            JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
            jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
            jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);
            jpegEncodeParam.setQuality(0.75f, false);
            jpegEncodeParam.setXDensity(xDensity);
            jpegEncodeParam.setYDensity(yDensity);
            jpegEncoder.encode(image, jpegEncodeParam);
            image.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}