栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java快速实现导出PDF功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java快速实现导出PDF功能

组件学习—导出PDF 一、制作word模板,这里需要文件后缀默认是.docx,${xxxx}是需要替换的内容

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uNCLy3Fb-1658302114457)(C:Users86159AppDataRoamingTyporatypora-user-imagesimage-20220720135810683.png)]

二、添加poi所需要的jar包文件,这里使用maven进行jar包管理

jacob jar包下载地址:https://sourceforge.net/projects/jacob-project/?source=typ_redirect

       
        
            org.apache.poi
            poi
            4.0.0
        

        
            org.apache.poi
            poi-scratchpad
            4.0.0
        

        
            org.apache.poi
            poi-ooxml
            4.0.0
        

        
        
            org.apache.poi
            poi-ooxml-schemas
            4.0.0
        

        
            com.jacob
            jacob
            1.19
            system
            ${project.basedir}/src/main/resources/lib/jacob.jar
        
        
三、添加导出word,word转pdf 的工具类,(这里暂时忽略图片的功能,后期会总结添加!!!)
package com.yumc.rdf.common.util;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import org.apache.poi.xwpf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class WordUtils {

    
    public static int judgment = 0;

    public WordUtils() {
        judgment = 0;
    }

    
    public void getWord(String path, Map params, List tableList, String fileName,
                        HttpServletResponse response) throws Exception {
//        String saveRoute = path.substring(0, path.indexOf("\"));

        File file = new File(path);
        InputStream is = new FileInputStream(file);
        CustomXWPFDocument doc = new CustomXWPFDocument(is);

        this.replaceInPara(doc, params); // 替换文本里面的变量
        this.replaceInTable(doc, params, tableList); // 替换表格里面的变量
        OutputStream os = null;
        if (judgment == 0) {
            fileName = java.net.URLDecoder.decode(fileName, "UTF-8");
            os = new FileOutputStream( "C:/Users/86159/Desktop/" + fileName);

            doc.write(os);

            String pdf = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf"; // 截掉
            wToPdfChange("C:/Users/86159/Desktop/" + fileName, "C:/Users/86159/Desktop/" + pdf);

            try {
                System.out.println("========================pdf下载开始========================");
                // path是指欲下载的文件的路径。
                file = new File("C:/Users/86159/Desktop/" + pdf);
                // 取得文件名。
                String filename = URLEncoder.encode(file.getName(), "utf-8");
                // 取得文件的后缀名。
                String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
                // 以流的形式下载文件。
                is = new BufferedInputStream(new FileInputStream("C:/Users/86159/Desktop/" + pdf));
                byte[] buffer = new byte[is.available()];
                is.read(buffer);
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + filename);
                response.addHeader("Content-Length", "" + file.length());
                os = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                os.write(buffer);
                os.flush();
                System.out.println("========================pdf下载结束========================");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else {
            os = response.getOutputStream();
            fileName = java.net.URLDecoder.decode(fileName, "UTF-8");
            os = new FileOutputStream("C:/Users/86159/Desktop/" + fileName);
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(), "ISO8859-1") );
            doc.write(os);
            judgment = 0;
        }

        this.close(os);
        this.close(is);
    }

    
    public static void wToPdfChange(String wordFile, String pdfFile) {
        ActiveXComponent app = null;
        Dispatch document = null;
        System.out.println("========================开始转换========================");
        try {
            // 打开word
            System.out.println("开始打开word");
            app = new ActiveXComponent("Word.Application");

            // 获得word中所有打开的文档
            Dispatch documents = app.getProperty("Documents").toDispatch();
            System.out.println("打开文件: " + wordFile);
            // 打开文档
            document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
            // 如果文件存在的话,不会覆盖,会直接报错,所以我们需要判断文件是否存在
            File target = new File(pdfFile);
            if (target.exists()) {
                target.delete();
            }
            System.out.println("另存为: " + pdfFile);
            Dispatch.call(document, "SaveAs", pdfFile, 17);
        } catch (Exception e) {
            System.out.println("转换失败" + e.getMessage());
        } finally {
            // 关闭office
//			app.invoke("Quit", 0);

            if (document != null) {
                // 关闭文档
                Dispatch.call(document, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit", 0);
            }

            // 获取系统类型
            String osName = System.getProperty("os.name");
            // 判断是系统类型
            if (osName.toLowerCase().startsWith("win")) {
                System.out.println(osName);
                // window系统
                String killCmd = "taskkill /f /im wps.exe";
                String killCmd1 = "taskkill /f /im wpscenter.exe";
                Process p;
                try {
                    p = Runtime.getRuntime().exec(killCmd);
                    p = Runtime.getRuntime().exec(killCmd1);
                    int runnngStatus = p.waitFor();
                    System.out.println("已杀" + runnngStatus);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("转换失败" + e.getMessage());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("转换失败" + e.getMessage());
                }
            }
        }
        System.out.println("========================转换结束========================");
    }

    
    private void replaceInPara(CustomXWPFDocument doc, Map params) {
        Iterator iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while (iterator.hasNext()) {
            para = iterator.next();
            this.replaceInPara(para, params, doc);
        }
    }

    
    private void replaceInPara(XWPFParagraph para, Map params, CustomXWPFDocument doc) {
        List runs;
        Matcher matcher;
        if (this.matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            int start = -1;
            int end = -1;
            String str = "";
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                String runText = run.toString();
                if ('$' == runText.charAt(0) && '{' == runText.charAt(1)) {
                    start = i;
                }
                if ((start != -1)) {
                    str += runText;
                }
                if ('}' == runText.charAt(runText.length() - 1)) {
                    if (start != -1) {
                        end = i;
                        break;
                    }
                }
            }

            for (int i = start; i <= end; i++) {
                para.removeRun(i);
                i--;
                end--;
            }

            for (Map.Entry entry : params.entrySet()) {
                String key = entry.getKey();
                if (str.indexOf(key) != -1) {
                    Object value = entry.getValue();
                    if (value instanceof String) {
                        str = str.replace(key, value.toString());
                        para.createRun().setText(str, 0);
                        break;
                    } else if (value instanceof Map) {
                        str = str.replace(key, "");
                        Map pic = (Map) value;
                        int width = Integer.parseInt(pic.get("width").toString());
                        int height = Integer.parseInt(pic.get("height").toString());
                        int picType = getPictureType(pic.get("type").toString());
                        byte[] byteArray = (byte[]) pic.get("content");
                        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
                        try {
                            //int ind = doc.addPicture(byteInputStream,picType);
                            //doc.createPicture(ind, width , height,para);
                            doc.addPictureData(byteInputStream, picType);
//                            doc.createPicture(doc.getAllPictures().size() - 1, width, height, para);
                            para.createRun().setText(str, 0);
                            break;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }


    
    private static void insertTable(XWPFTable table, List tableList) {
        //创建行,根据需要插入的数据添加新行,不处理表头
        for (int i = 0; i < tableList.size(); i++) {
            XWPFTableRow row = table.createRow();
        }
        //遍历表格插入数据
        List rows = table.getRows();
        int length = table.getRows().size();
        for (int i = 1; i < length - 1; i++) {
            XWPFTableRow newRow = table.getRow(i);
            List cells = newRow.getTableCells();
            for (int j = 0; j < cells.size(); j++) {
                XWPFTableCell cell = cells.get(j);
                String s = tableList.get(i - 1)[j];
                cell.setText(s);
            }
        }
    }

    
    private void replaceInTable(CustomXWPFDocument doc, Map params, List tableList) {
        Iterator iterator = doc.getTablesIterator();
        XWPFTable table;
        List rows;
        List cells;
        List paras;
        while (iterator.hasNext()) {
            table = iterator.next();
            if (table.getRows().size() > 1) {
                //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入
                if (this.matcher(table.getText()).find()) {
                    rows = table.getRows();
                    for (XWPFTableRow row : rows) {
                        cells = row.getTableCells();
                        for (XWPFTableCell cell : cells) {
                            paras = cell.getParagraphs();
                            for (XWPFParagraph para : paras) {
                                this.replaceInPara(para, params, doc);
                            }
                        }
                    }
                } else {
                    insertTable(table, tableList);  //插入数据
                }
            }
        }
    }


    
    private Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\$\{(.+?)\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

    
    public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
        byte[] byteArray = null;
        try {
            int total = in.available();
            byteArray = new byte[total];
            in.read(byteArray);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (isClose) {
                try {
                    in.close();
                } catch (Exception e2) {
                    e2.getStackTrace();
                }
            }
        }
        return byteArray;
    }


    
    private void close(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    
    private void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

四、在第三步,word转pdf文件需要添加一个jacob.jar包,可以将jacob.jar包放入项目中的resources 文件下的lib中,然后maven通过项目路径引入本地jar包

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PnM84k3i-1658302114459)(C:Users86159AppDataRoamingTyporatypora-user-imagesimage-20220720135523781.png)]


    com.jacob
    jacob
    1.19
    system
    ${project.basedir}/src/main/resources/lib/jacob.jar

同时需要将jacob中的dll文件放到自己的jdk环境中,将 dll 文件拷贝到本地 jre/bin路径下

五、最后进行测试就可以啦
    @Override
    public void exportOrderInfo(HttpServletRequest request, HttpServletResponse response, String orderCode){
        WordUtils wordUtil=new WordUtils();
        //获取订单信息
        OrderDetailVO order = orderMapper.queryOrderDetail(orderCode);
        //动态添加费用详情  测试用例
        List costList = new ArrayList<>();
        OrderCostDetailVO cost = new OrderCostDetailVO();
        cost.setNumber("2");
        cost.setContent("测试服务内容");
        cost.setTotalHour(BigDecimal.valueOf(20));
        cost.setSupplierUnitPrice(BigDecimal.valueOf(2440));
        cost.setOrderAmount(BigDecimal.valueOf(48800));
        cost.setRemark("测试可否动态添加费用详情");
        costList.add(cost);

        Map params = new HashMap();
        params.put("${firstPartyName}", order.getFirstPartyName());
        params.put("${secondPartyName}", order.getSupplierName());
        params.put("${pmName}", order.getFirstPmName());
        params.put("${supplierName}", order.getSupplierName());
        params.put("${place}", order.getDeliveryPlace());
        params.put("${orderEffectiveDate}", TimeUtil.getTimeInFormat(order.getOrderEffectiveDate(), "yyyy-MM-dd"));

        if(order.getOrderType() == 0){
            params.put("${systemName}",order.getSystemName());
            params.put("${tax}", "增值税专用发票" + order.getTax().toString()+"%");
        }else if(order.getOrderType() == 1){
            params.put("${systemName}",order.getSystemName());
            params.put("${tax}", "增值税电子普通发票"+ order.getTax().toString()+"%");
        }else{
            params.put("${systemName}",order.getDemandName());
            params.put("${tax}", "普通发票"+ order.getTax().toString()+"%");
        }
        params.put("${orderAmount}",order.getOrderAmount().toString());
        params.put("${totalAmount}",order.getOrderAmount().toString());
        params.put("${totalHour}",order.getTotalHour().toString());

        try{
            List testList = new ArrayList();
            testList.add(new String[]{"1",order.getSystemName(),order.getSupplierUnitPrice().toString(),order.getTotalHour().toString()
                    ,order.getOrderAmount().toString(),order.getDemandDescription()});
            for (OrderCostDetailVO detail:costList) {
            testList.add(new String[]{detail.getNumber(), detail.getContent(), detail.getSupplierUnitPrice().toString(),detail.getTotalHour().toString(),
            detail.getOrderAmount().toString(), detail.getRemark()});
            }
            String path="C:/Users/86159/Desktop/srb-test.docx";  //模板文件位置
            String fileName= new String((orderCode+".docx").getBytes("UTF-8"),"iso-8859-1");    //生成word文件的文件名
            wordUtil.getWord(path,params,testList,fileName,response);

        }catch(Exception e){
            e.printStackTrace();
        }
    }
六、最后生成的PDF文档

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-P3ycRowR-1658302114460)(C:Users86159AppDataRoamingTyporatypora-user-imagesimage-20220720140058661.png)]

今天组件使用小结,还有图片格式未实现,继续加油吖~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1020427.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号