参考 :
提高图片质量 : https://blog.youkuaiyun.com/u014411256/article/details/84121081
设置分辨率(好像没用) : https://my.oschina.net/osgit/blog/530283
注 : 如果设置了抗锯齿打印出来还是很模糊的话,应该是尺寸设小了,A4纸应该设置为 2479 × 3508,汉字大写建议48,标题大写建议 58
说明 :
生成报表主要用到了两个方法
写字: g.drawString(str,x,y)
划线: g.drawLine(x1,y1,x2,y2)
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
/**
* @Auther: liyue
* @Date: 2019/6/28 19:35
* @Description:
*/
public class DrawUtil {
private static final int CHINESE_SIZE = 48;
public static void main(String[] args) throws Exception {
test("/Users/leyili/Desktop/file_test/test.png");
}
/**
* 生成图片
*
* @param fileName
*/
private static void test(String fileName) {
try {
File file = new File(fileName);
BufferedImage image = new BufferedImage(460, 870, BufferedImage.TYPE_INT_BGR);
//获取Graphics2D对象
Graphics2D graphics = image.createGraphics();
//开启文字抗锯齿
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
// 填充白色背景
graphics.setColor(Color.white);
graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
//设置字体
Font font = new Font("宋体", Font.PLAIN, 40);
graphics.setColor(Color.black);
graphics.setFont(font);
//向画板上写字
graphics.drawString("This is test!", 10, 60);
graphics.drawString("BKJL8987890", 10, 100);
graphics.dispose();
// 输出
saveImageUsingJPGWithQuality(image, fileName, 3F);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 转换成JPEG,及设置质量
*
* @param image
* @param filePath
* @param quality 图片质量(0-1)
* @throws Exception
*/
public static void saveImageUsingJPGWithQuality(BufferedImage image,
String filePath, float quality) throws Exception {
BufferedImage newBufferedImage = new BufferedImage(image.getWidth(),
image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
newBufferedImage.getGraphics().drawImage(image, 0, 0, null);
Iterator<ImageWriter> iter = ImageIO
.getImageWritersByFormatName("jpeg");
ImageWriter imageWriter = iter.next();
ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality);
File file = new File(filePath);
FileImageOutputStream fileImageOutput = new FileImageOutputStream(file);
imageWriter.setOutput(fileImageOutput);
IIOImage iio_image = new IIOImage(newBufferedImage, null, null);
imageWriter.write(null, iio_image, iwp);
imageWriter.dispose();
}
/**
* 单元格水平居中
*
* @param width
* @param str
* @return 得出的是该单元格第一个字体放置的位置
*/
private static int chineseCenterWidth(int width, String str) {
return (width - str.length() * (CHINESE_SIZE + 1)) / 2;
}
/**
* 单元格垂直居中
*
* @param height
* @return 得出的是汉字在单元格内垂直居中的像素
*/
private static int chineseCenterHeight(int height) {
return (height - CHINESE_SIZE) / 2 + CHINESE_SIZE;
}
}