基于LibreOffice转换文档

LibreOffice开源免费,支持Windows、Linux、MacOS平台,需要先在服务器上安装LibreOffice软件,如果转换结果出现乱码,则还需要在服务器上安装字体。
安装过程,略
本文重点在于java代码的封装,其中使用过程基于SpringBoot
不需要手动启动LibreOffice软件,一切由框架掌握,转换效果不输其它框架

POM依赖

<dependency>
    <groupId>org.jodconverter</groupId>
    <artifactId>jodconverter-local</artifactId>
    <version>4.4.2</version>
</dependency>
<dependency>
    <groupId>org.libreoffice</groupId>
    <artifactId>ridl</artifactId>
    <version>7.3.4</version>
</dependency>
<dependency>
    <groupId>org.jodconverter</groupId>
    <artifactId>jodconverter-spring-boot-starter</artifactId>
    <version>4.4.2</version>
</dependency>
<!-- 使用POI封装对excel的打印设置支持 -->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>4.4.0</version>
</dependency>

封装工具类 不依赖SpringBoot

工具类务必在同一级包目录下

MyOfficeUtils

package com.xxx.office.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public final class MyOfficeUtils {
	
	private MyOfficeUtils () {}
	
	/**
	 * 获取文档类型
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static FileMagic getFileMagic(File file) throws IOException {
		try (
				FileInputStream inp = new FileInputStream(file);
				) {
			return getFileMagic(inp);
		}
	}

	/**
	 * 获取文档类型
	 * @param inp
	 * @return
	 * @throws IOException
	 */
	public static FileMagic getFileMagic(InputStream inp) throws IOException {
		InputStream is = FileMagic.prepareToCheckMagic(inp);
        FileMagic fm = FileMagic.valueOf(is);
        return fm;
	}
	
	/**
	 * 判断是否excel03版本
	 * @param file
	 * @return
	 */
	public static boolean isExcel03(File file) {
		try {
			boolean ole2 = FileMagic.OLE2 == getFileMagic(file);
			if (!ole2) {
				return false;
			}
			try (
					Workbook workbook = WorkbookFactory.create(file);
					) {
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * 判断是否excel07版本
	 * @param file
	 * @return
	 */
	public static boolean isExcel07(File file) {
		try {
			boolean ole2 = FileMagic.OOXML == getFileMagic(file);
			if (!ole2) {
				return false;
			}
			try (
					Workbook workbook = WorkbookFactory.create(file);
					) {
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * excel默认打印配置
	 * @param workbook
	 */
	public static void setDefaultExcelPrintScale (Workbook workbook) {
		int numberOfSheets = workbook.getNumberOfSheets();
		for (int i = 0; i < numberOfSheets; i++) {
			workbook.removePrintArea(i);
			setSheetPrintScale(workbook.getSheetAt(i), null);
		}
	}
	
	static void setExcelPrintScale (Workbook workbook, OfficeInputExcelPrintSetup inputExcelPrintSetup) {
		int numberOfSheets = workbook.getNumberOfSheets();
		for (int i = 0; i < numberOfSheets; i++) {
			workbook.removePrintArea(i);
			setSheetPrintScale(workbook.getSheetAt(i), inputExcelPrintSetup);
		}
	}

	private static void setSheetPrintScale(Sheet sheet, OfficeInputExcelPrintSetup inputExcelPrintSetup) {
		PrintSetup setup = sheet.getPrintSetup();
		if (inputExcelPrintSetup == null) {
			setup.setLandscape(true);
			setup.setFitHeight((short) 0);
			setup.setFitWidth((short) 1);
			setup.setPaperSize(PrintSetup.A4_PAPERSIZE);
			sheet.setFitToPage(true);
			sheet.setPrintRowAndColumnHeadings(false);
			sheet.setHorizontallyCenter(true);
			sheet.setVerticallyCenter(false);
		} else {
			setup.setLandscape(inputExcelPrintSetup.isLandscape());
			setup.setFitHeight(inputExcelPrintSetup.getFitHeight());
			setup.setFitWidth(inputExcelPrintSetup.getFitWidth());
			setup.setPaperSize(inputExcelPrintSetup.getPaperSize());
			sheet.setFitToPage(inputExcelPrintSetup.isFitToPage());
			sheet.setPrintRowAndColumnHeadings(inputExcelPrintSetup.isPrintRowAndColumnHeadings());
			sheet.setHorizontallyCenter(inputExcelPrintSetup.isHorizontallyCenter());
			sheet.setVerticallyCenter(inputExcelPrintSetup.isVerticallyCenter());
		}
		sheet.setMargin(Sheet.TopMargin, 0.75);
		sheet.setMargin(Sheet.RightMargin, 0.70);
		sheet.setMargin(Sheet.BottomMargin, 0.75);
		sheet.setMargin(Sheet.LeftMargin, 0.70);
		sheet.setMargin(Sheet.HeaderMargin, 0.30);
		sheet.setMargin(Sheet.FooterMargin, 0.30);
	}
}

OfficeConvertHelper

核心转换类,也是工具类入口
POI文档注释说明,读取输入流比读取文件占用更多的内存,所以先将输入流保存到临时文件再读取,最后将临时文件删除。

package com.xxx.office.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.util.IOUtils;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.document.DocumentFormat;
import org.jodconverter.core.job.ConversionJobWithOptionalSourceFormatUnspecified;
import org.jodconverter.core.job.ConversionJobWithSourceSpecified;
import org.jodconverter.core.office.OfficeException;

public final class OfficeConvertHelper {
	
	private static final String TMP_DIRECTORY = System.getProperty("java.io.tmpdir");
	
	private OfficeConvertHelper () {}
	
	public static OfficeConverterBox converter(DocumentConverter documentConverter) {
		return new OfficeConverterBox(documentConverter);
	}
	
	/**
	 * 转换
	 * @param outputHelper
	 * @throws IOException
	 * @throws OfficeException
	 */
	static void execute(OfficeOutputBox outputHelper) throws IOException, OfficeException {
		OfficeInputBox officeInputBox = outputHelper.getOfficeInputBox();
		OfficeConverterBox officeConverterBox = officeInputBox.getOfficeConverterBox();
		
		DocumentConverter documentConverter = officeConverterBox.getDocumentConverter();
		
		File inpFile = officeInputBox.getInpFile();
		InputStream inp = officeInputBox.getInp();
		boolean inpCloseStream = officeInputBox.isCloseStream();
		DocumentFormat inpDocumentFormat = officeInputBox.getInpDocumentFormat();
		OfficeInputExcelPrintSetup inputExcelPrintSetup = officeInputBox.getOfficeInputExcelPrintSetup();
		
		File outFile = outputHelper.getOutFile();
		OutputStream outp = outputHelper.getOutp();
		boolean outpCloseStream = outputHelper.isCloseStream();
		DocumentFormat outDocumentFormat = outputHelper.getOutDocumentFormat();
		
		if (inpFile != null) {
			DocumentFormat isDocFormat = inpDocumentFormat;
			if (MyOfficeUtils.isExcel03(inpFile)) {
				isDocFormat = DefaultDocumentFormatRegistry.XLS;
			} else if (MyOfficeUtils.isExcel07(inpFile)) {
				isDocFormat = DefaultDocumentFormatRegistry.XLSX;
			}
			if (DefaultDocumentFormatRegistry.XLS == isDocFormat || DefaultDocumentFormatRegistry.XLSX == isDocFormat) {
				File file = new File(TMP_DIRECTORY, "xls" + UUID.randomUUID().toString().replace("-", "") + ".tmp");
				try {
					try (
							OutputStream tmpOs = toBufferedOutputStream(new FileOutputStream(file));
							Workbook workbook = WorkbookFactory.create(inpFile);
							) {
						MyOfficeUtils.setExcelPrintScale(workbook, inputExcelPrintSetup);
						workbook.write(tmpOs);
					}
					ConversionJobWithSourceSpecified as = documentConverter.convert(file).as(isDocFormat);
					if (outFile != null) {
						if (outDocumentFormat != null) {
							as.to(outFile).as(outDocumentFormat).execute();
						} else {
							as.to(outFile).execute();
						}
					} else {
						OutputStream bufferedOs = toBufferedOutputStream(outp);
						as.to(bufferedOs, outpCloseStream).as(outDocumentFormat).execute();
					}
				} finally {
					try {
						if (file.exists()) {
							file.delete();
						}
					} catch (Exception e) {
					}
				}
			} else {
				if (inpDocumentFormat != null) {
					ConversionJobWithSourceSpecified as = documentConverter.convert(inpFile).as(inpDocumentFormat);
					if (outFile != null) {
						if (outDocumentFormat != null) {
							as.to(outFile).as(outDocumentFormat).execute();
						} else {
							as.to(outFile).execute();
						}
					} else {
						OutputStream bufferedOs = toBufferedOutputStream(outp);
						as.to(bufferedOs, outpCloseStream).as(outDocumentFormat).execute();
					}
				} else {
					ConversionJobWithOptionalSourceFormatUnspecified as = documentConverter.convert(inpFile);
					if (outFile != null) {
						if (outDocumentFormat != null) {
							as.to(outFile).as(outDocumentFormat).execute();
						} else {
							as.to(outFile).execute();
						}
					} else {
						OutputStream bufferedOs = toBufferedOutputStream(outp);
						as.to(bufferedOs, outpCloseStream).as(outDocumentFormat).execute();
					}
				}
			}
		} else {
			File unknownFile = new File(TMP_DIRECTORY, "unknown" + UUID.randomUUID().toString().replace("-", "") + ".tmp");
			try {
				InputStream bufferedIs = null;
				try {
					bufferedIs = FileMagic.prepareToCheckMagic(inp);
					IOUtils.copy(bufferedIs, unknownFile);
				} finally {
					if (inpCloseStream) {
						if (bufferedIs != null) {
							try {
								bufferedIs.close();
								bufferedIs = null;
							} catch (Exception e) {
							}
						} else {
							try {
								inp.close();
							} catch (Exception e) {
							}
						}
					} else {
						if (bufferedIs != null) {
							try {
								bufferedIs.reset();
							} catch (Exception e) {
							}
						}
					}
				}
				
				DocumentFormat isDocFormat = inpDocumentFormat;
				if (MyOfficeUtils.isExcel03(unknownFile)) {
					isDocFormat = DefaultDocumentFormatRegistry.XLS;
				} else if (MyOfficeUtils.isExcel07(unknownFile)) {
					isDocFormat = DefaultDocumentFormatRegistry.XLSX;
				}
				if (DefaultDocumentFormatRegistry.XLS == isDocFormat || DefaultDocumentFormatRegistry.XLSX == isDocFormat) {
					File file = new File(TMP_DIRECTORY, "xls" + UUID.randomUUID().toString().replace("-", "") + ".tmp");
					try {
						try (
								OutputStream tmpOs = toBufferedOutputStream(new FileOutputStream(file));
								Workbook workbook = WorkbookFactory.create(unknownFile);
								) {
							MyOfficeUtils.setExcelPrintScale(workbook, inputExcelPrintSetup);
							workbook.write(tmpOs);
						}
						ConversionJobWithSourceSpecified as = documentConverter.convert(file).as(isDocFormat);
						if (outFile != null) {
							if (outDocumentFormat != null) {
								as.to(outFile).as(outDocumentFormat).execute();
							} else {
								as.to(outFile).execute();
							}
						} else {
							OutputStream bufferedOs = toBufferedOutputStream(outp);
							as.to(bufferedOs, outpCloseStream).as(outDocumentFormat).execute();
						}
					} finally {
						try {
							if (file.exists()) {
								file.delete();
							}
						} catch (Exception e) {
						}
					}
				} else {
					if (inpDocumentFormat != null) {
						ConversionJobWithSourceSpecified as = documentConverter.convert(unknownFile).as(inpDocumentFormat);
						if (outFile != null) {
							if (outDocumentFormat != null) {
								as.to(outFile).as(outDocumentFormat).execute();
							} else {
								as.to(outFile).execute();
							}
						} else {
							OutputStream bufferedOs = toBufferedOutputStream(outp);
							as.to(bufferedOs, outpCloseStream).as(outDocumentFormat).execute();
						}
					} else {
						ConversionJobWithOptionalSourceFormatUnspecified as = documentConverter.convert(unknownFile);
						if (outFile != null) {
							if (outDocumentFormat != null) {
								as.to(outFile).as(outDocumentFormat).execute();
							} else {
								as.to(outFile).execute();
							}
						} else {
							OutputStream bufferedOs = toBufferedOutputStream(outp);
							as.to(bufferedOs, outpCloseStream).as(outDocumentFormat).execute();
						}
					}
				}
			} finally {
				try {
					if (unknownFile.exists()) {
						unknownFile.delete();
					}
				} catch (Exception e) {
				}
			}
			
		}
	}
	
	private static OutputStream toBufferedOutputStream(OutputStream stream) {
        if (stream instanceof BufferedOutputStream) {
            return stream;
        }
        return new BufferedOutputStream(stream);
    }
}

OfficeConverterBox

package com.xxx.office.util;

import java.io.File;
import java.io.InputStream;

import org.jodconverter.core.DocumentConverter;

public class OfficeConverterBox {

	private DocumentConverter documentConverter;
	
	OfficeConverterBox(DocumentConverter documentConverter) {
		this.documentConverter = documentConverter;
	}
	
	public OfficeInputBox from(File inpFile) {
		return new OfficeInputBox(this, inpFile);
	}
	
	public OfficeInputBox from(InputStream inp) {
		return new OfficeInputBox(this, inp, true);
	}
	
	public OfficeInputBox from(InputStream inp, boolean closeStream) {
		return new OfficeInputBox(this, inp, closeStream);
	}

	DocumentConverter getDocumentConverter() {
		return documentConverter;
	}
}

OfficeInputBox

LibreOffice可以自动识别输入文档类型,所以输入文档类型为选填项
java的输入流一般只能读取一次,但如果参数为输入流且不自动关闭(即使用officeConverterBox.from(InputStream inp, false)),则转换后的输入流仍然可以再次读取

package com.xxx.office.util;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.document.DocumentFormat;

public class OfficeInputBox {
	
	private OfficeConverterBox officeConverterBox;
	
	private File inpFile;
	
	private InputStream inp;
	
	private boolean closeStream = true;
	
	private DocumentFormat inpDocumentFormat;
	
	private OfficeInputExcelPrintSetup officeInputExcelPrintSetup;

	OfficeInputBox(OfficeConverterBox officeConverterBox, File inpFile) {
		this.officeConverterBox = officeConverterBox;
		this.inpFile = inpFile;
	}

	/**
	 * 
	 * @param officeConverterBox
	 * @param inp
	 * @param closeStream 是否关闭输入流,默认true
	 */
	OfficeInputBox(OfficeConverterBox officeConverterBox, InputStream inp, boolean closeStream) {
		this.officeConverterBox = officeConverterBox;
		this.inp = inp;
		this.closeStream = closeStream;
	}
	
	/**
	 * 
	 * @param documentFormat @see {org.jodconverter.core.document.DefaultDocumentFormatRegistry}
	 * @return
	 */
	public OfficeInputBox as(DocumentFormat documentFormat) {
		this.inpDocumentFormat = documentFormat;
		return this;
	}

	/**
	 * 
	 * @param extension @see {org.jodconverter.core.document.DefaultDocumentFormatRegistry}
	 * @return
	 */
	public OfficeInputBox asExtension(String extension) {
		this.inpDocumentFormat = DefaultDocumentFormatRegistry.getFormatByExtension(extension);
		return this;
	}
	
	/**
	 * 
	 * @param mediaType @see {org.jodconverter.core.document.DefaultDocumentFormatRegistry}
	 * @return
	 */
	public OfficeInputBox asMediaType(String mediaType) {
		this.inpDocumentFormat = DefaultDocumentFormatRegistry.getFormatByMediaType(mediaType);
		return this;
	}
	
	public OfficeInputExcelPrintSetup excel() {
		if (this.officeInputExcelPrintSetup == null) {
			this.officeInputExcelPrintSetup = new OfficeInputExcelPrintSetup(this);
		}
		return this.officeInputExcelPrintSetup;
	}
	
	public OfficeOutputBox to(File outFile) {
		return new OfficeOutputBox(this, outFile);
	}
	
	public OfficeOutputStreamBox to(OutputStream outp) {
		return new OfficeOutputStreamBox(this, outp, true);
	}
	
	public OfficeOutputStreamBox to(OutputStream outp, boolean closeStream) {
		return new OfficeOutputStreamBox(this, outp, closeStream);
	}

	OfficeConverterBox getOfficeConverterBox() {
		return officeConverterBox;
	}

	File getInpFile() {
		return inpFile;
	}

	InputStream getInp() {
		return inp;
	}

	boolean isCloseStream() {
		return closeStream;
	}

	DocumentFormat getInpDocumentFormat() {
		return inpDocumentFormat;
	}

	OfficeInputExcelPrintSetup getOfficeInputExcelPrintSetup() {
		return this.officeInputExcelPrintSetup;
	}
	
}

OfficeInputExcelPrintSetup

excel打印配置类,如果不配置,则使用工具类封装的默认配置转换excel文档
工具类自动识别excel文件,而不依赖输入文件扩展名或指定的文档类型,如果输入文件或输入流是excel文档,则工具类自动设置excel的打印格式,否则excel打印配置不起作用。

package com.xxx.office.util;

import org.apache.poi.ss.usermodel.PrintSetup;

public class OfficeInputExcelPrintSetup {
	
	private OfficeInputBox officeInputBox;
	
	/**
	 * 默认A4纸
	 */
	private short paperSize = PrintSetup.A4_PAPERSIZE;
	/**
	 * 默认横版
	 */
	private boolean landscape = true;
	/**
	 * 默认水平内容在一页上
	 */
	private short fitWidth = 1;
	/**
	 * 默认垂直内容分页
	 */
	private short fitHeight = 0;
	/**
	 * 默认铺满纸张
	 */
	private boolean fitToPage = true;
	/**
	 * 默认内容水平居中
	 */
	private boolean horizontallyCenter = true;
	/**
	 * 默认内容垂直与顶部对齐
	 */
	private boolean verticallyCenter = false;
	/**
	 * 默认不打印excel的行号和列号
	 */
	private boolean printRowAndColumnHeadings = false;

	OfficeInputExcelPrintSetup(OfficeInputBox officeInputBox) {
		this.officeInputBox = officeInputBox;
	}

	public OfficeInputBox end() {
		return this.officeInputBox;
	}
	
	/**
	 * 设置打印纸张大小
	 * @param size @see {org.apache.poi.ss.usermodel.PrintSetup}
	 * @return
	 */
	public OfficeInputExcelPrintSetup setPaperSize(short paperSize) {
		this.paperSize = paperSize;
		return this;
	}
	
	/**
	 * 设置打印方向,默认true
	 * @param landscape 是否横版打印
	 * @return
	 */
	public OfficeInputExcelPrintSetup setLandscape(boolean landscape) {
		this.landscape = landscape;
		return this;
	}
	
	/**
	 * 设置打印宽度
	 * @param fitWidth 是否打印宽度方向的内容在一页上
	 * @return
	 */
	public OfficeInputExcelPrintSetup setFitWidth(boolean fitWidth) {
		if (fitWidth) {
			this.fitWidth = 1;
		} else {
			this.fitWidth = 0;
		}
		return this;
	}
	
	/**
	 * 设置打印高度
	 * @param fitHeight 是否打印高度方向的内容在一页上
	 * @return
	 */
	public OfficeInputExcelPrintSetup setFitHeight(boolean fitHeight) {
		if (fitHeight) {
			this.fitHeight = 1;
		} else {
			this.fitHeight = 0;
		}
		return this;
	}
	
	/**
	 * 设置是否铺满
	 * @param fitToPage 内容是否铺满页面
	 * @return
	 */
	public OfficeInputExcelPrintSetup setFitToPage(boolean fitToPage) {
		this.fitToPage = fitToPage;
		return this;
	}
	
	/**
	 * 设置水平居中
	 * @param horizontallyCenter 内容是否水平居中
	 * @return
	 */
	public OfficeInputExcelPrintSetup setHorizontallyCenter(boolean horizontallyCenter) {
		this.horizontallyCenter = horizontallyCenter;
		return this;
	}
	
	/**
	 * 设置垂直居中
	 * @param verticallyCenter 内容是否垂直居中
	 * @return
	 */
	public OfficeInputExcelPrintSetup setVerticallyCenter(boolean verticallyCenter) {
		this.verticallyCenter = verticallyCenter;
		return this;
	}
	
	/**
	 * 设置是否打印行号和列号,默认false
	 * @param show
	 * @return
	 */
	public OfficeInputExcelPrintSetup setPrintRowAndColumnHeadings(boolean show) {
		this.printRowAndColumnHeadings = show;
		return this;
	}

	short getPaperSize() {
		return paperSize;
	}

	boolean isLandscape() {
		return landscape;
	}

	short getFitWidth() {
		return fitWidth;
	}

	short getFitHeight() {
		return fitHeight;
	}

	boolean isFitToPage() {
		return fitToPage;
	}

	boolean isHorizontallyCenter() {
		return horizontallyCenter;
	}

	boolean isVerticallyCenter() {
		return verticallyCenter;
	}

	boolean isPrintRowAndColumnHeadings() {
		return printRowAndColumnHeadings;
	}
	
}

OfficeOutputBox

LibreOffice可以根据输出文件的扩展名识别目标文档类型,但不能根据输出流识别目标目标文档类型,所以如果输出目标是文件,则可以不显式指定输出文档类型,如果输出目标是流,则必须指定输出文档类型。

package com.xxx.office.util;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.document.DocumentFormat;
import org.jodconverter.core.office.OfficeException;

public class OfficeOutputBox {
	
	private OfficeInputBox officeInputBox;
	
	private File outFile;
	
	private OutputStream outp;
	
	private boolean closeStream = true;
	
	private DocumentFormat outDocumentFormat;

	OfficeOutputBox(OfficeInputBox officeInputBox, File outFile) {
		this.officeInputBox = officeInputBox;
		this.outFile = outFile;
	}

	OfficeOutputBox(OfficeOutputStreamBox officeOutputStreamBox) {
		this.officeInputBox = officeOutputStreamBox.getOfficeInputBox();
		this.outp = officeOutputStreamBox.getOutp();
		this.closeStream = officeOutputStreamBox.isCloseStream();
	}
	
	/**
	 * 
	 * @param documentFormat @see {org.jodconverter.core.document.DefaultDocumentFormatRegistry}
	 * @return
	 */
	public OfficeOutputBox as(DocumentFormat documentFormat) {
		this.outDocumentFormat = documentFormat;
		return this;
	}

	/**
	 * 
	 * @param extension @see {org.jodconverter.core.document.DefaultDocumentFormatRegistry}
	 * @return
	 */
	public OfficeOutputBox asExtension(String extension) {
		this.outDocumentFormat = DefaultDocumentFormatRegistry.getFormatByExtension(extension);
		return this;
	}
	
	/**
	 * 
	 * @param mediaType @see {org.jodconverter.core.document.DefaultDocumentFormatRegistry}
	 * @return
	 */
	public OfficeOutputBox asMediaType(String mediaType) {
		this.outDocumentFormat = DefaultDocumentFormatRegistry.getFormatByMediaType(mediaType);
		return this;
	}
	
	public void execute() throws IOException, OfficeException {
		OfficeConvertHelper.execute(this);
	}

	public OfficeInputBox getOfficeInputBox() {
		return officeInputBox;
	}

	public File getOutFile() {
		return outFile;
	}

	public OutputStream getOutp() {
		return outp;
	}

	public boolean isCloseStream() {
		return closeStream;
	}

	public DocumentFormat getOutDocumentFormat() {
		return outDocumentFormat;
	}
	
}

OfficeOutputStreamBox

专为输出目标是流的时候准备的类

package com.xxx.office.util;

import java.io.OutputStream;

import org.jodconverter.core.document.DocumentFormat;

public class OfficeOutputStreamBox {
	
	private OfficeInputBox officeInputBox;
	
	private OutputStream outp;
	
	private boolean closeStream = true;

	OfficeOutputStreamBox(OfficeInputBox officeInputBox, OutputStream outp, boolean closeStream) {
		this.officeInputBox = officeInputBox;
		this.outp = outp;
		this.closeStream = closeStream;
	}

	
	/**
	 * 
	 * @param documentFormat @see {org.jodconverter.core.document.DefaultDocumentFormatRegistry}
	 * @return
	 */
	public OfficeOutputBox as(DocumentFormat documentFormat) {
		OfficeOutputBox officeOutputBox = new OfficeOutputBox(this);
		officeOutputBox.as(documentFormat);
		return officeOutputBox;
	}

	/**
	 * 
	 * @param extension @see {org.jodconverter.core.document.DefaultDocumentFormatRegistry}
	 * @return
	 */
	public OfficeOutputBox asExtension(String extension) {
		OfficeOutputBox officeOutputBox = new OfficeOutputBox(this);
		officeOutputBox.asExtension(extension);
		return officeOutputBox;
	}
	
	/**
	 * 
	 * @param mediaType @see {org.jodconverter.core.document.DefaultDocumentFormatRegistry}
	 * @return
	 */
	public OfficeOutputBox asMediaType(String mediaType) {
		OfficeOutputBox officeOutputBox = new OfficeOutputBox(this);
		officeOutputBox.asMediaType(mediaType);
		return officeOutputBox;
	}


	OfficeInputBox getOfficeInputBox() {
		return officeInputBox;
	}


	OutputStream getOutp() {
		return outp;
	}


	boolean isCloseStream() {
		return closeStream;
	}
	
}

使用

application.yml

jodconverter:
  # 使用本机作为转换服务器,如果使用其它主机作为转换服务器,则需要配置remote,
  # 请参考 org.jodconverter.boot.autoconfigure.JodConverterRemoteProperties
  local:
    enabled: true
    # 为了避免不必要的兼容问题,需要配置本机的LibreOffice安装目录
    office-home: D:/Program Files (x86)/LibreOffice
    # 配置LibreOffice的服务端口,以逗号分隔,每个端口为一个独立的进程
    port-numbers: 2002,2003,2004
    # 配置最大的任务队列
    max-tasks-per-process: 100

示例

package com.xxx.office.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.office.OfficeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.szh.mybatistest.office.util.OfficeConvertHelper;

@Service
public class OfficeServiceImpl {

	@Autowired
	private DocumentConverter documentConverter;
	
	public void test() throws OfficeException, IOException {
		
		OfficeConvertHelper.converter(documentConverter)
				.from(new File("D:/ceshi", "test123.xlsm"))
				.to(new File("D:/ceshi", "xlsfile2pdffile.pdf"))
				.execute();
		
		OfficeConvertHelper.converter(documentConverter)
				.from(new File("D:/ceshi", "test123.xlsm"))
				.asExtension("docx")
				.to(new FileOutputStream(new File("D:/ceshi", "xlsfile2pdfstream1.pdf")))
				.as(DefaultDocumentFormatRegistry.PDF)
				.execute();
		
		OfficeConvertHelper.converter(documentConverter)
				.from(new File("D:/ceshi", "test123.xlsm"))
				.asExtension("docx")
				.excel()
				.setLandscape(false)
				.end()
				.to(new FileOutputStream(new File("D:/ceshi", "xlsfile2pdfstream2.pdf")))
				.as(DefaultDocumentFormatRegistry.PDF)
				.execute();
		
		FileInputStream inputStream1 = new FileInputStream(new File("D:/ceshi", "test123.xlsm"));
		OfficeConvertHelper.converter(documentConverter)
				.from(inputStream1, false)
				.to(new File("D:/ceshi", "xlsstream2pdffile.pdf"))
				.execute();
		inputStream1.read();
		inputStream1.close();
		
		OfficeConvertHelper.converter(documentConverter)
				.from(new File("D:/ceshi", "test123.xlsm"))
				.asExtension("docx")
				.to(new FileOutputStream(new File("D:/ceshi", "xlsstream2pdfstream1.pdf")))
				.as(DefaultDocumentFormatRegistry.PDF)
				.execute();
		
		OfficeConvertHelper.converter(documentConverter)
				.from(new File("D:/ceshi", "test123.xlsm"))
				.asExtension("docx")
				.excel()
				.setLandscape(false)
				.end()
				.to(new FileOutputStream(new File("D:/ceshi", "xlsstream2pdfstream2.pdf")))
				.as(DefaultDocumentFormatRegistry.PDF)
				.execute();
		
		
		OfficeConvertHelper.converter(documentConverter)
				.from(new File("D:/ceshi", "765.docx"))
				.to(new File("D:/ceshi", "docfile2pdffile.pdf"))
				.execute();
		
		OfficeConvertHelper.converter(documentConverter)
				.from(new File("D:/ceshi", "765.docx"))
				.asExtension("docx")
				.to(new FileOutputStream(new File("D:/ceshi", "docfile2pdfstream1.pdf")))
				.as(DefaultDocumentFormatRegistry.PDF)
				.execute();
		
		OfficeConvertHelper.converter(documentConverter)
				.from(new File("D:/ceshi", "765.docx"))
				.asExtension("docx")
				.excel()
				.setLandscape(false)
				.end()
				.to(new FileOutputStream(new File("D:/ceshi", "docfile2pdfstream2.pdf")))
				.as(DefaultDocumentFormatRegistry.PDF)
				.execute();
		
		FileInputStream inputStream2 = new FileInputStream(new File("D:/ceshi", "765.docx"));
		OfficeConvertHelper.converter(documentConverter)
				.from(inputStream2, false)
				.to(new File("D:/ceshi", "docstream2pdffile.pdf"))
				.execute();
		inputStream2.read();
		inputStream2.close();
		
		OfficeConvertHelper.converter(documentConverter)
				.from(new File("D:/ceshi", "765.docx"))
				.asExtension("docx")
				.to(new FileOutputStream(new File("D:/ceshi", "docstream2pdfstream1.pdf")))
				.as(DefaultDocumentFormatRegistry.PDF)
				.execute();
		
		OfficeConvertHelper.converter(documentConverter)
				.from(new File("D:/ceshi", "765.docx"))
				.asExtension("docx")
				.excel()
				.setLandscape(false)
				.end()
				.to(new FileOutputStream(new File("D:/ceshi", "docstream2pdfstream2.pdf")))
				.as(DefaultDocumentFormatRegistry.PDF)
				.execute();
	}

}

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用LibreOffice的Java API来实现将LibreOffice文档转换为PDF文档。以下是实现的步骤: 1. 首先需要确保LibreOffice已经安装在系统中,并且已经配置好了环境变量。同时需要下载并安装LibreOffice的Java API。 2. 在Java程序中引入LibreOffice的Java API所在的jar包。 3. 使用以下代码将文档转换为PDF文档: ``` import com.sun.star.beans.PropertyValue; import com.sun.star.frame.XComponentLoader; import com.sun.star.lang.XComponent; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; public class ConvertToPDF { public static void main(String[] args) { XComponentContext xContext = null; try { //获取LibreOffice的上下文 xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); XComponentLoader xLoader = UnoRuntime.queryInterface(XComponentLoader.class, xContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", xContext)); //设置待转换文档的路径和文件名 String fileToConvert = "file:///C:/example.docx"; //设置转换后的PDF文档的路径和文件名 String pdfFile = "file:///C:/example.pdf"; //设置转换参数 PropertyValue[] conversionProperties = new PropertyValue[2]; conversionProperties[0] = new PropertyValue(); conversionProperties[0].Name = "Hidden"; conversionProperties[0].Value = Boolean.TRUE; conversionProperties[1] = new PropertyValue(); conversionProperties[1].Name = "FilterName"; conversionProperties[1].Value = "writer_pdf_Export"; //打开待转换文档 XComponent xComponent = xLoader.loadComponentFromURL(fileToConvert, "_blank", 0, conversionProperties); //将文档转换为PDF格式 PropertyValue[] storeProperties = new PropertyValue[3]; storeProperties[0] = new PropertyValue(); storeProperties[0].Name = "FilterName"; storeProperties[0].Value = "writer_pdf_Export"; storeProperties[1] = new PropertyValue(); storeProperties[1].Name = "Overwrite"; storeProperties[1].Value = Boolean.TRUE; storeProperties[2] = new PropertyValue(); storeProperties[2].Name = "Hidden"; storeProperties[2].Value = Boolean.TRUE; UnoRuntime.queryInterface(XStorable.class, xComponent).storeToURL(pdfFile, storeProperties); //关闭文档 UnoRuntime.queryInterface(XCloseable.class, xComponent).close(Boolean.TRUE); } catch (Exception e) { e.printStackTrace(); } finally { if (xContext != null) { com.sun.star.uno.Runtime.getRuntime(xContext).freeUnusedLibraries(); } } } } ``` 4. 运行程序即可将LibreOffice文档转换为PDF文档

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值