项目要使用iText,必须引入jar包。才能使用,maven依赖如下:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
输出中文,还要引入下面itext-asian.jar包:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
设置pdf文件密码,还要引入下面bcprov-jdk15on.jar包:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.54</version>
</dependency>
创建pdf工具类
/**
* 根据参数创建pdf文件
*
* @param json pdf内容
* @param path 文件路径
* @return pdf访问全路径
*/
public static String createPDFFile(JSONObject json, String path) {
Document pdfDoc = null;
String pdfPath = "";
try {
// 设置字体
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
pdfDoc = new Document(PageSize.A4.rotate(), 36, 36, 24, 36);
String filename = json.getString("gzdbh") + ".pdf";
log.info("pdf文档放置路径:" + path);
pdfPath = "http://" + HttpSessionHelper.getServerInfo() + "/web/pdf/";
//pdfPath = "http://" + HttpSessionHelper.getServerInfo() + "/web/pdf/"+ json.getString("pdfname") + "//";
PdfWriter.getInstance(pdfDoc, new FileOutputStream(path + File.separator + filename));
pdfDoc.open();
JSONArray pages = (JSONArray) json.get("pages");
int[] borders = new int[] { PdfPCell.TOP, PdfPCell.RIGHT, PdfPCell.BOTTOM, PdfPCell.LEFT };
for (int k = 0; k < pages.size(); k++) {
JSONObject page = (JSONObject) pages.get(k);
String[] relativeWidthStrs = page.getString("relativeWidths").split(",");
float[] relativeWidths = new float[relativeWidthStrs.length];
int columnCount = relativeWidths.length;
for (int i = 0; i < columnCount; i++) {
relativeWidths[i] = Float.parseFloat(relativeWidthStrs[i]);
}
PdfPTable headerTable = new PdfPTable(relativeWidths);
headerTable.setWidthPercentage(95);
pdfDoc.setPageSize(page.getInt("orientation") == 0 ? PageSize.A4 : PageSize.A4.rotate());
pdfDoc.newPage();
JSONArray array = page.getJSONArray("cells");
for (int i = 0; i < array.size(); i++) {
JSONObject obj = (JSONObject) array.get(i);
String content = obj.getString("content");
JSONArray enableBorders = obj.getJSONArray("enableBorders");
int align = obj.getBoolean("alignCenter") ? Element.ALIGN_CENTER : Element.ALIGN_LEFT;
float fontSize = obj.getInt("fontSize");
int column = obj.getInt("column");
int rowspan = obj.getInt("rowspan");
int type = obj.getInt("type");
int fontStyle = obj.getInt("fontStyle");
int lineHeight = obj.getInt("lineHeight");
PdfPCell iCell = new PdfPCell();
for (int j = 0; j < enableBorders.size(); j++) {
if (Integer.parseInt(enableBorders.get(j).toString()) == 0) {
iCell.disableBorderSide(borders[j]);
}
}
iCell.setLeading(0, 1.7f);
iCell.setPaddingLeft(0);//10f
iCell.setPaddingRight(0);//10f
iCell.setPaddingTop(-4);//10f
iCell.setHorizontalAlignment(align);
iCell.setMinimumHeight(lineHeight);
iCell.setColspan(column);
iCell.setRowspan(rowspan);
iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
if (type == 0) {// 文本类型
Font fontChinese = new Font(bfChinese, fontSize, Font.NORMAL);
if (fontStyle == 1) {
fontChinese.setStyle(Font.BOLD);
} // 创建字体,设置family,size,style,还可以设置color
Paragraph par = new Paragraph(content, fontChinese);
iCell.setPhrase(par);
} else if (type == 1) {// 图片类型
String[] imgs = content.split(",");
for (int j = 0; j < imgs.length; j++) {
Image img = Image.getInstance(imgs[j]);
//img.scaleAbsolute(lineHeight, lineHeight * 1.5f);
img.setAlignment(Element.ALIGN_CENTER);
img.setAbsolutePosition(img.getWidth() * j, img.getWidth() * j * -1);
iCell.addElement(img);
}
} else if (type == 2) {
iCell.setCellEvent(new CheckboxCellEvent("0", false));
} else if (type == 3) {
iCell.setCellEvent(new CheckboxCellEvent("1", true));
}
headerTable.addCell(iCell);
}
pdfDoc.add(headerTable);
}
pdfDoc.close();
} catch (Exception e) {
e.printStackTrace();
pdfDoc.close();
}
return pdfPath;
}
获取服务器IP和端口信息
public final class HttpSessionHelper {
/**
*非web环境下返回空字符串
*/
public static String getServerInfo() {
HttpServletRequest request = getHttpServletRequest();
return request.getLocalAddr() + ":" + request.getLocalPort();
}
}
创建pdf单元
/**
* 创建单元格集合
*
* @param contents 单元格内容数组,一个元素为一个单元格,若type为图片类型则元素内容为图片绝对路径,多张图片用","分隔
* @param columns 每个单元格对应的跨列数数组
* @param lineHeight 单元格最小高度
* @param enableBorders 是否显示边框数组,顺序为上右下左,1代表显示,0代表不显示,如:new int[]{1,0,1,0}即显示上下边框,而左右边框不显示
* @param fontsize 字体大小
* @param aligncenter 是否居中显示
* @param type 0代表文本类型,1代表图片类型,2代表多选框无勾,3代表多选框有勾
* @param fontStyle 字体格式 0代表普通 1代表加粗
* @param rowspan 单元格跨行数
* @return JSONArray
*/
public static JSONArray generateCellList(Object[] contents, int[] columns, int lineHeight, int[] enableBorders, float fontsize,
boolean aligncenter, int type, int fontStyle, int rowspan) {
JSONArray list = new JSONArray();
JSONObject cell = null;
for (int i = 0; i < contents.length; i++) {
cell = new JSONObject();
cell.put("type", type);
cell.put("content", contents[i]);
cell.put("column", columns[Math.min(i, columns.length - 1)]);
cell.put("alignCenter", aligncenter);
cell.put("enableBorders", enableBorders);
cell.put("fontSize", fontsize);
cell.put("lineHeight", lineHeight);
cell.put("fontStyle", fontStyle);
cell.put("rowspan", rowspan);
list.add(cell);
}
return list;
}
pdf签章方法
public class SignatureUtil {
/**
* pdf签章方法
*
* @param src pdf路径
* @param desc 签章后pdf路径
* @param imagePath 图片路径
* @param range 签章位置
* @param pageNum 页数
*/
public static void sign(String src, String desc, String imagePath, int[] range, int pageNum) {
try {
PdfReader pdfReader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(pdfReader, new FileOutputStream(desc));
PdfContentByte canvas = stamper.getOverContent(pageNum);
Image image = Image.getInstance(imagePath);
// image.setAbsolutePosition(60, 350);
image.setAbsolutePosition(range[0], range[1]);
canvas.addImage(image);
stamper.close();
pdfReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}