一、背景
????????在工作中需要對(duì)上傳到服務(wù)器的各種類型包括但不限于word、pdf、excel等文件進(jìn)行在線預(yù)覽,前端比較菜搞不定,只能本人親自上。
? ? ? ? 網(wǎng)上的經(jīng)驗(yàn)比較多也比較亂,有的只有預(yù)覽,沒(méi)有文件格式轉(zhuǎn)換,有的也不說(shuō)linux存在字體問(wèn)題,本文會(huì)直白的給出過(guò)程和結(jié)果,包括文件預(yù)覽,其他格式文件轉(zhuǎn)pdf進(jìn)行預(yù)覽,前端如何接收展示。
二、引入jar包
<dependency>
<groupId>org.apache.tika</groupId><artifactId>tika-core</artifactId><version>1.28.4</version>
</dependency>
<dependency>
<groupId>com.luhuiguo</groupId><artifactId>aspose-words</artifactId>
<version>23.1</version>
</dependency>
三、后端實(shí)現(xiàn)代碼
controller
@GetMapping(”/preview”)
public ResponseEntity<?>?previewFile(@RequestParam String fileName){
????????String baseDir = RuoYiConfig.getUploadPath();
????????String filePath = baseDir + File.separator + fileName;
????????String extension = this.getExtension(fileName);
????????String pdfPath ="";
????????File file;
????????if("docx”.equals(extension)||"doc".equals(extension)){????????????????pdfPath = filePath.substring(0, filePath.lastIndex0f( str:".") + 1) + ????????????????????????????????"pdf";FileCovertUtils.wordToPdf(filePath,pdfPath);
????????????????file = new File(pdfPath);????????} else if ("png”.equals(extension)) {
? ? ? ? ? ? ? ? // excel\png等格式和上面word一樣自己寫(xiě)邏輯
? ? ? ? }?else{
????????????????file= new File(filePath);
????????}
????????try (FileInputStream fileInputStream = new FileInputStream(file)) {????????????????byte[] buf = new byte[fileInputStream.available()];
????????????????fileInputStream.read(buf);? ? ? ? ? ? ? ? ?return FileResponseUtils.getResponseEntity
????????????????????????????????(buf,contentDispositionType:"inline",FileUtils.getName(fileName));
????????} catch (IOException e) {
? ? ? ? ? ? ? ? log.error("獲取文件流異常{}",e);
? ? ? ? ? ? ? ? return “預(yù)覽失敗”;
????????} finally {????????????????if ("docx".equals(extension)||“doc".equals(extension)) {
????????????????????????FileUtils.deleteFile(pdfPath);
????????????????}
? ? ? ? }
}
getExtension
private String getExtension(String filename) {
????????int dotIndex = filename.lastIndex0f( str: ".");
????????if (dotIndex > ?&& dotIndex < filename.length() - 1){
????????????????return filename.substring(dotIndex + 1);
????????}
????????return "";}
FileResponseUtils.getResponseEntity
@Component
plic class FileResponseUtils {
????????public static ResponseEntity<?> getResponseEntity(byte[] buf, String ????????contentDispositionlype, String originalFilelame){????????????????ResponseEntity.BodyBuilder responseEntity = ResponseEntity.ok();HttpHeaders? ? ? ? ? ? ? ? ?HttpHeaders = new HttpHeaders();
????????????????Tika tika = new Tika();
????????????????String mediaType = tika.detect(buf);
????????????????httpHeaders.setContentType(MediaType.parseMediaType(mediaType));
????????????????HttpHeaders headers = new HttpHeaders();
????????????????headers.setContentType(MediaType.parseMediaType(mediaType);????????????????headers.add(HttpHeaders.CONTENT_DISPOSITION, headerValue: ????????????????????????????????????????????????cntentDispositionType+"; filename=" + originalFilename);
????????????????httpHeaders.setCacheControl(CacheControl.noCache());????????????????return responseEntity.headers(httpHeaders).body(buf);
????????}
}
?FileCovertUtils
public static void wordToPdf(String wordPath, String pdfPath) {
????????File file=new File(pdfPath);
????????try {????????????????FileOutputStream os = new FileOutputStream(file);
????????????????Document doc = new Document(wordPath);
????????????????if (System.getProperty("os,name").toLowerCase().contains("linux")){
????????????????????????FontSettings fontSettings = new FontSettings();
????????????????????????fontSettings.setFontsFolder( fontFolder: "/usr/share/fonts/", recursive: true);
????????????????????????doc.setFontSettings(fontSettings);
????????????????}
????????????????doc.save(os,SaveFormat.PDF);
????????????????os.flush();
????????????????os.close();????????}??catch (Exception e){
? ? ? ? ? ? ? ? log.error("word轉(zhuǎn)pdf異常:{}",e);????????}
}
FileUtils.getName
public static String getName(String fileName){
????????if (fileName == null){?????????????????return null:
????????}
????????int lastUnixPos = fileName .lastIndex0f('/');????????int lastWindowsPos = fileName .lastIndexOf('\\');
????????int index = Math.max(lastUnixPos, lastWindowsPos);
????????return fileName.substring(index + 1);
}
四、前端接收方式,簡(jiǎn)單粗暴
展示:
//1、請(qǐng)求接口 請(qǐng)求設(shè)置responseType
axios.get(url,{resonseType:'blob'})
?
//2.根據(jù)返回的值創(chuàng)建一個(gè)Blob對(duì)象, 以pdf文件為例
let blob = new Blob([result],{
? ? ? ?type: "application/pdf;chartset=UTF-8"
})
?
//3.window.URL.createObjectURL創(chuàng)建一個(gè)url連接
let blob = new Blob([result],{
? ? ? ?type: "application/pdf;chartset=UTF-8"
})
let url = window.URL.createObjectURL(blob)
?
//4.在線預(yù)覽
//可以用iframe預(yù)覽,url的值為 window.URL.createObjectURL(blob),或者直接打開(kāi)window.open(url)
打?。?/p>
//1.創(chuàng)建iframe標(biāo)簽
const iframe = document.createElement('iframe')
?
//2.屬性相關(guān)
iframe.className = 'tmp-pdf';
iframe.style.display = 'none'
// blobUrl 像在線預(yù)覽1,2,3這樣得來(lái)的url
iframe.src = blobUrl
?
//3.創(chuàng)建好的iframe添加到頁(yè)面body
document.body.appendChild(iframe)
?
//4.執(zhí)行打印方法,并移除iframe
setTimeout(function() {
? ?iframe.contentWindow.print()
? ?document.body.removechild(iframe)
}, 100)
五、linux中文字體亂碼解決
????????項(xiàng)目使用aspost轉(zhuǎn)pdf,Windows系統(tǒng)本地調(diào)試的時(shí)候一切正常,部署到Linux服務(wù)器,轉(zhuǎn)換后的pdf文件中文無(wú)法正確顯示。
原因是Linux服務(wù)器上沒(méi)有中文字體庫(kù)。
解決方法:在linux服務(wù)器中安裝字體,在Windows系統(tǒng)找到字體文件,路徑C:\Windows\Fonts,將字體文件fonts上傳到服務(wù)器
1、把fonts (只有一層文件夾) 上傳至tmp
2、移動(dòng) fonts: sudo mv /tmp/fonts/ /usr/share/
3、授權(quán)文件: sudo chmod 755 /usr/share/fonts/*
4、進(jìn)入文件: cd /usr/share/fonts/4
5、執(zhí)行: sudo mkfontscale 如果沒(méi)命令執(zhí)行sudo yum install mkfontscale
6、執(zhí)行: sudo mkfontdir 如果沒(méi)命令執(zhí)行sudo yum install fontconfig
7、sudo fc-cache
六、效果
七、推薦文章
java接口返回圖片或pdf如何設(shè)置在線預(yù)覽還是下載文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-846946.html
文檔在線預(yù)覽(三)將word、txt、ppt、excel、圖片轉(zhuǎn)成pdf來(lái)實(shí)現(xiàn)在線預(yù)覽文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-846946.html
到了這里,關(guān)于java超簡(jiǎn)單實(shí)現(xiàn)文檔在線預(yù)覽功能,支持word\excel\text\pdf\圖片等格式轉(zhuǎn)pdf,aspost 轉(zhuǎn)pdf部署linux中文亂碼解決方案的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!