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

使用itextpdf批量打印学生信息

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

使用itextpdf批量打印学生信息

使用itextpdf批量打印学生信息
  • maven依赖
    • pdf工具
    • 打印工具

maven依赖
    
        com.itextpdf
        itextpdf
        5.5.13
    
    
    
        com.itextpdf
        itext-asian
        5.2.0
    
pdf工具

public class PdfUtil {
// 定义全局的字体静态变量
private static Font titlefont;
private static Font headfont;
private static Font keyfont;
private static Font textfont;
private static Font textfont1;
// 最大宽度
private static int maxWidth = 520;
// 静态代码块
static {
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
baseFont bfChinese = baseFont.createFont(“STSong-Light”, “UniGB-UCS2-H”, baseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 15, Font.NORMAL);
textfont1 = new Font(bfChinese, 12, Font.NORMAL);
headfont = new Font(bfChinese, 10, Font.NORMAL);
keyfont = new Font(bfChinese, 10, Font.NORMAL);
textfont = new Font(bfChinese, 10, Font.NORMAL);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

// 生成PDF文件
public static void generatePDF(List list, String title) throws Exception {
    int code = 0;
    Map printMap = new HashMap<>();
    System.out.println("此次打印数量:"+list.size());
    for (Student student : list) {
        code++;
        System.out.println("当前孩子:"+student.getStudentName()+"正在生成pdf,打印序号:"+code);
        // 1.新建document对象
        document document = new document(PageSize.A4);// 建立一个document对象
        // 2.建立一个书写器(Writer)与document对象关联
        String printUrl = "/Users/sim/Desktop/"+student.getSchoolName()+student.getGradeName()+student.getClassName()+"-"+student.getStudentName()+".pdf";
        File file = new File(printUrl);
        file.createNewFile();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        // 3.打开文档
        document.open();
        document.addTitle("sim");// 标题
        document.addAuthor("sim@umiz");// 作者
        document.addSubject("Ssim");// 主题
        document.addKeywords("sim");// 关键字
        document.addCreator("sim");// 创建者
        // 段落
        Paragraph paragraph = new Paragraph(title, titlefont);
        paragraph.setAlignment(1); //设置文字居中 0靠左   1,居中     2,靠右
        paragraph.setIndentationLeft(12); //设置左缩进
        paragraph.setIndentationRight(12); //设置右缩进
        paragraph.setFirstLineIndent(24); //设置首行缩进
        paragraph.setLeading(20f); //行间距
        paragraph.setSpacingBefore(50f); //设置段落上空白
        paragraph.setSpacingAfter(30f); //设置段落下空白
        // 表格
        PdfPTable table = createTable(new float[] { 100, 80, 80, 70, 70});
        table.addCell(newCreateCell("姓名:"+student.getStudentName(), 30f));
        table.addCell(newCreateCell("性别:"+student.getSexName(), 30f));
        table.addCell(newCreateCell("年龄:"+student.getAge(), 30f));
        table.addCell(newCreateCell("身高:"+student.getHeight()+"(m)",30f));
        table.addCell(newCreateCell("体重:"+student.getWeight()+("kg"), 30f));
        PdfPTable table1 = createTable(new float[] { 100, 80, 80, 70, 70});
        table1.addCell(newCreateCell("学校:"+student.getSchoolName(),30f));
        table1.addCell(newCreateCell("年级:"+student.getGradeName(),30f));
        table1.addCell(newCreateCell("班级:"+student.getClassName(),30f));
        table1.addCell(newCreateCell("BMI:"+student.getBmi(),30f));
        table1.addCell(newCreateCell("",20f));
        PdfPTable table2 = createTable(new float[] { 100, 300});
        table2.addCell(newCreateCell("体检结果",50f));
        String weightName = "";
        String heightName = "";
        if(!student.getWeightName().equals("正常")){
            weightName = "体重:"+student.getWeightName()+"(建议到儿童内分泌科或生长发育科复查)nn";
        }else {
            weightName = "体重:正常 (建议定期观察生长速率)nn";
        }
        if(!student.getHeightName().equals("正常")){
            heightName = "身高:"+student.getHeightName()+"(建议到儿童内分泌科或生长发育科复查)nn";
        }else {
            heightName = "身高:正常 (建议定期观察生长速率)";
        }
        table2.addCell(newCreateCell(weightName+heightName,50f));
        PdfPTable table3 = createTable(new float[] { 100, 300});
        table3.addCell(newCreateCell("温馨提示",180f));
        table3.addCell(newCreateCell("孩子的成长只有一次!我们建议:n" +
                "n" +
                "1、每天1-2小时户外运动。n" +
                "     在以下项目中选择一项或两项(跳绳、游泳、有氧跑、有氧韵律操、羽毛球、网球、篮球、排球等纵向体育运动)。n" +
                "n" +
                "2、合理饮食,吃饱吃好一日三餐,荤素搭配,可适当多吃点鱼类少吃肉类,每天确保一个鸡蛋、250-500ml牛奶及水果等。n" +
                "n" +
                "3、充足规律的睡眠,晚上熟睡后体内生长激素分泌旺盛,并有两个分泌高峰期,因此充足规律的睡眠有利于孩子更好的长高。n" +
                "n" +
                "4、给孩子创造一个快乐、心情舒畅的生活环境,让孩子保持乐观向上的心态,不要过于宠溺孩子,适当的规矩是对孩子最好的保护。",180f));
        Paragraph paragraph1 = new Paragraph("关爱儿童,呵护成长", textfont1);
        paragraph1.setAlignment(1); //设置文字居中 0靠左   1,居中     2,靠右
        paragraph1.setIndentationLeft(12); //设置左缩进
        paragraph1.setIndentationRight(12); //设置右缩进
        paragraph1.setFirstLineIndent(24); //设置首行缩进
        paragraph1.setLeading(20f); //行间距
        paragraph1.setSpacingBefore(50f); //设置段落上空白
        paragraph1.setSpacingAfter(10f); //设置段落下空白
        document.add(paragraph);
        document.add(table);
        document.add(table1);
        document.add(table2);
        document.add(table3);
        document.add(paragraph1);
        document.close();
        printMap.put(student.getStudentName(),printUrl);
    }
    System.out.println("pdf生成完成,准备开始打印");
    for(String key:printMap.keySet()){
        System.out.println("开始打印"+key+"的报告");
        String printUrl = printMap.get(key).toString();
        PrintUtil.defaultPrintPDF(printUrl);
        System.out.println("等待5s");
        Thread.sleep(5000);
    }

}


public PdfPCell createCell(String value, Font font) {
    PdfPCell cell = new PdfPCell();
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setPhrase(new Phrase(value, font));
    return cell;
}
public static PdfPCell newCreateCell(String value,float height){
    PdfPCell cell = new PdfPCell();
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
    cell.setPhrase(new Phrase(value, keyfont));
    cell.setFixedHeight(height);
    return cell;
}

public PdfPCell createCell(String value, Font font, int align) {
    PdfPCell cell = new PdfPCell();
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setHorizontalAlignment(align);
    cell.setPhrase(new Phrase(value, font));
    return cell;
}

public PdfPCell createCell(String value, Font font, int align, int colspan) {
    PdfPCell cell = new PdfPCell();
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setHorizontalAlignment(align);
    cell.setColspan(colspan);
    cell.setPhrase(new Phrase(value, font));
    return cell;
}

public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
    PdfPCell cell = new PdfPCell();
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setHorizontalAlignment(align);
    cell.setColspan(colspan);
    cell.setPhrase(new Phrase(value, font));
    cell.setPadding(3.0f);
    if (!boderFlag) {
        cell.setBorder(0);
        cell.setPaddingTop(15.0f);
        cell.setPaddingBottom(8.0f);
    } else if (boderFlag) {
        cell.setBorder(0);
        cell.setPaddingTop(0.0f);
        cell.setPaddingBottom(15.0f);
    }
    return cell;
}

public PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
    PdfPCell cell = new PdfPCell();
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.setHorizontalAlignment(align);
    cell.setPhrase(new Phrase(value, font));
    cell.setBorderWidthLeft(borderWidth[0]);
    cell.setBorderWidthRight(borderWidth[1]);
    cell.setBorderWidthTop(borderWidth[2]);
    cell.setBorderWidthBottom(borderWidth[3]);
    cell.setPaddingTop(paddingSize[0]);
    cell.setPaddingBottom(paddingSize[1]);
    if (flag) {
        cell.setColspan(2);
    }
    return cell;
}

