第一種方案 使用itext填充靜態PDF模板 然後生成PDF新文件 1 使用Adobe Acrobat 編輯原PDF 添加文本域 itext依賴 <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId ...
第一種方案 使用itext填充靜態PDF模板 然後生成PDF新文件
1 使用Adobe Acrobat 編輯原PDF 添加文本域
itext依賴
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
代碼實現
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 java.io.FileOutputStream;
import java.util.ArrayList;
/**
* 操作PDF
*
* @Author liguangcheng
* @Date 2022/6/11 09:26
* @Vision 1.0
**/
public class PDFTest {
public static void main(String[] args) throws Exception {
String filePath = "test.pdf";
PdfReader reader = new PdfReader(filePath);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("test-副本.pdf"));
//使用中文字體
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
ArrayList<BaseFont> fontList = new ArrayList<>();
fontList.add(bf);
AcroFields acroFields = stamper.getAcroFields();
acroFields.setSubstitutionFonts(fontList);
//設置欄位
acroFields.setField("name", "測試姓名");
acroFields.setField("age", "18");
stamper.setFormFlattening(true);
stamper.close();
}
}
test-副本.pdf效果
第二種方案 通過坐標定位 然後添加水印
import com.itextpdf.awt.geom.Rectangle2D;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import lombok.Getter;
import lombok.Setter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* 操作PDF
*
* @Author liguangcheng
* @Date 2022/6/11 09:26
* @Vision 1.0
**/
public class PDFTest {
public static void main(String[] args) throws Exception {
List<String> keywordList = new ArrayList();
keywordList.add("測試姓名");
keywordList.add("18");
List<PdfItextModel> pdfItextModels = new ArrayList<>();
for (String keyword : keywordList) {
float[] keyWordsByPath = getKeyWords("test-副本.pdf", keyword);
PdfItextModel pdfItextModel = new PdfItextModel();
pdfItextModel.setContent("水印" +keyword);
for (int i = 0; i < keyWordsByPath.length; i++) {
pdfItextModel.setXCoordinate(keyWordsByPath[0]);//x坐標
pdfItextModel.setYCoordinate(keyWordsByPath[1]);//y坐標
pdfItextModel.setPageNum((int) keyWordsByPath[2]);//頁數
System.out.println(keyword + "坐標值:" + keyWordsByPath[i]);
}
pdfItextModels.add(pdfItextModel);
}
signSinglePsw("test.pdf", pdfItextModels);
}
/**
* @param filepath 文件位置
* @param keyWords 關鍵字
* @return float[]
* @Description 獲取關鍵字所在PDF坐標
*/
private static float[] getKeyWords(String filepath, String keyWords) {
float[] coordinate = null;
int page = 0;
try {
PdfReader pdfReader = new PdfReader(filepath);
int pageNum = pdfReader.getNumberOfPages();
PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(pdfReader);
CustomRenderListener renderListener = new CustomRenderListener();
renderListener.setKeyWord(keyWords);
for (page = 1; page <= pageNum; page++) {
renderListener.setPage(page);
pdfReaderContentParser.processContent(page, renderListener);
coordinate = renderListener.getPcoordinate();
if (coordinate != null) break;
}
} catch (IOException e) {
e.printStackTrace();
}
return coordinate;
}
@Getter
@Setter
static class CustomRenderListener implements RenderListener {
private float[] pcoordinate = null;
private String keyWord;
private int page;
@Override
public void beginTextBlock() {
}
@Override
public void endTextBlock() {
}
@Override
public void renderImage(ImageRenderInfo arg0) {
}
@Override
public void renderText(TextRenderInfo textRenderInfo) {
String text = textRenderInfo.getText();
if (null != text && text.contains(keyWord)) {
Rectangle2D.Float boundingRectange = textRenderInfo.getBaseline().getBoundingRectange();
pcoordinate = new float[3];
pcoordinate[0] = boundingRectange.x;
pcoordinate[1] = boundingRectange.y;
pcoordinate[2] = page;
}
}
}
/**
* @param oldPswFilePath 原來的文件地址
* @param list 需要添加的詳細信息
* @return
*/
public static String signSinglePsw(String oldPswFilePath, List<PdfItextModel> list) throws Exception {
int lastIndex = oldPswFilePath.lastIndexOf('.');
// 獲取文件尾碼
String suffix = oldPswFilePath.substring(lastIndex + 1);
// 判斷是否為pdf文件
if (!"pdf".equalsIgnoreCase(suffix)) {
throw new RuntimeException("Not is PDF file");
}
// 生成新的文件路徑
String newPswPath = oldPswFilePath.substring(0, lastIndex) + "-副本1." + suffix;
System.out.println("單個psw文件簽名生成的新路徑:" + newPswPath);
//解析文件
PdfReader reader = new PdfReader(oldPswFilePath);
FileOutputStream fOut = new FileOutputStream(newPswPath);
PdfStamper stp = new PdfStamper(reader, fOut);
// 總頁數
System.out.println("PDF總頁數:" + reader.getNumberOfPages());
for (PdfItextModel model : list) {
Float xCoordinate = model.getXCoordinate();
Float yCoordinate = model.getYCoordinate();
Integer pageNum = model.getPageNum();
String content = model.getContent();
if (xCoordinate == null || yCoordinate == null ||
pageNum == null || pageNum == 0 || content == null || "".equals(content)) {
continue;
}
PdfContentByte pdfContentByte = stp.getOverContent(pageNum);
pdfContentByte.beginText();
// 設置字體及字型大小
pdfContentByte.setFontAndSize(getBaseFont(), 14);
addDeptReview(xCoordinate, yCoordinate, pdfContentByte, content);
pdfContentByte.endText();
}
stp.close();
// 將輸出流關閉
fOut.close();
reader.close();
// 文件讀寫結束
System.out.println("PSW文件讀寫完畢");
return newPswPath;
}
// 獲取基礎文字
public static BaseFont getBaseFont() throws Exception {
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
return base;
}
/**
* @param content
* @param keyword
* @param x X軸坐標
* @param y Y軸坐標
* @Description 添加水印
*/
private static void addDeptReview(float x, float y, PdfContentByte content, String keyword) {
content.setColorFill(BaseColor.BLACK);
// 設置水印位置和內容
System.out.println("水印內容:" + keyword);
System.out.println("列印位置坐標:" + x + "," + y);
content.showTextAligned(Element.ALIGN_LEFT, keyword, x, y, 0);
}
@Getter
@Setter
static class PdfItextModel {
// X坐標
private Float xCoordinate;
//Y坐標
private Float yCoordinate;
//頁碼
private Integer pageNum;
//內容
private String content;
public PdfItextModel() {
}
}
}
找到test.副本.pdf中關鍵字坐標
通過test.pdf空白模板生成新的文件test.副本1.pdf並添加水印
參考博客[https://blog.51cto.com/u_15127609/3272726]
參考博客[https://www.cnblogs.com/alphajuns/p/12436332.html]
參考博客[https://blog.csdn.net/k_young1997/article/details/103512997]