Word Pdf 分别在windows下和 linux下的预览功能

Word Pdf 分别在windows下和 linux下的预览功能


前言

记录windows和linux word或者pdf 在线预览功能

一、windows下 word 转化成pdf

环境准备:使用document4j 该依赖必须依赖于ms office(就是该电脑中必须有wps 或者 offic 这两款软件)。

二、使用步骤

代码如下(示例):

依赖

        <!-- documents4j word转pdf -->
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>1.1.5</version>
        </dependency>
        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-word</artifactId>
            <version>1.1.5</version>
        </dependency>

核心代码

//核心代码如下
public class PdfUtil {
    public static boolean docxToPdf(String wordFilePath, String pdfFilePath) {
        boolean result = false;

        File inputFile = new File(wordFilePath);
        File outputFile = new File(pdfFilePath);
        try {
            InputStream inputStream = new FileInputStream(inputFile);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(inputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();

            outputStream.close();
            result = true;
        } catch (Exception e) {

            e.printStackTrace();
        }

        return result;
    }
}

2.pdf 转 图片

依赖如下:

        <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/fontbox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.9</version>
        </dependency>

代码如下

public class PdfToPhoUtil {

    /**
     * 转换全部的pdf
     * @param fileAddress 文件地址
     * @param filename PDF文件名
     * @param type 图片类型
     */
    public static String pdf2png(String fileAddress,String filename,String type) {
        // 将pdf装图片 并且自定义图片得格式大小
//        File file = new File(fileAddress+"\\"+filename);
        File file = new File(fileAddress+filename.substring(1,filename.length())); //拼接pdf路径
        String fileNewName = IDUtils.genImageName();
        String fileLastName = "";
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                String imageName = IDUtils.genImageName();
//                ImageIO.write(image, type, new File(fileAddress+filename.substring(0,filename.lastIndexOf("/")+1)+"\\"+fileNewName+"_"+(i+1)+"."+type)); windows
//拼接图片 如多页pdf则生成的图片为  xxxxx_1.png xxxx_2.png
                ImageIO.write(image, type, new File(fileAddress+filename.substring(0,filename.lastIndexOf("/")+1)+fileNewName+"_"+(i+1)+"."+type));
                fileLastName = fileLastName +filename.substring(0,filename.lastIndexOf("/")+1)+fileNewName+"_"+(i+1)+"."+type+",";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileLastName.substring(0,fileLastName.length()-1);
    }


    /**
     *自由确定起始页和终止页
     * @param fileAddress 文件地址
     * @param filename pdf文件名
     * @param indexOfStart 开始页  开始转换的页码,从0开始
     * @param indexOfEnd 结束页  停止转换的页码,-1为全部
     * @param type 图片类型
     */
    public static void pdf2png(String fileAddress,String filename,int indexOfStart,int indexOfEnd,String type) {
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(fileAddress+"\\"+filename+".pdf");
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = indexOfStart; i < indexOfEnd; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                ImageIO.write(image, type, new File(fileAddress+"\\"+filename+"_"+(i+1)+"."+type));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上面需要的IDUtils 类

public class IDUtils {

    /**
     * 图片名生成
     */
    public static String genImageName() {
        //取当前时间的长整形值包含毫秒
        long millis = System.currentTimeMillis();
        //long millis = System.nanoTime();
        //加上三位随机数
        Random random = new Random();
        int end3 = random.nextInt(999);
        //如果不足三位前面补0
        String str = millis + String.format("%03d", end3);

        return str;
    }

    /**
     * 商品id生成
     */
    public static long genItemId() {
        //取当前时间的长整形值包含毫秒
        long millis = System.currentTimeMillis();
        //long millis = System.nanoTime();
        //加上两位随机数
        Random random = new Random();
        int end2 = random.nextInt(99);
        //如果不足两位前面补0
        String str = millis + String.format("%02d", end2);
        long id = new Long(str);
        return id;
    }

    /**
     * 返回一个不重复的字符串
     *
     * @return
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }

//    public static void main(String[] args) {
//        for (int i = 0; i < 100; i++)
//            System.out.println(genItemId());
//    }
}

基于linux下的pdf 转word

环境准备,这里利用 LibreOffice
参考文章如下:
该文章主要是如何安装 LibreOffice

下载LibreOffice

百度云链接
提取码: 7ni7

安装

将下载文件放入 /usr/local/etc 下

cd /usr/local/etc

解压该文件

tar -xvf LibreOffice_7.0.0_Linux_x86-64_rpm.tar.gz

解压完成后 进入解压后的文件

cd LibreOffice_7.0.0_Linux_x86-64_rpm.tar.gz/RPMS

安装

yum localinstall *.rpm

查看一下是否安装成功:

which libreoffice7.0 

如果得到 /usr/bin/libreoffice7.0 则安装成功
为了防止中文word转化乱码 需要安装字体包

yum groupinstall "fonts"

安装成功后返回到/usr/local/etc下并放入一个pdf文件
在这里插入图片描述
用该命令开始测试转换

libreoffice7.0 --headless --invisible --convert-to pdf ./1.docx --outdir ./

在这里插入图片描述
如果有以上效果 则成功

可能遇到的问题

/opt/libreoffice7.0/program/soffice.bin: error while loading shared libraries: 
libSM.so.6: cannot open shared object file: No such file or directory

需要添加依赖

yum install cairo -y
yum install cups-libs -y
yum install libSM -y

如果还有问题请度娘

java代码如下 (ps:我这里偷懒了 没有找到好用的依赖 所以我直接调的linux的命令)

java 调用 linux 指令工具类

public class ExeUtil {
    public static Boolean executeNewFlow(List<String> commands) {
        List<String> rspList = new ArrayList<String>();
        Runtime run = Runtime.getRuntime();
        try {
            Process proc = run.exec("/bin/bash", null, null);
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            for (String line : commands) {
                out.println(line);
            }
            out.println("exit");// 这个命令必须执行,否则in流不结束。
            String rspLine = "";
            while ((rspLine = in.readLine()) != null) {
                System.out.println(rspLine);
                rspList.add(rspLine);
            }
            proc.waitFor();
            in.close();
            out.close();
            proc.destroy();
            return true;
        } catch (IOException | InterruptedException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}

调用代码如下

                //拼接linux下的语句
                String wordPath ="word地址";//这个地址是word的路径需要加上自己的文件名
                String pdfSavePath = "pdf存放地址";//注意 这个存放地址 只是存放地址 没有生成的文件名
                String cmd = "libreoffice7.0 --headless --invisible --convert-to pdf "+wordPath +" --outdir "+pdfSavePath ;
                    ArrayList<String> cmdList = new ArrayList<>();
                    cmdList.add(cmd);

总结

核心代码都给出了,最恶心的就是拼接字符串了,这个就按找自己的需求来了。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值