通过aspose-words把word文件链接直接转成pdf
1,引入pom包
1 2 3 4 5
| <dependency> <groupId>com.luhuiguo</groupId> <artifactId>aspose-words</artifactId> <version>22.4</version> </dependency>
|
2,pdf工具类
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
| import com.aspose.words.Document;
import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL;
public class PDFTemplateUtil { /** * 通过模板导出pdf文件 * * @param documentUrl word模板链接 * @throws Exception */ public static ByteArrayOutputStream createPDF(String documentUrl) throws Exception { URL url = new URL(documentUrl); InputStream stream = url.openStream(); try { // 从流中加载Word文档 Document doc = new Document(stream); // 创建用于保存输出PDF的字节数组输出流 ByteArrayOutputStream pdfBytes = new ByteArrayOutputStream(); // 将Word文档保存为PDF格式并写入字节数组输出流 doc.save(pdfBytes, com.aspose.words.SaveFormat.PDF); // 返回包含PDF内容的字节数组输出流 return pdfBytes; } catch (Exception e) { throw e; } finally { if (stream != null) { try { stream.close(); } catch (Exception ex) { // 忽略关闭异常 } } } } }
|
3,导出pdf并上传到oss
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
| import com.awsa.site.controller.Req.word.ExportWordReq; import com.awsa.site.service.IWordService; import com.awsa.site.service.PDFService; import com.awsa.site.utils.oss.OssUtil; import com.awsa.site.utils.pdf.PDFTemplateUtil; import com.open.capacity.common.common.BaseRes; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.ByteArrayOutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; @Service @Slf4j public class PDFServiceImpl implements PDFService { @Resource IWordService wordService; @Override public BaseRes<String> exportPdf(ExportWordReq reqEntity) throws Exception { BaseRes<String> baseRes = wordService.exportWord(reqEntity); ByteArrayOutputStream outputStream = null; String name = ""; if (baseRes.getCode() == 200) { outputStream = PDFTemplateUtil.createPDF(baseRes.getMsg()); Pattern pattern = Pattern.compile("word\\/(.*?)\\.docx"); Matcher matcher = pattern.matcher(baseRes.getMsg()); while (matcher.find()) { name = matcher.group(1); } } // 将导出结果上传至OSS String fileName = "pdf/" + name + ".pdf"; byte[] fileData = outputStream.toByteArray(); OssUtil.ossUploadMediaByteArray(fileName, fileData); // 释放资源、删除本地临时文件并打印导出成功信息 outputStream.close(); return BaseRes.Success("https://awsacloud.oss-cn-shanghai.aliyuncs.com/" + fileName); } }
|