实例演示(准考证制作)

package edu.ecnu.admission.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import edu.ecnu.admission.po.AdmissionTicket;

public class AdmissionDao {
	/**
	 *  批量添加准考证
	 * @param tickets
	 * @return
	 */
	public static int addAll(List<AdmissionTicket> tickets) {
		Connection conn = null;
        try {
            conn = ConnectionFactory.getConnection();
            conn.setAutoCommit(false);
            //构建数据库执行者
            PreparedStatement p = conn.prepareStatement("INSERT INTO `t_admission_ticket`(`name`, `candidate_number`, `id_number`, `gender`, `subject`, `address`, `time`, `seat`, `email`) " +
                    "VALUES ( ?, ?, ?, ?, ?, ?, ?, ?,?);");
	        for (AdmissionTicket at : tickets) {
	    	   p.setString(1, at.getName());
	    	   p.setString(2, at.getCandidateNumber());
	    	   p.setString(3, at.getIdNumber());
	    	   p.setString(4, at.getGender());
	    	   p.setString(5, at.getSubject());
	    	   p.setString(6, at.getAddress());
	    	   p.setString(7, at.getTime());
	    	   p.setString(8, at.getSeat());
	    	   p.setString(9, at.getEmail());
	    	   p.addBatch();
	        }
	        p.executeBatch();
	        conn.commit();
	        p.close();
        } catch (Exception e){
            e.printStackTrace();
            try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
            return -1;
        } finally {
        	try	{
        		if(null != conn) {
            		conn.close();
            	}
        	} catch (SQLException e){
                e.printStackTrace();
        	}        	
        }
        return 0;
	}


	/**
	 * 批量获取准考证
	 * @return
	 */
	public static List<AdmissionTicket> getAll() {
		List<AdmissionTicket> tickets = new ArrayList<>();
		Connection conn = null;
        try {
            conn = ConnectionFactory.getConnection();
            PreparedStatement p = conn.prepareStatement("select `name`, `candidate_number`, `id_number`, `gender`, `subject`, `address`, `time`, `seat`, `email` from `t_admission_ticket` ;");
            ResultSet rs = p.executeQuery();
            while(rs.next()){
            	AdmissionTicket ticket = new AdmissionTicket();
            	ticket.setName(rs.getString("name"));
            	ticket.setCandidateNumber(rs.getString("candidate_number"));
            	ticket.setIdNumber(rs.getString("id_number"));
            	ticket.setGender(rs.getString("gender"));
            	ticket.setSubject(rs.getString("subject"));
            	ticket.setAddress(rs.getString("address"));
            	ticket.setTime(rs.getString("time"));
            	ticket.setSeat(rs.getString("seat"));
            	ticket.setEmail(rs.getString("email"));
            	tickets.add(ticket);
            }
            p.close();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
        	try	{
        		if(null != conn) {
            		conn.close();
            	}
        	} catch (SQLException e){
                e.printStackTrace();
        	}        	
        }
        return tickets;
	}
}
package edu.ecnu.admission.data;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import edu.ecnu.admission.po.AdmissionTicket;

public class ConnectionFactory{

	
	private static DruidDataSource dataSource = null;
	/**
	 * 初始化连接池
	 * @throws Exception
	 */
	public static void init() throws Exception {
		Properties properties = new Properties();
		
		InputStream in = ConnectionFactory.class.getClassLoader().getResourceAsStream("druid.properties");  
		properties.load(in); 		
		dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);		
		
