1、使用的依赖
< dependencies>
< dependency>
< groupId> com. aspose< / groupId>
< artifactId> aspose- words< / artifactId>
< version> 14.9 .0 < / version>
< / dependency>
< / dependencies>
< repositories>
< repository>
< id> com. e- iceblue< / id>
< url> https: / / repo. e- iceblue. cn/ repository/ maven- public / < / url>
< / repository>
< repository>
< id> aspose- maven- repository< / id>
< url> http: / / artifact. aspose. com/ repo/ < / url>
< / repository>
< / repositories>
2、编写aspose.word 工具类
public class AsposeWordUtils {
private static final Logger log = LoggerFactory. getLogger ( AsposeWordUtils. class ) ;
static {
String fileName = "license.xml" ;
try ( InputStream license = AsposeWordUtils. class . getClassLoader ( ) . getResource ( fileName) . openStream ( ) ) {
License asposeLicense = new License ( ) ;
asposeLicense. setLicense ( license) ;
} catch ( Exception e) {
log. error ( "引入license文件失败!" , e) ;
}
}
public static byte [ ] byteToPdf ( byte [ ] content) {
try ( ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ;
InputStream inputStream = new ByteArrayInputStream ( content) ) {
Document document = new Document ( inputStream) ;
document. save ( bos, SaveFormat. PDF) ;
return bos. toByteArray ( ) ;
} catch ( Exception e) {
log. error ( "字节数组转pdf字节数组失败!" , e) ;
return null;
}
}
public static byte [ ] docToDocx ( byte [ ] content) {
try ( ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ;
InputStream inputStream = new ByteArrayInputStream ( content) ) {
Document document = new Document ( inputStream) ;
document. save ( bos, SaveFormat. DOCX) ;
return bos. toByteArray ( ) ;
} catch ( Exception e) {
log. error ( "doc字节数组转docx字节数组失败!" , e) ;
return null;
}
}
}
3、测试代码
@Test
public void wordToPdf ( ) {
String filePath = "C:\\Users\\desktop\\docx文件的.docx" ;
byte [ ] content = new byte [ 0 ] ;
try {
content = Files. readAllBytes ( Paths. get ( filePath) ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
byte [ ] result = AsposeWordUtils. byteToPdf ( content) ;
InputStream inputStream = new ByteArrayInputStream ( result) ;
FileOutputStream fos = new FileOutputStream ( "C:\\Users\\desktop\\导出的pdf文件.pdf" ) ;
byte [ ] buffer = new byte [ 1024 ] ;
int r = 0 ;
while ( ( r = inputStream. read ( buffer) ) != - 1 ) {
fos. write ( buffer, 0 , r) ;
}
inputStream. close ( ) ;
}
4、写一个license.xml文件,SpringBoot项目放resource目录下
< License>
< Data>
< Products>
< Product> Aspose.Total for Java</ Product>
< Product> Aspose.Words for Java</ Product>
</ Products>
< EditionType> Enterprise</ EditionType>
< SubscriptionExpiry> 20991231</ SubscriptionExpiry>
< LicenseExpiry> 20991231</ LicenseExpiry>
< SerialNumber> 8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</ SerialNumber>
</ Data>
< Signature> sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</ Signature>
</ License>