Java中將Html轉(zhuǎn)換為PDF的方法和步驟
Html分兩種情況轉(zhuǎn)換為Pdf:
第一種:html的文件
第二鐘:html格式的字符串
我們先來講一下第一種情況: 1.市面上有很多的html轉(zhuǎn)pdf的方法,但是不是受限于中文的限制就是受限于css樣式的丟失或者是對html的要求太嚴格。 所以我在做這個教程的時候找到了一個非常厲害的一個組件首先看一下他的官網(wǎng): e-iceblue 他有商業(yè)版本和免費的版本,商業(yè)版本沒購買之前是有水印的,但是可以轉(zhuǎn)換10頁,免費版本是沒有水印的,但是只支持轉(zhuǎn)換前三頁。結(jié)合教程使用,我們使用他的免費版本,首先第一步導入他的jar包:
<dependency> <groupId> e-iceblue </groupId> <artifactId>spire.doc.free</artifactId> <version>3.9.0</version> </dependency>
但是中央倉庫是沒有這個jar包的,所以我們還需要加一個他的jar包倉庫地址:
<repositories> <repository> <id>com.e-iceblue</id> <url>http://repo.e-iceblue.cn/repository/maven-public/</url> </repository> </repositories>
2.第二步我們使用一下方式讀取html文件的內(nèi)容:
public class HtmlToPDFUtil { public static void main(String[] args) throws IOException{ String inputHtml = "C:\\InputHtml.txt"; //新建Document對象 Document doc = new Document(); //添加section Section sec = doc.addSection(); String htmlText = readTextFromFile(inputHtml); //添加段落并寫入HTML文本 sec.addParagraph().appendHTML(htmlText); //將文檔另存為PDF doc.saveToFile("C:\\HTMLstringToPDF.pdf", FileFormat.PDF); doc.dispose(); } public static String readTextFromFile(String fileName) throws IOException { StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new FileReader(fileName)); String content; while ((content = br.readLine()) != null) { sb.append(content); } return sb.toString(); } }
這個時候就會在c盤目錄下生成InputHtml.txt
對應(yīng)的HTMLstringToPDF.pdf
文件 第二種方法,html為文本格式的情況: 1.導入上的jar包之后之間將html的文本內(nèi)容賦值給htmlTest
:
public static void main(String[] args) throws IOException{ //新建Document對象 Document doc = new Document(); //添加section Section sec = doc.addSection(); String htmlText = " <tr>\n" + " <td colspan=\"8\">\n" + " <div class=\"yiban\">\n" + " <span class=\"jiachu\">聯(lián)系電話:<span>18888888888</span></span>\n" + " </div>\n" + " <div class=\"yiban\">\n" + " <span class=\"jiachu\">送貨單號:</span><span>1567894</span>\n" + " </div>\n" + " </td>\n" + " </tr>"; //添加段落并寫入HTML文本 sec.addParagraph().appendHTML(htmlText); //將文檔另存為PDF doc.saveToFile("C:\\HTMLstringToPDF.pdf", FileFormat.PDF); doc.dispose(); }
這個情況也是一樣的
拓展:將生成的pdf文件返回給前端以供下載
需要一下的代碼段,直接貼出來供大家參考:
public static void downloadPdf(String fileName, String path) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletResponse response = requestAttributes.getResponse(); response.setContentType("application/force-download"); try { response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1")); } catch (Exception e) { e.printStackTrace(); } File file = new File(path); InputStream is = null; ServletOutputStream os = null; try { is = new FileInputStream(file); os = response.getOutputStream(); int b; while ((b = is.read()) != -1) { os.write(b); } } catch (FileNotFoundException e) { ExceptionUtils.logError(e); } catch (IOException e) { ExceptionUtils.logError(e); } finally { try { if (null != os) { os.close(); } if (null != is) { is.close(); } } catch (IOException e) { ExceptionUtils.logError(e); } } }
這段Java代碼演示了如何從本地服務(wù)器下載PDF文件并強制用戶下載。在此代碼中,通過ServletRequestAttributes
獲取當前請求的HttpServletResponse
對象,并設(shè)置響應(yīng)的content-type
和Content-Disposition
頭信息,強制將網(wǎng)頁作為附件進行下載保存。
接著,使用 FileInputStream
從指定路徑打開該文件,并從響應(yīng)對象獲取輸出流 ServletOutputStream
,將文件內(nèi)容通過循環(huán)一個字節(jié)一個字節(jié)讀取寫入輸出流中,最終實現(xiàn)文件的下載。循環(huán)的過程中沒有直接按塊大小讀取并寫入,可能會對操作系統(tǒng)產(chǎn)生一些額外的負載,但是其功能簡單易懂,可以適用于小型文檔或者測試用例場景等;如果文件較大,可以改變循環(huán)體來調(diào)用更高效的I/O操作API實現(xiàn)數(shù)據(jù)的分塊傳輸,避免內(nèi)存泄漏。
最后在finally塊中關(guān)閉輸入和輸出流,釋放資源,防止出現(xiàn)問題可能導致的文件描述符泄露等安全隱患。
需要注意的是,在設(shè)定Content-Disposition頭信息時有編碼轉(zhuǎn)換的處理,確保整個文件名不會受到URL編碼而導致亂碼問題。
使用該方法:
HtmlToPDFUtil.downloadPdf(fileName,tmplPath+fileName);
這樣就會將pdf文件作為response返回給前端,前端做對應(yīng)的操作就能將文件下載下來。
到此這篇關(guān)于Java中將Html轉(zhuǎn)換為PDF的方法和步驟的文章就介紹到這了,更多相關(guān)Java Html轉(zhuǎn)換為PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于HashMap相同key累加value的問題
這篇文章主要介紹了關(guān)于HashMap相同key累加value的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05