java实现各种文件类型转PDF

demo地址:https://download.csdn.net/download/qq_39098505/10595102

OpenOffice下载地址:https://download.csdn.net/download/qq_39098505/10595134

可以支持各种类型文件转pdf

private static Logger logger = Logger.getLogger(FileToPdfUtils.class);
	private final static long MAXSIZE = 80000000; // 最大限制转化大小8MB

	public static File convertFileToPdf(File sourceFile, String pdfTempPath) throws IOException {
		if (sourceFile.length() > MAXSIZE) {
			throw new BusinessException("the size of file  out of range");
		}

		String fileType = FileOperation.getFileType(sourceFile.getName());

		// 临时pdf文件
		File pdfFile = new File(pdfTempPath);
		if (!pdfFile.exists()) {
			pdfFile.createNewFile();
		}
		InputStream inputStream = null;
		OutputStream outputStream = null;

		if (!fileType.equals("pdf")) {

			// 获得文件格式
			DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
			DocumentFormat pdfFormat = formatReg.getFormatByFileExtension("pdf");
			DocumentFormat docFormat = formatReg.getFormatByFileExtension(fileType);

			/**
			 * 在此之前需先开启openoffice服务,用命令行打开cd C:\Program Files\OpenOffice.org 3\program (openoffice安装的路径) 
			 * 输入 soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
			 */
			OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);

			try {
				// stream 流的形式
				inputStream = new FileInputStream(sourceFile);
				outputStream = new FileOutputStream(pdfFile);
				connection.connect();
				DocumentConverter converter = new OpenOfficeDocumentConverter(connection);

				converter.convert(inputStream, docFormat, outputStream, pdfFormat);

			} catch (Exception e) {
				e.printStackTrace();
				throw new BusinessException(e.getMessage());
			} finally {
				if (connection != null) {
					connection.disconnect();
					connection = null;
				}

				try {
					inputStream.close();
					outputStream.close();
				} catch (IOException e) {

					e.printStackTrace();
				}

			}
			System.out.println("转化pdf成功....");
			logger.info("转化pdf成功....");

		} else {
			// 复制pdf文件到新的文件
			FileUtils.copyFile(sourceFile, pdfFile);

		}

		return pdfFile;

猜你喜欢

转载自blog.csdn.net/qq_39098505/article/details/81559864
今日推荐