天天看点

利用jodconverter将office文件转为pdf文件

首先引入pom文件:

<!--        pdf工具-->
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>juh</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>jurt</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>ridl</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>unoil</artifactId>
            <version>4.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-local</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.livesense</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>1.0.5</version>
        </dependency>

        <dependency>
            <groupId>com.artofsolving</groupId>
            <artifactId>jodconverter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

           

引入pom文件后,有几个是需要手动打到jar包中的:

接下来看代码:

package org.support.project.common.util;/*
  类名称:OfficeToPdf
  功能描述:
  作者:
  创建时间:2021/4/20 10:03
*/

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.jodconverter.office.OfficeException;

import java.io.File;
import java.io.FileOutputStream;
import java.util.regex.Pattern;

/**
 * @filename: OfficeToPdf.java
 * @package: common
 * @description: OfficeToPdf
 * @author: leon
 * @date: 2019年6月14日 下午5:25:32
 * @version: V1.0
 *
 */
public class OfficeToPdfUtils {

//    public static void main(String[] args) throws OfficeException {
//        String inputFilePath = "D:\\ChinaSnow\\knowledge\\pdf转换\\项目介绍.docx";
//        //String inputFilePath = "F://officeToPdf/pptToPdf测试.pptx";
//        //String inputFilePath = "F://officeToPdf/xlsxToPdf测试.xlsx";
//        String outputFilePath = getOutputFilePath(inputFilePath);
//        //Office转换成Pdf
//        OfficeToPdf.office2pdf(inputFilePath,outputFilePath);
//        //添加水印、页眉、页脚
//        addFooterAndWater("D:\\ChinaSnow\\knowledge\\pdf转换\\项目介绍.pdf", "D:\\ChinaSnow\\knowledge\\pdf转换\\项目介绍2.pdf", "华雪物流 内部文件 严禁复印", "WordToPdf页眉", "WordToPdf页脚");
//
//    }

    /**
     * 将Office文档转换为PDF. 需要安装OpenOffice
     *
     * @param inputFilePath
     *            源文件,绝对路径. 可以是Office2003-2007全部格式的文档, 包括.doc, .docx, .xls, .xlsx, .ppt, .pptx等.
     *
     * @param outputFilePath
     *            目标文件.绝对路径.
     */
    public static void office2pdf(String inputFilePath,String outputFilePath) throws OfficeException {
        File file=new File(outputFilePath);
        file.delete();
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        String officeHome = getOfficeHome();
        //设置OpenOffice.org安装目录
        config.setOfficeHome(officeHome);
        //设置转换端口,默认为8100
        //config.setPortNumbers(8100);
        //设置任务执行超时为60分钟
        config.setTaskExecutionTimeout(1000 * 60 * 60L);
        //设置任务队列超时为24小时
        config.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
        OfficeManager officeManager = config.buildOfficeManager();
        officeManager.start();
        System.out.println("office转换服务启动成功!");
        OfficeDocumentConverter converter = new OfficeDocumentConverter( officeManager);
        File inputFile = new File(inputFilePath);
        if (inputFile.exists()) {// 找不到源文件, 则返回
            File outputFile = new File(outputFilePath);
            if (!outputFile.getParentFile().exists()) { // 假如目标路径不存在, 则新建该路径
                outputFile.getParentFile().mkdirs();
            }
            converter.convert(inputFile, outputFile);

        }
        if (null != officeManager){
            officeManager.stop();
            System.out.println("office转换服务完成。");
        }

    }
    /**
     * 根据源文件路径获取PDF文件路径
     * @param inputFilePath
     * @return
     */
    public static String getOutputFilePath(String inputFilePath) {
        String outputFilePath = "";
        String temp = inputFilePath.substring(inputFilePath.lastIndexOf(".")) ;
        outputFilePath = inputFilePath.replaceAll(temp, ".pdf");
        return outputFilePath;
    }
    /**
     * 获取OpenOffice安装目录
     * @return
     */
    public static String getOfficeHome() {
        String osName = System.getProperty("os.name");
        if (Pattern.matches("Linux.*", osName)) {
//            return "/opt/openoffice.org3";
            return "/opt/openoffice4";
        } else if (Pattern.matches("Windows.*", osName)) {
            return "D:\\chinasnow\\knowledge\\openOffice";
        } else if (Pattern.matches("Mac.*", osName)) {
            return "/Application/OpenOffice.org.app/Contents";
        }
        return null;
    }

