当前位置: 首页 > 工具软件 > common.office > 使用案例 >

Spire.Office For JAVA(简单使用文档转图片)

哈宪
2023-12-01

1、jar引用:


/**
 * word文件转图片
 *
 * @author 超
 * @version 1.0
 * @date 2021-04-09 14:02
 */
public class WordToImgUtils {

    /**
     * word文件转图片
     *
     * @param fileName 文件名称
     * @param filePath 文件存放地址   (地址+文件名称+.文件后缀)
     * @return
     * @throws IOException
     */
    public static List<String> wordToImg(String fileName, String filePath) throws IOException {
        List<String> filePathList = new ArrayList<>();
        //创建Document对象
        Document doc = new Document();
        //加载Word文档
        doc.loadFromFile(filePath, FileFormat.Auto);
        BufferedImage[] image = doc.saveToImages(ImageType.Bitmap);
        //将图片数据保存为PNG格式文档
        List<BufferedImage> bufferedImages = Arrays.asList(image);
        for (int i = 0; i < bufferedImages.size(); i++) {
            File file = new File("***文件夹路径" + fileName + "(" + i + ")" + ".png");
            filePathList.add(file.getName());
            ImageIO.write(bufferedImages.get(i), "PNG", file);
        }
        doc.close();
        System.out.println(filePathList);
        return filePathList;
    }

    /**
     * pdf文件转图片
     *
     * @param fileName 文件名称
     * @param filePath 文件存放地址   (地址+文件名称+.文件后缀)
     * @return
     * @throws IOException
     */
    public static List<String> pdfToImg(String fileName, String filePath) throws IOException {
        List<String> filePathList = new ArrayList<>();
        //创建Document对象
        PdfDocument PDF = new PdfDocument();
        //加载Word文档
        PDF.loadFromFile(filePath);
        for (int i = 0; i < PDF.getPages().getCount(); i++) {
            BufferedImage image = PDF.saveAsImage(i, PdfImageType.Bitmap);
            File file = new File(FJConfig.getDownloadPath()+ fileName + "(" + i + ")" + ".png");
            filePathList.add(file.getName());
            ImageIO.write(image, "PNG", file);
        }
        PDF.close();
        System.out.println(filePathList);
        return filePathList;
    }

    /**
     * excel文件转图片
     *
     * @param fileName 文件名称
     * @param filePath 文件存放地址   (地址+文件名称+.文件后缀)
     * @return
     * @throws IOException
     */
    public static List<String> excelToImg(String fileName, String filePath) {
        List<String> filePathList = new ArrayList<>();
        Workbook excel = new Workbook();
        //加载Excel文档
        excel.loadFromFile(filePath);
        int i1 = excel.getWorksheets().getCount();
        for (int i = 0; i < i1; i++) {
            Worksheet worksheet = excel.getWorksheets().get(i);
            if (worksheet.isEmpty()){
            }
            worksheet.saveToImage("***文件夹路径" + fileName + "(" + i + ")" + ".png");
            filePathList.add(fileName + "(" + i + ")" + ".png");
        }
        return filePathList;
    }
}
 类似资料: