Java中world、PDF、Excel转图片

         相对来说world、pdf转图片还是比较简单的,world、pdf转html坑是最多的。不过我们这篇文章只写world、pdf转图片,后者我将会用另一篇文章就行讲述。

       原理: world、Excel转图片   就是先将内容转成pdf   在将pdf转成图片 

        话不多说 直接贴代码

       首先就是 必须要有的依赖包

 


        
            net.sf.jacob-project
            jacob
            1.14.3
        
        
            
            
            
        


        
            com.sun.pdfview
            PDFRenderer
            0.9.1
        
  • import java.io.File;
    
    public class FileManage {
        public static void listRoots() {
            // 将根目录存入File数组roots中
            File[] roots = File.listRoots();
            // 打印出根目录
            try {
                for (int i = 0; i < roots.length; i++) {
                    // 打印出根目录下的文件
                    File[] rootfile = roots[i].listFiles();
                    if(rootfile!=null){
                        for (File rf : rootfile) {
                            //  System.out.println(rf);
    //        System.out.println("------------------------------------");
                        }
                    }
                }
            } catch (RuntimeException e) {
                // TODO 自动生成 catch 块
                e.printStackTrace();
            }
        }
        // 删除指定文件或一些文件
        public void deleteFiles(String path, String inname, String inextension) {
            boolean status = true;
            FileManagerFilter fmf = new FileManagerFilter(inname, inextension);
            File file = new File(path);
            File[] filelist = file.listFiles(fmf);
            // System.out.println(filelist.length); 此语句用于测试
            if (filelist.length != 0) {
                for (File fl : filelist) {
                    // boolean delfil = fl.delete();
                    System.out.println(fl + (fl.delete() ? " 成功" : " 没有成功")
                            + "被删除!");
                }
            } else {
                System.out.println("根据您所给的条件,没有找到要删除的文件!");
            }
        }
        // 删除所有目录下所有文件,但是目录没有删除,哈哈其实效果一样
        public void deletAllFile() {
            FileManage fmqq53227117 = new FileManage();
            File[] roots = File.listRoots();
            for (int i = 0; i < roots.length; i++) {
                if (roots[i].isDirectory()) {
                    fmqq53227117.deleteFiles(roots[i].toString(), "*", "*");
                }
            }
        }
    
        //d:\ceshi.pdf
        public  void deleteFile(String filePath) {
            FileManage.listRoots();
            FileManage fm = new FileManage();
            // 此句表示删除G:\下的所有以"Fi"开头的,以"java"结尾的文件
            // 删除指定文件,请慎用!!!本机环境下有G:\盘
            File file = new File(filePath);
    
            //获取文件名 带后缀
            String filename = file.getName();
    
            //获取文件后缀
            String suffix =filename.substring(filename.indexOf(".")+1);
    
            //获取文件名  不带后缀
            String name = filename.substring(0, filename.indexOf("."));
    
    
            System.out.println(name+suffix);
            fm.deleteFiles("D:\\", name, suffix);
            //删除所有目录下文件, 请慎用此方法!!!!!!!!!!!!!!!!!
            //fm.deletAllFile();
        }
    
        public static void main(String args[]) {
            FileManage.listRoots();
            FileManage fm = new FileManage();
            // 此句表示删除D:\下的ceshi文件,以"pdf"结尾的文件
            fm.deleteFiles("D:\\", "ceshi", "pdf");
    
        }
    }

//用到的工具类



import java.io.File;
import java.io.FilenameFilter;

