LK最近项目中要进行对pdf的操作,具体需求是要在现有pdf文件末尾加入一下文字。
-
首先需要准备的jar包,itextpdf-5.5.5.jar和itext-asian-5.2.0.jar
jar包可以在maven仓库中下
>https://mvnrepository.com/
下完以后新建项目导入就行
-
代码
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
/**
* @Description:使用itextpdf在已有pdf文件中追加图片和文字
* @author yrz
* @version:1.0
*/
public class itText {
public static void main(String[] args) throws Exception {
PdfReader reader = new PdfReader("E://tu100.pdf");// 指定将和 图片拼接的 PDF
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("E://tu101.pdf"));// 生成的PDF 路径
PdfContentByte overContent = stamper.getOverContent(1);
String imgPath = "E://td2.jpg";
String str = " ,cv0001,cv0002,cv0003,cv0004,cv0001,cv0002,cv0003,cv0004,cv0001,cv0002,cv0003,cv0004,cv0001,cv0002,cv0003,cv0004";
addImg(overContent,imgPath);
addtext(overContent, str);
System.out.println("追加成功");
overContent.stroke();
stamper.close();
reader.close();
}
/**
* @Description:添加图片
* @param overContent
* @param path
* @throws Exception
*/
public static void addImg(PdfContentByte overContent, String path) throws Exception {
// 添加图片
Image image = Image.getInstance(path);// 图片名称
image.scaleAbsolute(500, 20);
image.setAbsolutePosition(20, 5);// 左边距、底边距
overContent.addImage(image);
}
/**
* @Description:追加文字
* @param overContent
* @param str
* @throws Exception
*/
public static void addtext(PdfContentByte overContent, String str) throws Exception {
StringBuffer bufAll = new StringBuffer();
StringBuffer buf = new StringBuffer();
int a = 0;
int b = 0;
String by[] = str.split(",");
// 每10个换行
for (int i = 1; i < by.length; i++) {
buf.append(new String(by[i]) + " ");
if (i % 10 != 0 && i == by.length - 1) {
bufAll.append(buf.toString());
} else if (i % 10 == 0) {
b = i;
bufAll.append(buf.toString() + "__");
buf.delete(0, buf.length());
a = b;
b = 0;
}
}
System.out.println(bufAll.toString());
if (bufAll.toString().contains("__")) {
String aa[] = bufAll.toString().split("__");
BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
overContent.beginText();
overContent.setFontAndSize(font, 8);
overContent.setTextMatrix(200, 200);
// pdf中换行
for (int i = 1; i < aa.length; i++) {
overContent.showTextAligned(Element.ALIGN_CENTER, "" + aa[i] + "", 250, i * 10, 0);
}
overContent.showTextAligned(Element.ALIGN_CENTER, "参与此次实验的毒株编号:" + aa[0] + "", 250, aa.length * 10, 0);
overContent.endText();
}
}
}
- 效果展示
原始图:
== 追加文字后 ==
最后附上学习地址:https://www.yiibai.com/javaexamples/java_itext.html
接下来考虑使用表格改进