java原装代码完成pdf在线预览和pdf打印及下载

本文介绍了一种使用Java实现PDF在线预览、打印和下载的方法,涉及核心库的引入、自定义Tag类基类、配置接口、异常处理、TLD配置和Action及FTL模板文件的使用。通过自定义逻辑处理预览和打印的差异化需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是我在工作中,遇到这样需求,完成需求后,总结的成果,就当做是工作笔记,以免日后忘记,当然,能帮助到别人是最好的啦!下面进入正题:

  若有不正之处请多多谅解,并欢迎批评指正。

  请尊重作者劳动成果,转载请标明原文链接:


前提准备:

 

  1. 项目中至少需要引入的jar包,注意版本:

    a) core-renderer.jar

    b) freemarker-2.3.16.jar

    c) iText-2.0.8.jar

    d) iTextAsian.jar

上代码:

注释: 此类为自定义的Tag类的基类,在action中怎么放的数据,在ftl中就怎么取数据,简洁明了。

 1. 自定义Tag类的基类

复制代码
/**
 * 通用的生成pdf预览和生成打印的html文件
 * 
 * @author xg君
 * 
 */
public abstract class PDFTag extends BodyTagSupport {

    private static final long serialVersionUID = 1L;

    // 标签属性变量
    private String json = "";
    private String tempDir = "";
    // 非标签属性变量
    private Map<String, Object> rootMap = new HashMap<String, Object>();
    private String templateStr = null;
    private String freemarkereConfigurationBeanName = null;
    private String fileName = null;
    private String basePath = null;
    private String fileEncoding = "utf-8";

    @Override
    public int doStartTag() throws JspException {
        setConfigParams();
        WebApplicationContext application = WebApplicationContextUtils.getWebApplicationContext(pageContext
                .getServletContext());
        doServiceStart();
        String ctx = (String) pageContext.getAttribute("ctx");
        rootMap.put("ctx", ctx);
        Map<String, Object> map = parseJSON2Map(json);
        rootMap.putAll(map);
        if (freemarkereConfigurationBeanName == null) {
            try {
                throw new CstuException("FreemarkereConfigurationBeanName不能为空!");
            } catch (CstuException e) {
                e.printStackTrace();
            }
        }
        Configuration cptFreemarkereConfiguration = (Configuration) application
                .getBean(freemarkereConfigurationBeanName);
        try {
            if (templateStr == null) {
                throw new CstuException("模板文件不能为空!");
            }
            Template template = cptFreemarkereConfiguration.getTemplate(templateStr);
            if (basePath == null) {
                throw new CstuException("文件的基本路径(父路径)不能为空!");
            }
            File htmlPath = new File(tempDir + File.separator + basePath);
            if (!htmlPath.exists()) {
                htmlPath.mkdirs();
            }
            if (fileName == null) {
                throw new CstuException("生成的html文件名不能为空!");
            }
            File htmlFile = new File(htmlPath, File.separator + fileName);
            if (!htmlFile.exists()) {
                htmlFile.createNewFile();
            }
            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(htmlFile), fileEncoding));
            template.process(rootMap, out);
            out.flush();
            doServiceDoing();
            // 显示在页面
            template.process(rootMap, pageContext.getResponse().getWriter());
        } catch (Exception e) {
            e.printStackTrace();
        }

        doServiceEnd();
        return SKIP_BODY;
    }

    /**
     * 配置基础参数,如
     */
    public abstract void setConfigParams();

    /**
     * 业务处理方法-开始 填充数据
     * 
     * @return
     */
    public abstract void doServiceStart();

    /**
     * 业务处理方法-执行中 备用,可空实现,若rootMap中存在双份数据则可在此处填充判断条件
     * 
     * @return
     */
    public abstract void doServiceDoing();

    /**
     * 业务处理方法-结束 清空rootMap并调用垃圾回收,也可空实现
     * 
     * @return
     */
    public abstract void doServiceEnd();

    /**
     * 将元素放入rootMap中
     */
    public void putKV(String key, Object value) {
        rootMap.put(key, value);
    }

    /**
     * 将map放入rootMap中
     * 
     * @param m
     */
    public void putMap(Map m) {
        rootMap.putAll(m);
    }

    public void clear() {
        rootMap.clear();
        rootMap = null;
    }

    /**
     * 移除元素
     * 
     * @param key
     * @return
     */
    public Object remove(String key) {
        return rootMap.remove(key);
    }

    public static Map<String, Object> parseJSON2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject json = JSONObject.fromObject(jsonStr);
        for (Object k : json.keySet()) {
            Object v = json.get(k);
            if (v instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                Iterator<JSONObject> it = ((JSONArray) v).iterator();
                while (it.hasNext()) {
                    JSONObject json2 = it.next();
                    list.add(parseJSON2Map(json2.toString()));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }

    public String getJson() {
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }

    public String getTempDir() {
        return tempDir;
    }

    public void setTe
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值