html转pdf

html页面显示



生成pdf截图



废话少说 直接上代码

调用生成pdf的工具类

PdfUtil.htmlToPdf(filepath, url);//filepath:文件保存的路径,url:html页面地址

package com.hlmedicals.app.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;

/**
 * 对html的规范要求极高,例如:页面中<mate></mate>必须闭合,必须: <br />
 *
 * <pre>
 * <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 * "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html
 * xmlns="http://www.w3.org/1999/xhtml">
 *
 * @author zsj
 *
 */
public class PdfUtil {

    public static void main(String[] args) throws Exception {
        // String filePath = PdfUtil.class.getClassLoader().getResource("")
        // .toString()
        // + "simsun.ttc";
        // System.out.println(filePath.replaceAll("file:/", ""));
        // System.out.println(new File(filePath));
        htmlToPdf("/data/fs/sinspector/BJ20150522001.pdf",
                "http://localhost:9080/account/observerInforeport/BJ20150522001");
    }

    /**
     * 把URL转换为PDF
     *
     * @param outputFile
     *            , 示例:/data/fs/inspector/BJ20150522001.pdf
     * @param url
     *            ,示例:http :xxxx
     * @return
     * @throws Exception
     */
    public static boolean htmlToPdf(String outputFile, String url)
            throws Exception {
        File outFile = new File(outputFile);
        if (!outFile.exists()) {
            outFile.getParentFile().mkdirs();
        }
        
        
        
        OutputStream os = new FileOutputStream(outputFile);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
    
        String fontPath = PdfUtil.class.getClassLoader().getResource("")
                .toString().replaceAll("file:/", "")
                + "font/simsun.ttc";
        System.out.println(fontPath);
        // 解决中文支持问题
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont(fontPath, BaseFont.IDENTITY_H,
                BaseFont.NOT_EMBEDDED);
        // 支持BASE64图片
        renderer.getSharedContext().setReplacedElementFactory(new B64ImgReplacedElementFactory());
        renderer.layout();
        renderer.createPDF(os);
        System.out.println("ok");
        os.flush();
        os.close();
        return true;
    }

    public static void htmlToPdf(OutputStream os, String url)
            throws DocumentException, IOException {
        ITextRenderer renderer = new ITextRenderer();

        renderer.setDocument(url);
        String fontPath = PdfUtil.class.getClassLoader()
                .getResource("/simsun.ttc").getPath();
        System.out.println(fontPath);
        // 解决中文支持问题
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont(fontPath, BaseFont.IDENTITY_H,
                BaseFont.NOT_EMBEDDED);
        renderer.layout();
        renderer.createPDF(os);
        os.flush();
    }
}

//imgbase64解决

/**
 *
 */
package com.hlmedicals.app.util;

import java.io.IOException;

import org.bouncycastle.util.encoders.Base64;
import org.w3c.dom.Element;
import org.xhtmlrenderer.extend.FSImage;
import org.xhtmlrenderer.extend.ReplacedElement;
import org.xhtmlrenderer.extend.ReplacedElementFactory;
import org.xhtmlrenderer.extend.UserAgentCallback;
import org.xhtmlrenderer.layout.LayoutContext;
import org.xhtmlrenderer.pdf.ITextFSImage;
import org.xhtmlrenderer.pdf.ITextImageElement;
import org.xhtmlrenderer.render.BlockBox;
import org.xhtmlrenderer.simple.extend.FormSubmissionListener;

import com.lowagie.text.Image;  
import com.lowagie.text.BadElementException;

/**
 * @author dell
 *
 */
public class B64ImgReplacedElementFactory implements ReplacedElementFactory{

    /*
     *  
     * <p>Title: createReplacedElement</p>  
     * <p>Description: </p>  
     * <p>sql: </p>  
     *
     * @author  2016年11月1日 下午7:05:55
     *  
     * @param c 上下文
     * @param box 盒子
     * @param uac 回调
     * @param cssWidth css宽  
     * @param cssHeight css高
     * @return  
     * @see org.xhtmlrenderer.extend.ReplacedElementFactory#createReplacedElement(org.xhtmlrenderer.layout.LayoutContext, org.xhtmlrenderer.render.BlockBox, org.xhtmlrenderer.extend.UserAgentCallback, int, int)
     */  
    @Override  
    public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac, int cssWidth,  
            int cssHeight) {  
        Element e = box.getElement();  
        if (e == null) {  
            return null;  
        }  
        String nodeName = e.getNodeName();  
        // 找到img标签  
        if (nodeName.equals("img")) {  
            String attribute = e.getAttribute("src");  
            FSImage fsImage;  
            try { // 生成itext图像  
                fsImage = buildImage(attribute, uac);  
            } catch (BadElementException e1) {  
                fsImage = null;  
            } catch (IOException e1) {  
                fsImage = null;  
            }  
            if (fsImage != null) { // 对图像进行缩放  
                if (cssWidth != -1 || cssHeight != -1) {  
                    fsImage.scale(cssWidth, cssHeight);  
                }  
                return new ITextImageElement(fsImage);  
            }  
        }  
        return null;  
    }  
      
    /**
     *  
     * TODO(将base64编码解码并生成itext图像)  
     * @author 2016年11月1日 下午7:08:57   
     * @param srcAttr 属性
     * @param uac 回调  
     * @return
     * @throws IOException
     * @throws BadElementException
     */  
    protected FSImage buildImage(String srcAttr, UserAgentCallback uac) throws IOException, BadElementException {  
        FSImage fsImage;  
        if (srcAttr.startsWith("data:image/")) {  
            String b64encoded = srcAttr.substring(srcAttr.indexOf("base64,") + "base64,".length(), srcAttr.length()); // 解码  
            byte[] decodedBytes = Base64.decode(b64encoded);  
            fsImage = new ITextFSImage(Image.getInstance(decodedBytes));  
        } else {  
            fsImage = uac.getImageResource(srcAttr).getImage();  
        }  
        return fsImage;  
    }  
 
    @Override  
    public void remove(Element arg0) {  
        // TODO 自动生成的方法存根  
          
    }  
 
    @Override  
    public void reset() {  
        // TODO 自动生成的方法存根  
          
    }  
 
    @Override  
    public void setFormSubmissionListener(FormSubmissionListener arg0) {  
        // TODO 自动生成的方法存根  
          
    }  
}  


jsp文件:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/context/mytags.jsp"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" ></meta>
<title>电子处方</title>
<t:base type="jquery,easyui,tools,DatePicker"></t:base>
<script type="text/javascript" src="plug-in/jquery/jquery-1.8.3.js"></script>
<link href="plug-in/ace/assets/css/bootstrap.min.css" rel="stylesheet"/>
<link href="plug-in/ace/assets/css/bootstrap-table.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="plug-in/ace/assets/css/bootstrap-editable.css"/>
<script src="plug-in/ace/assets/js/bootstrap.min.js"></script>
<script src="plug-in/ace/assets/js/bootstrap-table.js"></script>
<script src="plug-in/ace/assets/js/bootstrap-table-zh-CN.min.js"></script>
<script src="plug-in/ace/assets/js/bootstrap-editable.js"></script>
<script src="plug-in/ace/assets/js/x-editable/bootstrap-table-editable.js"></script>

注意:汉字要在html指明字体

<body style="text-align:center;font-family:SimSun;">

 <span style="font-family:SimSun;">${hosptialname}</span>


还有运用jsoup把html的内容转成document在进行转换的

可参考

http://my.oschina.net/yifanxiang/blog/678139

同样也不支持   data:image base64

 参考

https://my.oschina.net/yifanxiang/blog/680936?p={{currentPage+1}}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值