java 使用aspose做word轉pdf
代碼如下
import cn.hutool.core.io.FileUtil;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Word2Pdf
*
* @author [email protected]
* @version 1.0
* @date 2020/1/19 10:07
*/
public class Word2Pdf {
public static boolean getLicense() {
boolean result = false;
try {
String s = "<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>";
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
License license = new License();
license.setLicense(is);
result = true;
} catch (Exception e) {
}
return result;
}
public static void doc2pdf(InputStream inputStream, OutputStream outputStream) {
// 驗證License 若不驗證則轉化出的pdf文檔會有水印產生
if (!getLicense()) {
return;
}
try {
//Address是將要被轉化的word文檔
Document doc = new Document(inputStream);
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互轉換
doc.save(outputStream, SaveFormat.PDF);
} catch (Exception e) {
}
}
public static void main(String[] args) throws Exception {
long old = System.currentTimeMillis();
OutputStream outputStream = new FileOutputStream("/Users/liaoshuhao/2019年終總結.pdf");
doc2pdf(FileUtil.getInputStream("/Users/liaoshuhao/Desktop/2019年終總結.docx"), outputStream);
outputStream.flush();
long now = System.currentTimeMillis();
//轉化用時
System.out.println("共耗時:" + ((now - old) / 1000.0) + "秒");
}
}
上述代碼各處可見,最麻煩的問題在於,當我們在本地macOs/ Windows 環境測試沒有問題,上到測試或者生產linux、docker服務器時就會出現亂碼
原因在於linux字體庫沒有對應office的各種中文字體
解決方法
1.linux環境下
上傳本地字體庫
scp /Users/Desktop/Fonts.zip -i sum [email protected]:/
進入服務器192.168.1.100 [這裏是舉例服務器]
unzip -o -d /usr/share/fonts/ Fonts.zip
如果unzip未安裝,則 yum install unzip
fc-cache -fv 刷新字體庫緩存
shutdown -r now 重啓服務器字體庫起效,不重啓也有可能起效,保險起見還是重啓
fc-list :lang=zh 使用這個命令可以看到如下數據就說明成功了
重啓項目使用就不亂碼了
2.docker環境下
重複上面操作,不過進入的服務器是宿主機
docker run -v /usr/share/fonts:/usr/share/fonts ***
docker啓動時共享宿主機的字體庫重啓docker項目即可解決亂碼問題