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返回给前端,前端做对应的操作就能将文件下载下来。

Guess you like

Origin blog.csdn.net/csdnerM/article/details/120649237