2017-07-31 104 views
2

我需要單擊頁面上的鏈接下載文件。點擊按鈕,從HERE調用一個下載js文件。Download.js不能用於pdf mimetype

但是這不適用於mimetype application/pdf。任何幫助?可以試用HERE獨立演示測試download.js。

download("hello world", "dlText.pdf", "application/pdf"); 

回答

2

看起來像你想JsPDF這是致力於解決PDF的東西。

所有你需要做的是使用setText()功能

var doc = new jsPDF(); 
 
doc.text(20, 20, 'Hello world!'); 
 
doc.save('is_this_what_you_are_looking_for.pdf');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js"></script>

+0

謝謝蘇雷什。所以當我按照這個,我得到以下錯誤。 spdf.js:471函數對象中的錯誤:saveAs未定義ReferenceError:saveAs未在Object中定義。在Object.success(detail.js:287)處的對象.__ safeCallWrapper [作爲輸出](jspdf.js:465)處的Object.API.save(jspdf.js:2029)處的(jspdf.js:962) jquery-3.2.1.min.js:2)在XMLHttpRequest上的A(jquery-3.2.1.min.js:4)處的Object.fireWith [as resolveWith](jquery-3.2.1.min.js:2) 。 (jquery-3.2.1.min.js:4) –

+1

也可以添加嗎? https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js –

+0

是的,這對我有用。謝謝。 –

0

您需要使用BLOB數據類型,你需要改變你的代碼,

download(new Blob(["hello world"]), "dlText.pdf", "application/pdf"); 

希望這有助於!

+0

不,這也行不通。你可以在這裏查看獨立的網址。 http://pagedemos.com/sxks39b72aqb/1 –

+0

下載後下載的PDF文件被損壞。 @David R –

+0

根據插件,它也會接受字符串。它不是強制性的blob類型。 –

1

貌似沒有所需的JavaScript可言。 解決了它服務器端。如果有人在尋找服務器端java解決方案。

控制器與任何js apis一起工作。

public static void downloadFile(
      final HttpServletResponse response, 
      final String fileName, 
      final String fileType, 
      final byte[] decodedDocument) throws Exception{ 

     /* Set the file properties*/ 
     if(fileType == null) { 
      response.setContentType("application/octet-stream"); 
     } else { 
      response.setContentType(fileType); 
     } 
     response.setHeader("Content-Disposition", "attachment; filename=" + fileName); 
     response.setHeader("Pragma", "no-cache"); 
     response.setHeader("Cache-Control", "no-cache"); 

     /* Convert bytes to stream of objects*/ 
     InputStream is = new ByteArrayInputStream(decodedDocument); 

     /*Download copying the content to destination file*/ 
     IOUtils.copy(is, response.getOutputStream()); 
     response.flushBuffer(); 
    }