生成world文本后进行批量打印及预览

1 篇文章 0 订阅
1 篇文章 0 订阅

使用freemaker中ftl生成world文件

package com.finance.common.utils;

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

import javax.imageio.ImageIO;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Sides;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.*;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class PrintImage {


    private Font font     = new Font("黑体", Font.PLAIN, 25); // 添加字体的属性设置

    private Graphics2D g        = null;

    private int        fontsize = 0;

    /**
     * 导入本地图片到缓冲区
     */
    public BufferedImage loadImageLocal(String imgName) {
        try {
            return ImageIO.read(new File(imgName));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 导入网络图片到缓冲区
     */
    public BufferedImage loadImageUrl(String imgName) {
        try {
            URL url = new URL(imgName);
            return ImageIO.read(url);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 生成新图片到本地
     */
    public void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                ImageIO.write(img, "jpg", outputfile);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
    
    //获取所有可以使用的打印机
    private static List<String> getPrinterList(){
        List<String> strings =new ArrayList<>();
        HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        //查找所有的可用的打印服务
        PrintService[] printService = PrintServiceLookup.lookupPrintServices(flavor, pras);

        for (int i =0; i<printService.length ;i++ )
        {
            strings.add(printService[i].getName());
        }
        return strings;
    }

    // 传入文件和打印机名称
    public static void JPGPrint(File file,String printerName) throws PrintException {
        if (file == null) {
            System.err.println("缺少打印文件");
        }
        InputStream fis = null;
        try {
            // 设置打印格式,如果未确定类型,可选择autosense
            DocFlavor flavor = DocFlavor.INPUT_STREAM.JPEG;
            // 设置打印参数
            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            aset.add(new Copies(1)); //份数
            //aset.add(MediaSize.ISO.A4); //纸张
            // aset.add(Finishings.STAPLE);//装订
            aset.add(Sides.DUPLEX);//单双面
            // 定位打印服务
            PrintService printService = null;
            if (printerName != null) {
                //获得本台电脑连接的所有打印机
                PrintService[] printServices = PrinterJob.lookupPrintServices();
                if(printServices == null || printServices.length == 0) {
                    System.out.print("打印失败,未找到可用打印机,请检查。");
                    return ;
                }
                //匹配指定打印机
                for (int i = 0;i < printServices.length; i++) {
                    System.out.println(printServices[i].getName());
                    if (printServices[i].getName().contains(printerName)) {
                        printService = printServices[i];
                        break;
                    }
                }
                if(printService==null){
                    System.out.print("打印失败,未找到名称为" + printerName + "的打印机,请检查。");
                    return ;
                }
            }
            fis = new FileInputStream(file); // 构造待打印的文件流
            Doc doc = new SimpleDoc(fis, flavor, null);
            DocPrintJob job = printService.createPrintJob(); // 创建打印作业
            job.print(doc, aset);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } finally {
            // 关闭打印的文件流
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    //打印pdf
    public static  int printWorldToPdf(String fileUrl){
        System.out.println("开始打印");
        //将world转换为pdf进行打印
        AsposeUtil.wordToPdf(fileUrl, fileUrl.replaceAll(".doc",".pdf"));
        //打印pdf
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile(fileUrl.replaceAll(".doc",".pdf"));
        PdfPageBase pb = pdf.getPages().add(); //新增一页
        pdf.getPages().remove(pb); //去除第一页水印
        PrinterJob loPrinterJob = PrinterJob.getPrinterJob();
        PageFormat loPageFormat  = loPrinterJob.defaultPage();
        Paper loPaper = loPageFormat.getPaper();

        //删除默认页边距
        loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight());

        //设置打印份数
        loPrinterJob.setCopies(1);

        loPageFormat.setPaper(loPaper);
        loPrinterJob.setPrintable(pdf,loPageFormat);
        try {
            loPrinterJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
        System.out.println("打印成功");
        return 1;
    }


    public static void main(String[] args) {
        printWorldToPdf("D:\\text.doc");
    }
}


方法调用进行打印

@Override
    public String printBill(String billIdStr,Integer type,Integer printOrPrevicw) {
        String[] billIds=billIdStr.split(",");
        for (String billId:billIds){
            Map map=billMapper.printBillSql("call ECONLENDING.P_R_BillMain('"+billId+"')");
            List<Map> maps=billMapper.printBillListSql("call ECONLENDING.P_R_BillJSList('"+billId+"')");
            BigDecimal bigDecimal = new BigDecimal(0);
            for (Map map1:maps){
                bigDecimal=bigDecimal.add((BigDecimal) map1.get("YSAMOUNT"));
            }
            //计算合计
            map.put("jsAmountCount",bigDecimal);
            map.put("billJSList",maps);
            map.put("billAccountList",billMapper.printBillListSql("call ECONLENDING.P_BillAccount('"+billId+"')"));
            map.put("billLoanGuaList",billMapper.printBillListSql("select concat('抄送:',b.ORGNAME) ORGNAME, concat('担保比例:',round(a.GUASCALE, 2),'%') GUASCALE from ECONLENDING.T_LOANGUA a inner join ECONLENDING.T_LOANORG b on a.ORGID=b.ORGID where a.LOAID='"+billId+"'"));
            String fileUrl="";
            if (type==1){
                fileUrl=DocumentHandler.craeteTemplantWorld(map,"type1.ftl",getFileUrl+DateUtils.dateyyyyMMdd()+"\\",UUIDUtil.getUUID32()+".doc");
            }else if (type==2){
                fileUrl=DocumentHandler.craeteTemplantWorld(map,"type2.ftl",getFileUrl+DateUtils.dateyyyyMMdd()+"\\",UUIDUtil.getUUID32()+".doc");
            }else {
                fileUrl=DocumentHandler.craeteTemplantWorld(map,"type3.ftl",getFileUrl+DateUtils.dateyyyyMMdd()+"\\",UUIDUtil.getUUID32()+".doc");
            }
            if (printOrPrevicw==1){
                //预览时返回文件地址,否则返回空,无用
                AsposeUtil.wordToPdf(fileUrl, fileUrl.replaceAll(".doc",".pdf"));
                //判断是预览时返回路径
                return "http://"+systemIp+":8006/state/bill/showPdf?fileName="+fileUrl.replaceAll(".doc",".pdf").replaceAll("\\\\","%5C");
            }
            //将生成的doc转换为pdf进行打印
            if (StringUtils.isNotEmpty(fileUrl) && printOrPrevicw==0){
                PrintImage.printWorldToPdf(fileUrl);
            }
        }

        return "";
    }

type2.ftl文件中代码
直接读取map中的值

${SOURCENAME}

循环

<#list billJSList as js>
	${js.FITEMNAME}
</#list>

对pdf预览,直接在浏览器 中打开

 	//预览pdf
    @RequestMapping("/showPdf")
    public void showPdf(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/pdf");
        FileInputStream in;
        OutputStream out;
        try {
            //根据返回的全路径获取文件
            in = new FileInputStream(new File(request.getParameter("fileName")));
            out = response.getOutputStream();
            byte[] b = new byte[512];
            while ((in.read(b)) != -1) {
                out.write(b);
            }
            out.flush();
            in.close();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

预览图片

//通过produces 告知浏览器我要返回的媒体类型
@GetMapping(value = "/showImage", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_PNG_VALUE})
@ApiOperation("获取图片-返回BufferedImage")
public byte[] getImage2(String fileName) throws IOException {
    SysBusFiles sysBusFiles= iSysBusFileService.selectBusFilesById(fileName);
    File file = new File(sysBusFiles.getServerPath());
    FileInputStream inputStream = new FileInputStream(file);
    byte[] bytes = new byte[inputStream.available()];
    inputStream.read(bytes, 0, inputStream.available());
    return bytes;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值