com.itextpdf.text.Image
引用包
获取Image的两种常用方式:
1、本地图片插入如 :
String imageUrl = "d://123.png";
Image image =Image.getInstance(imageUrl);
2、链接图片地址插入:
String imgURL = "https://avatar.csdnimg.cn/3/1/7/1_qq_27292113.jpg"
Image image = Image.getInstance(new URL(imgURL))
部分业务代码:
/**
* @param image
* @param align_v 垂直 ALIGN_LEFT = 0; ALIGN_CENTER = 1;ALIGN_RIGHT = 2; ALIGN_TOP = 4;ALIGN_MIDDLE = 5;ALIGN_BOTTOM = 6;
* @param align_h 水平 ALIGN_LEFT = 0 ALIGN_CENTER = 1; ALIGN_RIGHT = 2;
* @param colspan 跨列
* @param rowspan 跨行
* @return
*/
public PdfPCell createCellNotBorder(Image image, int align, int colspan, int rowspan) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
if (colspan !=0) {
cell.setColspan(colspan);
}
if (rowspan !=0) {
cell.setRowspan(rowspan);
}
cell.setBorder(0);
cell.setFixedHeight(rowspan * 25.0F);
cell.setImage(image);
return cell;
}
/**
*生成图片二维码
* @param url 存放地址
* @param content 二维码的内容
* @param width
* @param height
* @return
* @throws Exception
*/
public String code(String url, String content, int width, int height)
throws Exception {
if (StringUtils.isEmpty(content)) {
return "";
}
// 调用工具类,生成二维码
BufferedImage bufferedImage = creatCode(content, width, height); // 200为图片高度和宽度
String url1 = url +"/"+ content + ".png";
File imageFile = new File(url1);
ImageIO.write(bufferedImage, "png", imageFile);
return url1;
}
public BufferedImage creatCode(String contents, int width, int height) {
BufferedImage image = null;
Hashtable<EncodeHintType, java.io.Serializable> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //设置字符编码
hints.put(EncodeHintType.MARGIN, 1); //二维码空白区域,最小为0也有白边,只是很小,最小是6像素左右
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints); // 1、读取文件转换为字节数组
image = MatrixToImageWriter.toBufferedImage(bitMatrix);
//转换成png格式的IO流
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
maven 引用包:
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.21</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!-- 二维码 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>