public PdfPTable createTable(int colNumber, int align) {
    PdfPTable table = new PdfPTable(colNumber);
    try {
        table.setTotalWidth(maxWidth);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(align);
        table.getDefaultCell().setBorder(1);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return table;
}

public static PdfPTable createTable(float[] widths) {
    PdfPTable table = new PdfPTable(widths);
    try {
        table.setTotalWidth(maxWidth);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setBorder(1);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return table;
}

public PdfPTable createBlankTable() {
    PdfPTable table = new PdfPTable(1);
    table.getDefaultCell().setBorder(0);
    table.addCell(createCell("", keyfont));
    table.setSpacingAfter(20.0f);
    table.setSpacingBefore(20.0f);
    return table;
}
打印工具

public class PrintUtil {

public static void defaultPrintPDF(String filePath) throws Exception{
File file = new File(filePath); // 获取选择的文件
// 构建打印请求属性集
HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
// 设置打印格式,因为未确定类型,所以选择autosense
DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
//pras.add(MediaName.ISO_A4_TRANSPARENT);//A4纸张
//遍历
// PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
//
// for (PrintService printService2 : printService) {
// logger.info(“本机可使用打印机列表:===================”+printService2);
// }
// 定位默认的打印服务
PrintService defaultService = PrintServiceLookup
.lookupDefaultPrintService();
DocPrintJob job = defaultService.createPrintJob(); // 创建打印作业
FileInputStream fis = new FileInputStream(file); // 构造待打印的文件流
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
job.print(doc, pras);
}

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

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

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