java导出word和pdf

package org.wican.company.approval.utils;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.wican.company.utils.pdfUtils.Word2PdfAsposeUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
import static org.wican.company.utils.pdfUtils.Word2PdfAsposeUtil.getLicense;

/**
 * @Description:
 * @Author: guoxingzhan
 * @Date:
 * @Version: V1.0
 */
public class ExportBootsUtils {


    /**
     * @Title exportBootsDoc1
     * @Description 导出-word - 非pdf
     * @author guoxingzhan
     * @date 2023/3/13 9:53
     * @param map
     * @param response
     * @param wordPath 模板路径
     * @return
     */
    public static void exportsDoc(Map<String, Object> map, HttpServletResponse response, String wordPath) throws Exception {
        exportsDoc(map, response, wordPath, false);
    }
    /**
     * @Title exportBootsDoc2
     * @Description 导出-word - 可选pdf
     * @author guoxingzhan
     * @date 2023/3/13 9:53
     * @param map
     * @param response
     * @param wordPath 模板路径
     * @return
     */
    public static void exportsDoc(Map<String, Object> map, HttpServletResponse response, String wordPath, Boolean isPdf) throws Exception {
        exportsDoc(map, response, wordPath, null, isPdf);
    }

    /**
     * @Title exportBootsDoc3
     * @Description 导出-word - 非pdf
     * @author guoxingzhan
     * @date 2023/3/13 9:53
     * @param map
     * @param response
     * @param wordPath 模板路径
     * @param fileName 文件名称
     * @return
     */
    public static void exportsDoc(Map<String, Object> map, HttpServletResponse response, String wordPath, String fileName, Boolean isPdf) throws Exception {
        exportsDoc(map, response, wordPath, fileName, null, isPdf);
    }

    /**
     * @Title exportBootsDoc5
     * @Description 导出-word
     * @author guoxingzhan
     * @date 2023/3/13 9:53
     * @param map 数据
     * @param response
     * @param wordPath 模板路径
     * @param fileName 文件名称
     * @param filePath 临时文件路径
     * @return
     */
    public static void exportsDoc(Map<String, Object> map, HttpServletResponse response, String wordPath, String fileName, String filePath, Boolean isPdf) throws Exception {
        if(fileName == null){
            fileName = "demo";
        }
        cn.afterturn.easypoi.word.parse.ParseWord07 pw07 = new cn.afterturn.easypoi.word.parse.ParseWord07();
//			/*XWPFDocument xwpfDocument = pw07.parseWord(doc,map);*/
        XWPFDocument doc = pw07.parseWord(wordPath, map);
//			XWPFDocument doc = WordExportUtil.exportWord07(wordPath, map);

		setPageMargin(doc, 567, 567, 567, 567);
        doc.getTables()
                .forEach(xwpfTable -> xwpfTable.getRows()
                        .forEach(xwpfTableRow -> xwpfTableRow.getTableCells()
                                .forEach(item->{
                                    addBreakInCell(item);
                                })));
        if(isPdf){
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            doc.write(bos);
            if(filePath != null){
                exportPDF(bos.toByteArray(),response, filePath, fileName);
            }else{
                InputStream ins = null;
                OutputStream out = null;
                ins = new ByteArrayInputStream(bos.toByteArray());
                response.setContentType("application/vnd.ms-word");
                // 设置一个响应头,无论是否被浏览器解析,都下载
                response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName + ".pdf", "utf-8"));
                out = response.getOutputStream();
                //word转pdf
                Word2PdfAsposeUtil.doc2pdf(ins,out);
            }
        }else{
            response.setContentType("application/vnd.ms-excel");
            // 设置一个响应头,无论是否被浏览器解析,都下载
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName + ".docx", "utf-8"));
            // 将要下载的文件内容通过输出流写到浏览器
            OutputStream bos = response.getOutputStream();
            doc.write(bos);
        }
    }

    /**
     * @Title exportBootsPDF
     * @Description 导出-pdf
     * @author guoxingzhan
     * @date 2023/3/13 9:54
     * @param brray
     * @param response
     * @param filePath 临时文件路径
     * @param fileName 文件名称
     * @return
     */
    public static void exportPDF(byte[] brray, HttpServletResponse response, String filePath, String fileName) {
        OutputStream os = null;
        BufferedInputStream bis = null;
        FileInputStream fis = null;
        try {
            //去掉水印
            getLicense();
            //将输出流转输入流
            InputStream is = new ByteArrayInputStream(brray);
            File file = new File(filePath);
            //输出PDF路径
            com.aspose.words.Document document = new com.aspose.words.Document(is);
            FileOutputStream fileOS = new FileOutputStream(file);
            // 转换为pdf
            document.save(fileOS, com.aspose.words.SaveFormat.PDF);
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".pdf", "UTF-8"));
            response.setContentType("application/pdf");
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            file.delete();//删除生产的文件
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
/**
	 * 设置页边距
	 *
	 * @param document doc对象
	 * @param left     左边距
	 * @param right    右边距
	 * @param top      上边距
	 * @param bottom   下边距
	 */
	public static void setPageMargin(XWPFDocument document,
									 long left,
									 long right,
									 long top,
									 long bottom) {
		CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
		CTPageMar pageMar = sectPr.addNewPgMar();
		pageMar.setLeft(BigInteger.valueOf(left));
		pageMar.setRight(BigInteger.valueOf(right));
		pageMar.setTop(BigInteger.valueOf(top));
		pageMar.setBottom(BigInteger.valueOf(bottom));
	}

    /**
     * @param cell
     * @return void
     * @Title: addBreakInCell
     * @Description: 处理文字中有\n换行符生产的文件并没换行的情况
     * @author: yinzhixing
     * @date 2021/3/31 10:52
     **/
    public static void addBreakInCell(XWPFTableCell cell) {
        if (cell.getText() != null && cell.getText().contains("\n")) {
            for (XWPFParagraph p : cell.getParagraphs()) {
                for (XWPFRun run : p.getRuns()) {//XWPFRun对象定义具有一组公共属性的文本区域
                    if (run.getText(0) != null && run.getText(0).contains("\n")) {
                        String[] lines = run.getText(0).split("\n");
                        if (lines.length > 0) {
                            run.setText(lines[0], 0); // set first line into XWPFRun
                            for (int i = 1; i < lines.length; i++) {
                                // add break and insert new text
                                run.addBreak();//中断
//				                    run.addCarriageReturn();//回车符,但是不起作用
                                run.setText(lines[i]);
                            }
                        }
                    }
                }
            }
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值