word转pdf java

word转pdf java

公司项目,需要生成pdf文件,思路是根据word模板生成word文件,然后将word文件转换成pdf文件,在pdf转换的时候遇到一些坑,网上找了很多案例,也踩了很多坑,下面把用到的方法和遇到的问题都记录说明一下。

1、docx2pdf

适用于windows系统,需要安装office服务

		
            com.documents4j
            documents4j-local
            1.1.5
        
        
            com.documents4j
            documents4j-transformer-msoffice-word
            1.1.5
        
public static OutputStream docxToPdf(InputStream wordInputStream) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
//		File inputFile = new File(wordFilePath);
//		File outputFile = new File(pdfFilePath);
		try {
//			InputStream inputStream = new FileInputStream(inputFile);
//			OutputStream outputStream = new FileOutputStream(outputFile);
//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			IConverter converter = LocalConverter.builder().build();
			converter.convert(wordInputStream).as(DocumentType.DOCX).to(baos).as(DocumentType.PDF).execute();

			return baos;
//			baos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return baos;
	}

2、poi转换

开发的时候是windows系统,采用的docx2pdf方式,但是客户的服务器是linux,上面的方法不支持,就改成了poi,改完之后出现了排版与word模板不一致的问题。

		
            org.apache.poi
            ooxml-schemas
            1.1
        
        
            org.eclipse.birt.runtime.3_7_1
            com.lowagie.text
            2.1.7
        
        
            org.apache.poi
            poi-ooxml
            3.17
        
public static OutputStream docxtoPdf(InputStream inputStream) throws IOException {
		XWPFDocument xwpfDocument = new XWPFDocument(inputStream);
		fr.opensagres.poi.xwpf.converter.pdf.PdfOptions pdfOptions = fr.opensagres.poi.xwpf.converter.pdf.PdfOptions.create();
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.getInstance().convert(xwpfDocument,baos,pdfOptions);
		return baos;
	}

3、aspose

需要配license


<License>
    <Data>
        <Products>
            <Product>Aspose.Total for JavaProduct>
            <Product>Aspose.Words for JavaProduct>
        Products>
        <EditionType>EnterpriseEditionType>
        <SubscriptionExpiry>20991231SubscriptionExpiry>
        <LicenseExpiry>20991231LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7SerialNumber>
    Data>
    <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=Signature>
License>

依赖

		
            com.aspose
            aspose-words
            15.8.0
        

import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;


import java.io.*;
import java.util.Properties;

public class Word2PdfAsposeUtil {


/**
	 * @Author zhuigu
	 * @Description 判断是否有授权文件 如果没有则会认为是试用版,转换的文件会有水
	 * @Date  2021/6/3
	 * @Param 
	 * @return boolean 
	 */
	public static boolean getLicense() {
		boolean result = false;
		InputStream is = null;
		try {
			Resource resource = new ClassPathResource("license.xml");// license.xml应放在resources路径下
			is = resource.getInputStream(); 
			License aposeLic = new License();
			aposeLic.setLicense(is);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
/**
	 * @Author zhuigu
	 * @Description word转pdf
	 * @Date  2021/6/3
	 * @Param inputStream
	 * @return java.io.OutputStream 
	 */
	public static OutputStream doc2pdf(InputStream inputStream) {
		if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
			return null;
		}
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();

			//判断系统环境
			Properties prop = System.getProperties();
			String os = prop.getProperty("os.name");
			if (os != null && os.toLowerCase().indexOf("linux") > -1) {
				// 设置字体
				// linux系统需要解开下面字体的注释
				FontSettings.setFontsFolder("/usr/share/fonts",true);
			}
			Document doc = new Document(inputStream); // Address是将要被转化的word文档
			doc.save(baos, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
			// EPUB, XPS, SWF 相互转换
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally {
			if (baos != null) {
				return baos;
			}
		}
		return null;
	}
}

采用这个方法也出现一个问题,但是与用到方法没有关系,转换后的pdf文件存在乱码现象,是由于服务器上没有模板中的字体,需要手动将字体加到服务器上,
linux字体地址:/usr/share/fonts
windows字体地址:C:\Windows\Fonts

你可能感兴趣的:(office,java,后端)