public class FileManagerFilter implements FilenameFilter {
    private String name;
    private String extension;
    public FileManagerFilter(String name, String extension) {
        this.name = name;
        this.extension = extension;
    }
    public boolean accept(File dir, String filename) {
        boolean fileOK = true;
        String str;
        char c;

        if (name == "*"&&extension=="*") {
            return fileOK = true;
        }

        //遍历filename字符串
        for(int i=0;i

下面的这段代码 是我在项目实战中用到的  仅供参考  强烈建议大家不要盲目的粘贴复制 ,这些代码 是不全的  况且文件定义的规则也是不一样的 只是让大家看看 我是怎么在项目中用这个封装好的工具类。

   大家可以先启动一下 上面的 main方法 慢慢的找一下 规则 理解一下 

//源文件全路径
            String docfile = path;

            //获取文件全名  带后缀
            String filename = null;

            //文件名  不带后缀
            String name = null;

            File file = new File(docfile);

            //获取文件名 带后缀
            filename = file.getName();
            //获取文件名  不带后缀
            name = filename.substring(0, filename.indexOf("."));
            //        System.out.println(name+"name");
            //用于存放图片的目录
            SimpleDateFormat formatter = new SimpleDateFormat("/YYYYMM/YYYYMMDD/hhmmss-");
            String dateString = formatter.format(new Date());
            String paths = dateString + UUID.randomUUID().toString().replaceAll("-", ""); // 相对路径
            String spath = paths + name;
            String outFile = getUploadPath()+spath;
            //如果目录不存在,就创建新的目录
            if (!new File(outFile).isDirectory()) {
                new File(outFile).mkdirs();
            }
            //存放PDF的路径和PDF的文件名
            String toFile = getUploadPath()+ paths + name;
            //实例化对象WorldToJPG
            FormatToJPG wj = new FormatToJPG();
            //将world文件转换为PDF文件   并返回PDF文件的全路径   17 表示文件格式为PDF
            String filePath = wj.wordToPDF(docfile, toFile, 17);
            try {
                //将PDF文件转换为JPG文件
                pathList = wj.pdfToJPG(filePath, outFile);
                //删除pdf文件
//                new FileManage().deleteFile(filePath);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

到这里第一种方法已经结束了  

ps:大家可以启动一下 main方法测试一下 在线上调用工具类的时候 千万不忘记把 System级别的打印给删除掉

上述是测试代码。是不是非常简单 也不需要什么依赖包

     

下面我说另外一种转图片的方法  是用的 oppenOffice

 

包依赖:这个包需要的话 可以去csdn下载 ,也可以加群 去文件里面自行下载

              QQ群号:         808249297

             下载链接:https://download.csdn.net/download/weixin_41036106/10711571

   


import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import java.io.File;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

public class OfficeToPDF {

    public void docToPdf(File inputFile, File outputFile){
        //启动服务
        String OpenOffice_HOME = "C:/Program Files (x86)/OpenOffice 4";// 这里是OpenOffice的安装目录
        if(OpenOffice_HOME.charAt(OpenOffice_HOME.length()-1)!='/'){
            OpenOffice_HOME+="/";
        }
        Process pro = null;
        OpenOfficeConnection connection = null;
        // 启动OpenOffice的服务
        String command = OpenOffice_HOME + "program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
        // connect to an OpenOffice.org instance running on port 8100

        try{
            pro = Runtime.getRuntime().exec(command);
            connection = new SocketOpenOfficeConnection(8100);
            connection.connect();

            // convert
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            System.out.println(inputFile+"="+outputFile);

            converter.convert(inputFile, outputFile);
        }catch(Exception ex){
            System.out.println("程序出错了");
            ex.printStackTrace();

        }finally{
            // close the connection
            if(connection!=null){
                connection.disconnect();
                connection = null;
            }
            pro.destroy();
        }
        System.out.println("生成"+outputFile.getName());
    }


    //生产pdf线程
    static class TestThread extends java.lang.Thread{
        private File inputFile;
        private File outputFile;

        public void run(){
            OfficeToPDF t = new OfficeToPDF();
            t.docToPdf(inputFile, outputFile);
            System.out.println(outputFile.getName()+"文件已生成");
        }

        public void setInputFile(File inputFile) {
            this.inputFile = inputFile;
        }

        public void setOutputFile(File outputFile) {
            this.outputFile = outputFile;
        }
    }


}

     根据自己的文件生成规则  建立输入 输出路径  (跟上述一样 也是 自己在项目中的代码  请忽粘贴,仅供参考)

SimpleDateFormat formatter = new SimpleDateFormat("/YYYYMM/YYYYMMDD/hhmmss-");
            String dateString = formatter.format(new Date());
            String paths = dateString + UUID.randomUUID().toString().replaceAll("-", ""); // 相对路径
            String spath = paths + attachment.getAttachName();
            String outFile = getUploadPath()+spath+".pdf";
            OfficeToPDF wordToPDF = new OfficeToPDF();
            wordToPDF.docToPdf(new File(path), new File(outFile));
            //实例化对象WorldToJPG
            FormatToJPG wj = new FormatToJPG();
            //将PDF文件转换为JPG文件
            String pathJPG =getUploadPath()+ paths+"JPG" + attachment.getAttachName();
            try {
                pathList = wj.pdfToJPG(outFile, pathJPG);
            } catch (IOException e) {
                e.printStackTrace();
            }

大家可能 很男理解这几段代码  我解释一下  我之所以 用完 oppenOffice 这个工具类  在用方法一 讲的 那个工具类 原因就是 我这边 是将excel 转pdf   现在就是在把生成的pdf用第一种方法 转成 图片

    下片文章我将为大家讲述一下  world、PDF、excel如何生成 html

  欢迎大家加java交流群,有问题我们可以一同探讨。

       群号:808249297

       二维码:

你可能感兴趣的:(java)