• 基于LibreOffice转换文档


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

    POM依赖

    <dependency>
        <groupId>org.jodconvertergroupId>
        <artifactId>jodconverter-localartifactId>
        <version>4.4.2version>
    dependency>
    <dependency>
        <groupId>org.libreofficegroupId>
        <artifactId>ridlartifactId>
        <version>7.3.4version>
    dependency>
    <dependency>
        <groupId>org.jodconvertergroupId>
        <artifactId>jodconverter-spring-boot-starterartifactId>
        <version>4.4.2version>
    dependency>
    
    <dependency>
        <groupId>cn.afterturngroupId>
        <artifactId>easypoi-spring-boot-starterartifactId>
        <version>4.4.0version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    封装工具类 不依赖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);
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134

    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);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230

    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;
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    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;
    	}
    	
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115

    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;
    	}
    	
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171

    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;
    	}
    	
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89

    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;
    	}
    	
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    使用

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    示例

    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
  • 相关阅读:
    关于 [ 新版 ] dubbo-admin登录失败这件事
    Hadoop HBase Hive day3-day4.md
    什么是WebAssembly?
    基于Go语言快速搭建Iris+Xorm后台管理系统
    时序分析基础(2)——input_delay
    秋招每日一题------剑指offer整数中1出现的次数
    27岁,准备转行做网络安全渗透,完全零基础,有前途吗?
    「零基础从零开始写VO视觉里程计」概率论、最小二乘、图优化(7-4)
    Amazon Linux 2022 来袭,AWS 承诺后续每两年更新一次
    Go语言开发小技巧&易错点100例(三)
  • 原文地址:https://blog.csdn.net/daodfs111/article/details/126202736