java将html的图文转化为PDF文件输出

首先在我的项目的resource目录下建立相应的目录,如图

java将html的图文转化为PDF文件输出

其中file用来存放一个logo以及生成的PDF文件,font文件夹用来存放font 字体

然后在项目的 pom.xml中添加引用

<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>flying-saucer-pdf</artifactId>
    <version>9.1.5</version>
</dependency>

然后写了一个测试类来测试是否成功生成

import com.lowagie.text.pdf.BaseFont;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Created by hongzhenyue on 18/2/28.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Html2PdfTest {
    @Test
    public void testHtml2Pdf() throws Exception{
        //指定PDF的存放路径
        String outputFile = "/Users/hongzhenyue/Desktop/backup/spring_boot_demo/src/main/resources/file/test.pdf";
        OutputStream os = new FileOutputStream(outputFile);
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();
        //指定字体。为了支持中文字体
        fontResolver.addFont("font/arialunicodems.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        StringBuffer html = new StringBuffer();

        html.append("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\"></meta>\n" +
                "    <title>Issue Payment Receipt</title>\n" +
                "    <style type=\"text/css\">\n" +
                "    body {\n" +
                "        font-family: Arial Unicode MS;\n" +
                "    }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <img src=\"file/logo.png\" style=\"width:160px;height:80px;\"></img>\n" +
                "    <br/>\n" +
                "    <br/> 建設銀行\n" +
                "    <br/> 12345678901\n" +
                "    <br/> 1000RMB\n" +
                "    <br/> 姓名:李四\n" +
                "    <br/> 單號:123456\n" +
                "    <br/>\n" +
                "</body>\n" +
                "</html>");
        renderer.setDocumentFromString(html.toString());
        // 解决图片的相对路径问题
        renderer.getSharedContext().setBaseURL("file:/Users/hongzhenyue/Desktop/backup/spring_boot_demo/src/main/resources/file");
        renderer.layout();
        renderer.createPDF(os);
        renderer.finishPDF();
        renderer = null;
        os.close();
    }
}


然后执行测试code,发现在file文件下面已经生成了一个PDF文件

java将html的图文转化为PDF文件输出

打开PDF

java将html的图文转化为PDF文件输出

可见已经输出了我们想要的东西,至此,我们很简单地将html转化成了PDF文件。