Java中將Html轉換為PDF


Html分兩種情況轉換為Pdf:

第一種:html的文件
第二鍾:html格式的字符串
我們先來講一下第一種情況:
1.市面上有很多的html轉pdf的方法,但是不是受限於中文的限制就是受限於css樣式的丟失或者是對html的要求太嚴格。
所以我在做這個教程的時候找到了一個非常厲害的一個組件首先看一下他的官網:
e-iceblue
他有商業版本和免費的版本,商業版本沒購買之前是有水印的,但是可以轉換10頁,免費版本是沒有水印的,但是只支持轉換前三頁。結合教程使用,我們使用他的免費版本,首先第一步導入他的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文件的內容:

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對應的HTMLstringToPDF.pdf文件
第二種方法,html為文本格式的情況:
1.導入上的jar包之后之間將html的文本內容賦值給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\">聯系電話:<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);
            }
        }
    }

使用該方法:

HtmlToPDFUtil.downloadPdf(fileName,tmplPath+fileName);

這樣就會將pdf文件作為response返回給前端,前端做對應的操作就能將文件下載下來。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM