使用 libreoffice 將 word 轉 pdf
阿新 • • 發佈:2019-06-23
https://mirror-hk.koddos.net/tdf/libreoffice/stable/6.2.4/
下載libreoffice
加入依賴
<dependency> <groupId>org.jodconverter</groupId> <artifactId>jodconverter-spring-boot-starter</artifactId> <version>4.2.2</version> </dependency> <dependency> <groupId>org.jodconverter</groupId> <artifactId>jodconverter-core</artifactId> <version>4.2.2</version> </dependency> <dependency> <groupId>org.jodconverter</groupId> <artifactId>jodconverter-local</artifactId> <version>4.2.2</version> </dependency> <dependency> <groupId>org.libreoffice</groupId> <artifactId>ridl</artifactId> <version>6.2.3</version> </dependency>
程式碼使用如下:
@Autowired private DocumentConverter documentConverter; public void toPdf(@PathVariable String fileName, HttpServletResponse response) throws IOException, OfficeException { ClassPathResource classPathResource = new ClassPathResource("static/aa.docx"); InputStream inputStream = classPathResource.getInputStream();//獲取檔案流 response.reset(); response.setContentType("multipart/form-data"); fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1"); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\".pdf"); try (OutputStream outputStream = response.getOutputStream()) { documentConverter .convert(inputStream).as(documentConverter.getFormatRegistry().getFormatByExtension("docx")) .to(outputStream).as(documentConverter.getFormatRegistry().getFormatByExtension("pdf")) .execute(); } }
yml配置檔案
jodconverter:
local:
enabled: true
# 設定LibreOffice主目錄
office-home: /opt/libreoffice6.0
# 開啟多個LibreOffice程序,每個埠對應一個程序
portNumbers: 8100,8101,8102
# LibreOffice程序重啟前的最大程序數
maxTasksPerProcess: 100
docker 依賴
參考地址:
http://www.luyixian.cn/news_show_15376.aspx
https://www.jianshu.com/p/b05fde8ac097
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<configuration>
<imageName>jerry/to-pdf</imageName>
<baseImage>openjdk:11-jdk-oracle</baseImage>
<runs>
<![CDATA[
yum install libreoffice-writer.x86_64 -y \
&& yum groupinstall "Fonts" -y && yum groupinstall "Input Methods" -y \
&& rm -rf /etc/localtime \
&& ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& yum -y install kde-l10n-Chinese \
&& yum -y reinstall glibc-common && localedef -c -f UTF-8 -i zh_CN zh_CN.utf8 \
&& yum clean all
]]>
</runs>
<env>LC_ALL zh_CN.utf8</env>
<entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>