Java实现打印功能

Java实现打印功能

网上找了一些资料,虽然资料不是很多,自己整理一下,改巴改巴还是很好用的,只需要一个util类即可,详细代码附上:

maven依赖:
<dependency>
	<groupId>com.itextpdf</groupId>
    <artifactId>itext7-core</artifactId>
    <version>7.0.2</version>
    <type>pom</type>
</dependency>
Java代码:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.color.DeviceRgb;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.layout.Document;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import org.springframework.stereotype.Component;

/**
 * @Author Mr.H
 * @Date 2020/01/13 17:22
 * @Version 1.0
 */
@Component
public class PrinterUtil {

    /**
     *
     * @param response
     * @param List<Map<String,Object>> list 数据内容
     * @param keys list中map的key数组集合
     * @param columnNames 列名
     */
    public static void doPost(HttpServletResponse response,List<Map<String, Object>> list,String[] keys, String[] columnNames,String tableName) {
        try {
            //定义响应头返回类型 这里为返回文件 text.pdf
            response.addHeader("Content-Disposition", "attachment;filename=test.pdf");
            //新建一个输出流
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            //pdfWriter 使用传递输出流为参数的构造函数
            PdfWriter writer = new PdfWriter(bao);
            PdfDocument pdfDoc = new PdfDocument(writer);
            //构建文档对象,可以设置PageSize.A1——A4纸大小
            Document doc = new Document(pdfDoc, PageSize.A3);
            doc.setMargins(10, 10, 10, 10); //设置外边距
            //设置字体
            PdfFont sysFont = PdfFontFactory.createFont("C:\\Windows\\Fonts\\simsun.ttc,0", PdfEncodings.IDENTITY_H, false);
            // new Paragraph("")   添加标题、段落           
            doc.add(new Paragraph(tableName).setFont(sysFont).setTextAlignment
                    (TextAlignment.CENTER).setFontSize(20l).setBold());
            //构建表格宽度100%
            // newfloat[] {1,1,1,1 }声明数组,有多少个值就有多少列,里面的值代表对应列的宽度比例;给4个1代表4列   1值是宽度
            Table table = new Table(new float[]{columnNames.length}).setWidth(UnitValue.createPercentValue(100));
            //添加表头new Cell(1,1)意思是合并单元格几行几列  前面的代表列,后面参数是行,setBackgroundColor颜色的值    setPaddingTop文字垂直居中
            for (int i = 0; i < columnNames.length; i++) {
                Cell cell = new Cell(1, 1).add(new Paragraph(columnNames[i])).setFont(sysFont).setTextAlignment
                        (TextAlignment.CENTER).setBackgroundColor(new DeviceRgb(221, 234, 238)).setPaddingTop(14f);
                table.addHeaderCell(cell);
            }
            //向表格添加数据
            for (int i = 0; i < list.size(); i++) {
                for (short j = 0; j < keys.length; j++) {
                    Cell cell = new Cell().add(new Paragraph(list.get(i).get(keys[j]) == null ? " " : list.get(i).get(keys[j]).toString()))
                            .setFont(sysFont).setTextAlignment(TextAlignment.CENTER);
                    table.addCell(cell);
                }
            }
            //将表格添加入文档并页面居中
            doc.add(table.setHorizontalAlignment(HorizontalAlignment.CENTER));
            doc.close();//关闭对象
            //将输出流转换为输入流
            ByteArrayInputStream swapStream = new ByteArrayInputStream(bao.toByteArray());
            ServletOutputStream out = response.getOutputStream();
            byte[] buffer = new byte[1024];//定义byte数组
            int count;
            //循环输出流
            while ((count = swapStream.read(buffer)) != -1) {
                out.write(buffer, 0, count);
            }
            //关闭流
            out.flush();
            out.close();
            swapStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

另外注意:

//解决中文字体问题
PdfFont sysFont = PdfFontFactory.createFont(“STSongStd-Light”, “UniGB-UCS2-H”, false);

这种方式解决中文字体会报错

暂时就这么多了,下次在分享,疑惑可以留言,好用留个赞,阿里嘎多三克油!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值