    /**
     *	添加水印、页眉、页脚
     * @param fileName 源文件路径
     * @param savepath 目标文件路径
     * @param waterMarkName 文字水印
     * @param pageHeade 页眉
     * @param foot 页脚
     * @return
     */
    public static int addFooterAndWater(String fileName, String savepath, String waterMarkName, String pageHeade, String foot) {

        // 文档总页数
        int num = 0;
        Document document = new Document();
        try
        {
            PdfReader reader = new PdfReader(fileName);
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

            num = reader.getNumberOfPages();
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(savepath));
            document.open();
            //pdf每一页的属性
            Rectangle pageSizeWithRotation=null;

            for (int i = 0; i < num;)
            {


                PdfImportedPage page = copy.getImportedPage(reader, ++i);
                PdfCopy.PageStamp stamp = copy.createPageStamp(page);
                Font f = new Font(base);

                // 添加页脚,左侧文字,右侧页码
                ColumnText.showTextAligned(stamp.getUnderContent(),
                        Element.ALIGN_RIGHT,
                        new Phrase(String.format("第 %d 页/共 %d 页", i, num), f),
                        550f, 28, 0);
                ColumnText.showTextAligned(stamp.getUnderContent(),
                        Element.ALIGN_LEFT, new Phrase(foot, f), 50f, 28, 0);

                // 添加页眉 (文字页眉,居中)
                ColumnText.showTextAligned(stamp.getUnderContent(),
                        Element.ALIGN_CENTER, new Phrase(pageHeade, f), 150f,
                        800, 0);

                // 页眉添加logo (图片页眉,居右)
                /*Image img = Image.getInstance("template/logo.png");// 选择图片
                img.setAlignment(1);
                img.scaleAbsolute(436 / 5, 96 / 5);// 控制图片大小
                img.setAbsolutePosition(450f, 800);// 控制图片位置
                stamp.getUnderContent().addImage(img);*/

                // 添加水印--getUnderContent为在内容下方加水印
                PdfContentByte under = stamp.getUnderContent();
                under.beginText();
                under.setColorFill(BaseColor.BLACK);
                // 设置透明度 0~1的透明度
                PdfGState gs = new PdfGState();
                gs.setFillOpacity(0.1f);
                under.setGState(gs);

                // 字符越长,字体越小,设置字体
                int fontSize = getFontSize(waterMarkName);
                under.setFontAndSize(base, 54);

//                //获取每一页的高度和宽度
                pageSizeWithRotation=reader.getPageSizeWithRotation(i);
                float pageHeight1=pageSizeWithRotation.getHeight();
                float pageWidth1 = pageSizeWithRotation.getWidth();

                // 设置水印文字字体倾斜 开始
                float pageWidth = reader.getPageSize(i).getWidth();
                float pageHeight = reader.getPageSize(i).getHeight();

                // 每页三行水印

                under.showTextAligned(Element.ALIGN_CENTER, waterMarkName,
                            pageWidth1 / 2, pageHeight1 / 1, 45);// 水印文字成60度角倾斜,且页面居中展示
                under.showTextAligned(Element.ALIGN_CENTER, waterMarkName,
                        pageWidth1 / 2, pageHeight1 / 2, 45);// 水印文字成60度角倾斜,且页面居中展示
                under.showTextAligned(Element.ALIGN_MIDDLE, waterMarkName,
                        pageWidth1 / 2, 0, 45);// 水印文字成60度角倾斜,且页面居中展示



                // 字体设置结束
                under.endText();
                stamp.alterContents();
                copy.addPage(page);

            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            if (null != document)
            {
                document.close();
            }
        }
        System.out.println("pdf totalpages:" + num);
        return num;

    }

    /**
     * 根据水印文字长度计算获取字体大小
     * @param waterMarkName
     * @return
     */
    private static int getFontSize(String waterMarkName){
        int fontSize = 80;
        if(null != waterMarkName && !"".equals(waterMarkName)){
            int length = waterMarkName.length();
            if(length <=26 && length >= 18){
                fontSize = 26;
            }else if(length <18 && length >= 8){
                fontSize = 40;
            }else if(length <8 && length >= 1){
                fontSize = 80;
            }else {
                fontSize = 16;
            }
        }
        return fontSize;
    }














}