		in.close();
	}
	/**
	 * 获取链接
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection() throws Exception {
		if(null == dataSource)
		{
			init();
		}
        return dataSource.getConnection();
    }    
}
package edu.ecnu.admission.data;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import edu.ecnu.admission.po.AdmissionTicket;

public class Importer {
	public static List<AdmissionTicket> importFromExcel(String fileName) throws IOException {
		
		InputStream in = Importer.class.getClassLoader().getResourceAsStream(fileName);
		XSSFWorkbook workbook = new XSSFWorkbook(in);
		XSSFSheet sheet = workbook.getSheetAt(0);
		
        List<AdmissionTicket> admissionTickets = new ArrayList<>();
        
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            XSSFRow row = sheet.getRow(i);
            AdmissionTicket admissionTicket = new AdmissionTicket();
            int colIndex = 0;
            XSSFCell cell = row.getCell(colIndex++);
            admissionTicket.setName(getStringValue(cell));

            cell = row.getCell(colIndex++);
            admissionTicket.setCandidateNumber(getStringValue(cell));

            cell = row.getCell(colIndex++);
            admissionTicket.setIdNumber(getStringValue(cell));

            cell = row.getCell(colIndex++);
            admissionTicket.setGender(getStringValue(cell));

            cell = row.getCell(colIndex++);
            admissionTicket.setSubject(getStringValue(cell));

            cell = row.getCell(colIndex++);
            admissionTicket.setAddress(getStringValue(cell));

            cell = row.getCell(colIndex++);
            admissionTicket.setTime(getStringValue(cell));

            cell = row.getCell(colIndex++);
            admissionTicket.setSeat(getStringValue(cell));

            cell = row.getCell(colIndex++);
            admissionTicket.setEmail(getStringValue(cell));

            admissionTickets.add(admissionTicket);
        }
        workbook.close();
        
        return admissionTickets;
    }

    private static String getStringValue(Cell cell) {

    	if (cell == null) {
			return "";
		}
		String cellValue = "";
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_NUMERIC:
			if(HSSFDateUtil.isCellDateFormatted(cell)){
				Date d = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				return df.format(d);
			}
			else{
				DecimalFormat format = new DecimalFormat("####");
				cellValue = format.format(cell.getNumericCellValue());
			}
			break;
		case Cell.CELL_TYPE_STRING:
			cellValue = cell.getStringCellValue().trim().replaceAll("\\s{1,}", "");
			break;
		case Cell.CELL_TYPE_FORMULA:
			cellValue = String.valueOf(cell.getNumericCellValue());
		default:
			break;
		}
		return cellValue;
    }
}

postman

package edu.ecnu.admission.mail;

import edu.ecnu.admission.po.AdmissionTicket;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class Postman {

    private Session session = null;
    private Transport transport = null;

    public void init() throws Exception {
    	//设置邮件账号
        Properties props = new Properties();
        //设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");
        //设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        session = Session.getDefaultInstance(props);
        //设置调试信息在控制台打印出来
        session.setDebug(true);
        //3、创建邮件的实例对象
        //4、根据session对象获取邮件传输对象Transport
        transport = session.getTransport();
        //设置发件人的账户名和密码
        transport.connect("1102266271@qq.com", "iwtcyqtoyijlfghi");
    }

    public void close() throws Exception {
        transport.close();
    }

      
    public void sendAll(List<AdmissionTicket> tickets) throws Exception {
    	if(null == session)
    	{
    		init(); //初始化
    	}
    	
        for (AdmissionTicket ticket : tickets) {
        	System.out.println("get");
            Message msg = formatAdmissionTicket(ticket);
            //发送邮件,并发送到所有收件人地址,message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(msg, msg.getAllRecipients());
        }
    }

    private MimeMessage formatAdmissionTicket(AdmissionTicket ticket) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("1102266271@qq.com"));
        message.setRecipients(Message.RecipientType.TO, ticket.getEmail());
        message.setSubject("请查收准考证");
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("<p>请查收准考证</p>", "text/html;charset=UTF-8");
        MimeBodyPart attachment = new MimeBodyPart();
        byte[] data = readPdf(ticket.getCandidateNumber() + ".pdf");
        DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(data, "application/pdf"));
        attachment.setDataHandler(dataHandler);
        // 设置附件的文件名(需要编码)
        attachment.setFileName(MimeUtility.encodeText("准考证.pdf"));
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(attachment);
        mm.setSubType("mixed");
        message.setContent(mm);
        message.saveChanges();
        message.setHeader("Content-Transfer-Encoding", "base64");
        return message;
    }   
    
    private byte[] readPdf(String fileName) throws Exception
    {
    	InputStream in = new FileInputStream(new File(fileName));
    	byte[] bytes= null;
    	
    	bytes= new byte[in.available()];    //in.available()是得到文件的字节数
    	in.read(bytes);    //把文件的字节填充bytes数组中
    	in.close(); 
    	return bytes;
    }
}

po

package edu.ecnu.admission.mail;

import edu.ecnu.admission.po.AdmissionTicket;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class Postman {

    private Session session = null;
    private Transport transport = null;

    public void init() throws Exception {
    	//设置邮件账号
        Properties props = new Properties();
        //设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");
        //设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        session = Session.getDefaultInstance(props);
        //设置调试信息在控制台打印出来
        session.setDebug(true);
        //3、创建邮件的实例对象
        //4、根据session对象获取邮件传输对象Transport
        transport = session.getTransport();
        //设置发件人的账户名和密码
        transport.connect("1102266271@qq.com", "iwtcyqtoyijlfghi");
    }

    public void close() throws Exception {
        transport.close();
    }

      
    public void sendAll(List<AdmissionTicket> tickets) throws Exception {
    	if(null == session)
    	{
    		init(); //初始化
    	}
    	
        for (AdmissionTicket ticket : tickets) {
        	System.out.println("get");
            Message msg = formatAdmissionTicket(ticket);
            //发送邮件,并发送到所有收件人地址,message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(msg, msg.getAllRecipients());
        }
    }

    private MimeMessage formatAdmissionTicket(AdmissionTicket ticket) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("1102266271@qq.com"));
        message.setRecipients(Message.RecipientType.TO, ticket.getEmail());
        message.setSubject("请查收准考证");
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("<p>请查收准考证</p>", "text/html;charset=UTF-8");
        MimeBodyPart attachment = new MimeBodyPart();
        byte[] data = readPdf(ticket.getCandidateNumber() + ".pdf");
        DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(data, "application/pdf"));
        attachment.setDataHandler(dataHandler);
        // 设置附件的文件名(需要编码)
        attachment.setFileName(MimeUtility.encodeText("准考证.pdf"));
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(attachment);
        mm.setSubType("mixed");
        message.setContent(mm);
        message.saveChanges();
        message.setHeader("Content-Transfer-Encoding", "base64");
        return message;
    }   
    
    private byte[] readPdf(String fileName) throws Exception
    {
    	InputStream in = new FileInputStream(new File(fileName));
    	byte[] bytes= null;
    	
    	bytes= new byte[in.available()];    //in.available()是得到文件的字节数
    	in.read(bytes);    //把文件的字节填充bytes数组中
    	in.close(); 
    	return bytes;
    }
}
package edu.ecnu.admission.po;

public class ImageData {
    private byte[] data;

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		this.data = data;
	}
    
}

service

package edu.ecnu.admission.service;

import edu.ecnu.admission.po.AdmissionTicket;
import edu.ecnu.admission.po.ImageData;
import edu.ecnu.admission.zxing.QRCodeUtils;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.*;

import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class DocxTemplateToPdfImpl {
	
	public static void generateAll(List<AdmissionTicket> tickets)
	{
		for(AdmissionTicket ticket : tickets)
		{
			generateDocxAndPdf(ticket);
		}
	}
    
    public static void generateDocxAndPdf(AdmissionTicket admissionTicket) {
        Map<String, Object> params = new HashMap<>();
        params.put("${can}", admissionTicket.getCandidateNumber());
        params.put("${add}", admissionTicket.getAddress());
        params.put("${name}", admissionTicket.getName());
        params.put("${gender}", admissionTicket.getGender());
        params.put("${subject}", admissionTicket.getSubject());
        params.put("${time}", admissionTicket.getTime());
        params.put("${seat}", admissionTicket.getSeat());
        String resource = "docx_template.docx";
        Map<String, ImageData> picParams = new HashMap<>();//图片类 key-url
        byte[] zxingqrCode = QRCodeUtils.createZxingqrCode(admissionTicket.getIdNumber());
        ImageData qrcode = new ImageData();
        qrcode.setData(zxingqrCode);
        picParams.put("${pic}", qrcode);
        try (InputStream inputStream = DocxTemplateToPdfImpl.class.getClassLoader().getResourceAsStream(resource)) {
        	FileOutputStream os = new FileOutputStream(new File(admissionTicket.getCandidateNumber()+".pdf"));
            XWPFDocument doc = new XWPFDocument(inputStream);//导入模板文件
            List<IBodyElement> ibes = doc.getBodyElements();
            for (IBodyElement ib : ibes) {
                if (ib.getElementType() == BodyElementType.TABLE) {
                    replaceTable(ib, params, picParams, doc);
                }
            }

            PdfOptions options = PdfOptions.create();
            // 中文字体处理
            options.fontProvider(new IFontProvider() {

                public Font getFont(String familyName, String encoding, float size, int style, java.awt.Color color) {
                    try {
                    	BaseFont bfChinese = BaseFont.createFont(
    							"C:\\Program Files (x86)\\Microsoft Office\\root\\VFS\\Fonts\\private\\STSONG.TTF",
    							BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    					Font fontChinese = new Font(bfChinese);
                        if (familyName != null)
                            fontChinese.setFamily(familyName);
                        return fontChinese;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            });
            doc.write(new FileOutputStream(new File(admissionTicket.getCandidateNumber()+".docx")));
            PdfConverter.getInstance().convert(doc, os, options);

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

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

    /**
     * 写入image
     *
     * @param run
     * @param data
     * @param doc
     * @throws InvalidFormatException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void replacePic(XWPFRun run, ImageData data, XWPFDocument doc) throws Exception {
        int format = Document.PICTURE_TYPE_PNG;
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data.getData());
        run.addPicture(inputStream, format, "rpic", Units.toEMU(100), Units.toEMU(100));
    }

    /**
       * 替换表格内占位符
     *
     * @param para      表格对象
     * @param params    文字替换map
     * @param picParams 图片替换map
     * @param indoc
     * @throws Exception
     */
    public static void replaceTable(IBodyElement para, Map<String, Object> params,
                                    Map<String, ImageData> picParams, XWPFDocument indoc)
            throws Exception {
        Matcher matcher;
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        table = (XWPFTable) para;
        rows = table.getRows();
        for (XWPFTableRow row : rows) {
            cells = row.getTableCells();
            int cellsize = cells.size();
            int cellcount = 0;
            for (cellcount = 0; cellcount < cellsize; cellcount++) {
                XWPFTableCell cell = cells.get(cellcount);
                String runtext = "";
                List<XWPFParagraph> ps = cell.getParagraphs();
                for (XWPFParagraph p : ps) {
                    for (XWPFRun run : p.getRuns()) {
                        runtext = run.text();
                        matcher = matcher(runtext);
                        if (matcher.find()) {
                            if (picParams != null) {
                                for (String pickey : picParams.keySet()) {
                                    if (matcher.group().equals(pickey)) {
                                        run.setText("", 0);
                                        replacePic(run, picParams.get(pickey), indoc);
                                    }
                                }
                            }
                            if (params != null) {
                                for (String pickey : params.keySet()) {
                                    if (matcher.group().equals(pickey)) {
                                        run.setText(params.get(pickey) + "", 0);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
package edu.ecnu.admission.service;

import edu.ecnu.admission.po.AdmissionTicket;
import edu.ecnu.admission.zxing.QRCodeUtils;

import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PushbuttonField;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;


public class PdfTemplateImpl {
    
	public static void generateAll(List<AdmissionTicket> tickets) throws Exception
	{
		for(AdmissionTicket ticket : tickets)
		{
			generatePdf(ticket);
		}
	}
	
	public static void generatePdf(AdmissionTicket ticket) throws Exception {
        String resource = "pdf_template.pdf";        
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        PdfReader reader = null;
        PdfStamper pdfStamper = null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        
        try (InputStream inputStream = PdfTemplateImpl.class.getClassLoader().getResourceAsStream(resource)) {
            reader = new PdfReader(inputStream);
            pdfStamper = new PdfStamper(reader, os);
            AcroFields form = pdfStamper.getAcroFields();
            /*BaseFont baseFont = BaseFont
                    .createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);*/
            BaseFont baseFont = BaseFont.createFont(
					"C:\\Program Files (x86)\\Microsoft Office\\root\\VFS\\Fonts\\private\\STSONG.TTF",
					BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			
            form.addSubstitutionFont(baseFont);
            form.setField("candidateNumber", ticket.getCandidateNumber());
            form.setField("address", ticket.getAddress());
            form.setField("name", ticket.getName());
            form.setField("gender", ticket.getGender());
            form.setField("subject", ticket.getSubject());
            form.setField("time", ticket.getTime());
            form.setField("seat", ticket.getSeat());

            pdfStamper.setFormFlattening(true);
            byte[] zxingqrCode = QRCodeUtils.createZxingqrCode(ticket.getIdNumber());
            PushbuttonField ad = form.getNewPushbuttonFromField("qrcode");
            if (ad != null && zxingqrCode != null) {
                ad.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
                ad.setProportionalIcon(true);
                ad.setImage(Image.getInstance(zxingqrCode));
                form.replacePushbuttonField("qrcode", ad.getField());
            }
            pdfStamper.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (pdfStamper != null) {
                    pdfStamper.close();
                }
                if (reader != null) {
                    reader.close();
                }
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        FileOutputStream  fos = new FileOutputStream(new File(ticket.getCandidateNumber() + "-2.pdf"));
        fos.write(os.toByteArray());
        fos.close();
    }
}

zxing

package edu.ecnu.admission.zxing;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

public class BarCodeUtils {
    public static BitMatrix getShapeCode(String code, int width, int height) {
        // 编码条形码
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "GBK");
        BitMatrix matrix = null;
        try {
            // 使用code_128格式进行编码生成100*25的条形码
            matrix = new MultiFormatWriter().encode(code,
                    BarcodeFormat.CODE_128, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return matrix;
    }

    public static byte[] getByte(String code, int width, int height) {
        BitMatrix matrix = getShapeCode(code, width, height);
        // 返回png图片流
        // 获得Servlet输出流

        try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
            ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png",
                    outStream);
            outStream.flush();
            return outStream.toByteArray();
        } catch (Exception e) {
            return null;
        }

    }

    public static void getByte(File file, String code, int width, int height) {
        BitMatrix matrix = getShapeCode(code, width, height);
        // 返回png图片流
        // 获得Servlet输出流

        try (FileOutputStream outStream = new FileOutputStream(file)) {
            ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png",
                    outStream);
            outStream.flush();

        } catch (Exception e) {

        }

    }

    public static void main(String[] args) throws Exception {
        getByte(new File("123.png"), "6051930500003940", 500, 250);
    }
}
package edu.ecnu.admission.zxing;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtils {
    /*
     * 定义二维码的宽高
     */
    private static int WIDTH = 150;
    private static int HEIGHT = 150;
    private static String FORMAT = "png";//二维码格式

    //生成二维码
    public static void createZxingqrCode(File file, String content) {
        //定义二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();

        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//设置容错等级
        hints.put(EncodeHintType.MARGIN, 2);//设置边距默认是5

        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            Path path = file.toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);//写到指定路径下

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

    }

    //生成二维码
    public static byte[] createZxingqrCode(String content) {
        //定义二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();

        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//设置容错等级
        hints.put(EncodeHintType.MARGIN, 2);//设置边距默认是5

        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

            MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, os);//写到指定路径下
            return os.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    //读取二维码
    public static void readZxingQrCode(File file) {
        MultiFormatReader reader = new MultiFormatReader();
        try {
            BufferedImage image = ImageIO.read(file);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "utf-8");//设置编码
            Result result = reader.decode(binaryBitmap, hints);
            System.out.println("解析结果:" + result.toString());
            System.out.println("二维码格式:" + result.getBarcodeFormat());
            System.out.println("二维码文本内容:" + result.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        createZxingqrCode(new File("123.png"), "https://www.baidu.com");
    }
}

Main

package edu.ecnu.admission;

import edu.ecnu.admission.data.AdmissionDao;
import edu.ecnu.admission.data.Importer;
import edu.ecnu.admission.mail.Postman;
import edu.ecnu.admission.po.AdmissionTicket;
import edu.ecnu.admission.service.DocxTemplateToPdfImpl;
import edu.ecnu.admission.service.PdfTemplateImpl;

import java.util.List;

public class Main {

    public static void main(String[] args) throws Exception {
    	//获取data.xlsx的所有数据
    	List<AdmissionTicket> tickets = Importer.importFromExcel("data.xlsx");
    	
    	//将tickets导入到数据库中
    	AdmissionDao.addAll(tickets);
    			
    	//从数据库中重新加载数据
    	List<AdmissionTicket> tickets2 = AdmissionDao.getAll();
    	
    	//生成所有的模板(两种方法)    	
    	DocxTemplateToPdfImpl.generateAll(tickets2); //write docx, then convert to pdf 
    	PdfTemplateImpl.generateAll(tickets2); //read pdf template and fill with values
    	
    	//发送邮件
    	new Postman().sendAll(tickets2);
    }   
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值