java 操作pdf模板(向指定域添加文本内容和图片)

项目需求涉及到操作pdf模板,根据生成好的模板向里面填充数据  

用到的jar包是iText-5.0.6.jar 和iTextAsian.jar

上代码:

   

 public static void main(String[] args)
{
try
{
String TemplatePDF = "e:/F-3.pdf"; //魔板路径
String outFile = "e:/test.pdf"; //生成新的pdf的路径
PdfReader reader = new PdfReader(TemplatePDF);
PdfStamper ps = new PdfStamper(reader, new FileOutputStream(outFile)); // 生成的输出流

AcroFields s = ps.getAcroFields();
// 插入文字
insertText(ps, s);
// 插入图片
insertImage(ps, s);
ps.close();
reader.close();
}
catch (Exception e)
{
e.printStackTrace();
} 
}
/**
* 插入图片
* 
* @param ps
* @param s
* @author WangMeng
* @date 2016年6月16日
*/
public static void insertImage(PdfStamper ps, AcroFields s)
{


try
{
List<AcroFields.FieldPosition> list = s.getFieldPositions("QR_CODE");
Rectangle signRect = list.get(0).position;


Image image = Image.getInstance("e:/pdf.jpg");
PdfContentByte under = ps.getOverContent(2);
float x = signRect.getLeft();
float y = signRect.getBottom();
System.out.println(x);
System.out.println(y);
image.setAbsolutePosition(x, y);
image.scaleToFit(signRect.getWidth(), signRect.getHeight());


under.addImage(image);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}


}
/**
* 创建Chunk
* 
* @return
* @author WangMeng
* @date 2016年6月16日
*/
public static Chunk CreateChunk()
{
BaseFont bfChinese;
Chunk chunk = null;
try
{
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
Font fontChinese = new Font(bfChinese, 10 * 4 / 3);
chunk = new Chunk("张三", fontChinese);
}
catch (Exception e)
{
e.printStackTrace();
}


return chunk;
}
/**
* 插入文本
* 
* @return
* @author WangMeng
* @date 2016年6月16日
*/
public static void insertText(PdfStamper ps, AcroFields s)
{
List<AcroFields.FieldPosition> list = s.getFieldPositions("CONNECT_NAME");
Rectangle rect = list.get(0).position;


PdfContentByte cb = ps.getOverContent(1);
PdfPTable table = new PdfPTable(1);
float tatalWidth = rect.getRight() - rect.getLeft() - 1;
table.setTotalWidth(tatalWidth);


PdfPCell cell = new PdfPCell(new Phrase(CreateChunk()));
cell.setFixedHeight(rect.getTop() - rect.getBottom() - 1);
cell.setBorderWidth(0);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setLeading(0, (float) 1.1);


table.addCell(cell);
table.writeSelectedRows(0, -1, rect.getLeft(), rect.getTop(), cb);
}

  注意:主要思路是:因为直接向域中插入文本和图片没有直接的方法(也许有,但是我可能没有找到),采用的是获取域的位置,在指定位置上插入表格或者图片

  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值