亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java中將Html轉(zhuǎn)換為PDF的方法和步驟

 更新時(shí)間:2023年06月15日 10:44:25   作者:掉頭發(fā)的王富貴  
這篇文章主要介紹了Java中如何將Html轉(zhuǎn)換為PDF的方法,文中有相關(guān)的代碼示例和步驟講解,感興趣的同學(xué)可以參考閱讀

Html分兩種情況轉(zhuǎn)換為Pdf:

第一種:html的文件

第二鐘:html格式的字符串

我們先來(lái)講一下第一種情況: 1.市面上有很多的html轉(zhuǎn)pdf的方法,但是不是受限于中文的限制就是受限于css樣式的丟失或者是對(duì)html的要求太嚴(yán)格。 所以我在做這個(gè)教程的時(shí)候找到了一個(gè)非常厲害的一個(gè)組件首先看一下他的官網(wǎng): e-iceblue 他有商業(yè)版本和免費(fèi)的版本,商業(yè)版本沒(méi)購(gòu)買(mǎi)之前是有水印的,但是可以轉(zhuǎn)換10頁(yè),免費(fèi)版本是沒(méi)有水印的,但是只支持轉(zhuǎn)換前三頁(yè)。結(jié)合教程使用,我們使用他的免費(fèi)版本,首先第一步導(dǎo)入他的jar包:

<dependency>
            <groupId> e-iceblue </groupId>
            <artifactId>spire.doc.free</artifactId>
            <version>3.9.0</version>
        </dependency>

但是中央倉(cāng)庫(kù)是沒(méi)有這個(gè)jar包的,所以我們還需要加一個(gè)他的jar包倉(cāng)庫(kù)地址:

    <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對(duì)象
        Document doc = new Document();
        //添加section
        Section sec = doc.addSection();
        String htmlText = readTextFromFile(inputHtml);
        //添加段落并寫(xiě)入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();
    }
}

這個(gè)時(shí)候就會(huì)在c盤(pán)目錄下生成InputHtml.txt對(duì)應(yīng)的HTMLstringToPDF.pdf文件 第二種方法,html為文本格式的情況: 1.導(dǎo)入上的jar包之后之間將html的文本內(nèi)容賦值給htmlTest

 public static void main(String[] args) throws IOException{
        //新建Document對(duì)象
        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)系電話(huà):<span>18888888888</span></span>\n" +
                "          </div>\n" +
                "          <div class=\"yiban\">\n" +
                "            <span class=\"jiachu\">送貨單號(hào):</span><span>1567894</span>\n" +
                "          </div>\n" +
                "        </td>\n" +
                "      </tr>";
        //添加段落并寫(xiě)入HTML文本
        sec.addParagraph().appendHTML(htmlText);
        //將文檔另存為PDF
        doc.saveToFile("C:\\HTMLstringToPDF.pdf", FileFormat.PDF);
        doc.dispose();
    }

這個(gè)情況也是一樣的

拓展:將生成的pdf文件返回給前端以供下載

需要一下的代碼段,直接貼出來(lái)供大家參考:

 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文件并強(qiáng)制用戶(hù)下載。在此代碼中,通過(guò)ServletRequestAttributes獲取當(dāng)前請(qǐng)求的HttpServletResponse對(duì)象,并設(shè)置響應(yīng)的content-typeContent-Disposition頭信息,強(qiáng)制將網(wǎng)頁(yè)作為附件進(jìn)行下載保存。

接著,使用 FileInputStream 從指定路徑打開(kāi)該文件,并從響應(yīng)對(duì)象獲取輸出流 ServletOutputStream,將文件內(nèi)容通過(guò)循環(huán)一個(gè)字節(jié)一個(gè)字節(jié)讀取寫(xiě)入輸出流中,最終實(shí)現(xiàn)文件的下載。循環(huán)的過(guò)程中沒(méi)有直接按塊大小讀取并寫(xiě)入,可能會(huì)對(duì)操作系統(tǒng)產(chǎn)生一些額外的負(fù)載,但是其功能簡(jiǎn)單易懂,可以適用于小型文檔或者測(cè)試用例場(chǎng)景等;如果文件較大,可以改變循環(huán)體來(lái)調(diào)用更高效的I/O操作API實(shí)現(xiàn)數(shù)據(jù)的分塊傳輸,避免內(nèi)存泄漏。

最后在finally塊中關(guān)閉輸入和輸出流,釋放資源,防止出現(xiàn)問(wèn)題可能導(dǎo)致的文件描述符泄露等安全隱患。

需要注意的是,在設(shè)定Content-Disposition頭信息時(shí)有編碼轉(zhuǎn)換的處理,確保整個(gè)文件名不會(huì)受到URL編碼而導(dǎo)致亂碼問(wèn)題。

使用該方法:

HtmlToPDFUtil.downloadPdf(fileName,tmplPath+fileName);

這樣就會(huì)將pdf文件作為response返回給前端,前端做對(duì)應(yīng)的操作就能將文件下載下來(lái)。

到此這篇關(guān)于Java中將Html轉(zhuǎn)換為PDF的方法和步驟的文章就介紹到這了,更多相關(guān)Java Html轉(zhuǎn)換為PDF內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論