引言
最近由于項目需要一個Word在線預覽的功能,由于考慮基于Linux平臺做部署,實現(xiàn)真正的Word在線預覽是不現(xiàn)實的,所以考慮通過Word轉PDF實現(xiàn)PDF的在線預覽。
經過一番研究,試了多種方式包括POI實現(xiàn)Word轉PDF,以及Word轉HTML再轉PDF等方式,但均存在操作非常復雜和效果不理想以及兼容性不好等問題,最終鎖定借助LibreOffice實現(xiàn)Word轉PDF的方案。
Linux安裝LibreOffice(在Ubuntu Server 18.04下實驗)
1.訪問http://download.documentfoundation.org/libreoffice/stable/6.2.2/deb/x86_64/ 下載離線安裝包:
- LibreOffice_6.2.2_Linux_x86-64_deb.tar.gz
- LibreOffice_6.2.2_Linux_x86-64_deb_langpack_zh-CN.tar.gz
- LibreOffice_6.2.2_Linux_x86-64_deb_sdk.tar.gz
2.將三個安裝包復制到Linux系統(tǒng),執(zhí)行以下指令:
sudo mkdir /opt/libreoffice
sudo tar -zxvf LibreOffice_6.2.2_Linux_x86-64_deb.tar.gz -C /opt/libreoffice/
sudo tar -zxvf LibreOffice_6.2.2_Linux_x86-64_deb_langpack_zh-CN.tar.gz -C /opt/libreoffice/
sudo tar -zxvf LibreOffice_6.2.2_Linux_x86-64_deb_sdk.tar.gz -C /opt/libreoffice/
cd /opt/libreoffice/LibreOffice_6.2.2.2_Linux_x86-64_deb/DEBS
sudo dpkg -i *.deb
cd /opt/libreoffice/LibreOffice_6.2.2.2_Linux_x86-64_deb_sdk/DEBS
sudo dpkg -i *.deb
cd /opt/libreoffice/LibreOffice_6.2.2.2_Linux_x86-64_deb_langpack_zh-CN/DEBS
sudo dpkg -i *.deb
sudo apt-get install libxinerama1
sudo apt-get install libcairo2-dev
sudo apt-get install libcups2-dev
Word轉PDF測試
libreoffice6.2 --headless --invisible --convert-to pdf <待轉換的word路徑> --outdir <生成的pdf路徑>
此時可在輸出目錄看到已經生成了轉換后的PDF文件,但是打開查看文件發(fā)現(xiàn)字符亂碼。
添加字體支持
1.下載如下字體:
- simsun.ttc 宋體
- simhei.ttf 黑體
- msyh.ttf 微軟雅黑
- msyhbd.ttf 微軟雅黑
2.在/usr/share/fonts/truetype下面建立一個文件夾CustomizedGonts,把字體文件復制進來。
3.把字體文件夾和字體文件都賦予權限
sudo chmod 777 CustomizedFonts
cd CustomizedFonts
sudo chmod 777 *
4.安裝字體
sudo mkfontscale
sudo mkfontdir
sudo fc-cache
Word轉PDF測試
libreoffice6.2 --headless --invisible --convert-to pdf <待轉換的word路徑> --outdir <生成的pdf路徑>
此時可在輸出目錄看到已經生成了轉換后的PDF文件,并且文字顯示正常。
Spring Boot工程
1.添加Maven依賴
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.libreoffice</groupId>
<artifactId>ridl</artifactId>
<version>5.4.2</version>
</dependency>
2.配置application.ptoperties
jodconverter.local.enabled=true
jodconverter.local.office-home=/opt/libreoffice6.2
jodconverter.local.port-numbers=8100,8101,8102
jodconverter.local.max-tasks-per-process=100
3.pdf轉換代碼
@RestController
@RequestMapping("/doc")
public class PDFController {
@Autowired
private DocumentConverter documentConverter;
@RequestMapping("/pdf")
public void toPdf() throws OfficeException {
File word = new File("/home/doc/123.doc");
File pdf = new File("/home/doc/123.pdf");
documentConverter.convert(word).to(pdf).execute();
}
}