個(gè)人感覺(jué)pdf的操作比word舒心多了
java操作pdf有個(gè)非常好用的庫(kù)itextpdf
,maven:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.6</version>
</dependency>
<!-- itextpdf的亞洲字體支持 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
思路:
- Adobe的Acrobat可以對(duì)pdf進(jìn)行編輯宰掉,在文檔中插入域,這個(gè)插入的域就是圖片的位置。這兒有關(guān)于域的介紹,但是這不重要格二,我們只是把域作為一個(gè)占位符用;
- 利用itextpdf得到目標(biāo)域所在的頁(yè)面竣蹦、位置顶猜、大小痘括;
- 利用域的坐標(biāo)长窄,把圖片以絕對(duì)位置的方式插入到pdf中。
代碼
public static void main(String[] args) throws Exception {
// 模板文件路徑
String templatePath = "template.pdf";
// 生成的文件路徑
String targetPath = "target.pdf";
// 書(shū)簽名
String fieldName = "field";
// 圖片路徑
String imagePath = "image.jpg";
// 讀取模板文件
InputStream input = new FileInputStream(new File(templatePath));
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(targetPath));
// 提取pdf中的表單
AcroFields form = stamper.getAcroFields();
form.addSubstitutionFont(BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED));
// 通過(guò)域名獲取所在頁(yè)和坐標(biāo)纲菌,左下角為起點(diǎn)
int pageNo = form.getFieldPositions(fieldName).get(0).page;
Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;
float x = signRect.getLeft();
float y = signRect.getBottom();
// 讀圖片
Image image = Image.getInstance(imagePath);
// 獲取操作的頁(yè)面
PdfContentByte under = stamper.getOverContent(pageNo);
// 根據(jù)域的大小縮放圖片
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
// 添加圖片
image.setAbsolutePosition(x, y);
under.addImage(image);
stamper.close();
reader.close();
}