java實現(xiàn)html轉(zhuǎn)pdf方法步驟
1.需求:
將一個html頁面轉(zhuǎn)成pdf格式。
2.方法:
在實現(xiàn)之前先考慮一個問題,pdf是前端生成還是后端生成。這里采用pdfbox+itext(PDF文件名可自定義)技術(shù)在服務(wù)端生成。優(yōu)點:免費(fèi),不需要安轉(zhuǎn)軟件,速度快,對于開發(fā)者而言,開發(fā)中僅需導(dǎo)入相應(yīng)jar,且易部署。
缺點:對于html標(biāo)簽比較嚴(yán)格。
3.實現(xiàn):
3.1 需要的jar
itext-2.0.8.jar+pdfbox-2.0.19.jar
3.2 準(zhǔn)備好html頁面代碼(注意:這里需要手動指定字體):
sHtml += "<!DOCTYPE html[<!ENTITY nbsp ' '>]>"; sHtml += "<html>"; sHtml += "<head>"; sHtml += "</head>"; sHtml += "<body style='font-family:SimSun !important;'>"; sHtml += "<h1>這里是測試PDF代碼部分</h1>"; sHtml += "</body>"; sHtml += "</html>";
3.3 服務(wù)端開始生成PDF文件:
public static void toPdf(String sHtml) { try { //創(chuàng)建PDf文件 ITextRenderer renderer = new ITextRenderer(); ITextFontResolver fontResolver = renderer.getFontResolver(); //C:/WINDOWS/Fonts/SimSun.ttc 系統(tǒng)自帶的語言包,直接引用 fontResolver.addFont("C:/WINDOWS/Fonts/SimSun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); fontResolver.addFont("C:/WINDOWS/Fonts/Arial.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);// 宋體字 String sDate = new SimpleDateFormat("yyyyMMdd").format(new Date()); String sTime = new SimpleDateFormat("HHmmssSSS").format(new Date()); //指定文件存放路徑 URL sUrlPath = 當(dāng)前類名.class.getResource("/"); String sPath = sUrlPath.toURI().getPath(); sPath1 = sPath.replace("WEB-INF/classes/", ""); String sPathFolder = sPath+sDate+"\\"; File filePath = new File(sPathFolder); if(!filePath.exists() && !filePath.isDirectory()){ filePath.mkdirs(); } String sFileName = sDate+sTime+".pdf"; String sPathSave = sPathFolder+sFileName; OutputStream os = new FileOutputStream(sPathSave); //使用有setDocumentFromString()方法的jar包 renderer.setDocumentFromString(sHtml); renderer.layout(); renderer.createPDF(os); os.close(); } catch (Exception e) { e.printStackTrace(); } }
3.4 前端頁面發(fā)起請求,服務(wù)端將生成的PDF文件返回。
String sTitle = "測試PDF文件名"; File file = new File(sFileUrl);//這里的sFileUrl即上面PDF保存路徑 try { OutputStream outputStream = response.getOutputStream(); //加載pdf附件到PDF流中 PDDocument document = PDDocument.load(new FileInputStream(file)); response.reset(); response.setContentType("application/pdf;charset=UTF-8"); response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(sTitle, "UTF-8")); response.setContentType("application/pdf;charset=UTF-8"); //從PDF流中獲得PDF文檔屬性對象 PDDocumentInformation info = document.getDocumentInformation(); //設(shè)置PDF文檔屬性對象的文件名稱(最重要的環(huán)節(jié)) info.setTitle(sTitle); document.setDocumentInformation(info); //修改完直接輸出到響應(yīng)體中 document.save(outputStream); outputStream.close(); document.close(); out.clear(); out = pageContext.pushBody(); } catch (Exception e) { }
完成!
總結(jié)
到此這篇關(guān)于java實現(xiàn)html轉(zhuǎn)pdf方法步驟的文章就介紹到這了,更多相關(guān)java html轉(zhuǎn)pdf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實現(xiàn)項目健康檢查與監(jiān)控
這篇文章主要介紹了SpringBoot實現(xiàn)項目健康檢查與監(jiān)控,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06