由于PdfTemplate继承于PdfContentByte类,可以使用PdfContentByte方法来进行操作
Document doc = new Document();PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filepath));
doc.open();PdfContentByte cb = writer.getDirectContent();
创建template并加到PdfContentByte里,template的状态位置是采用matrix方式来设置
PdfTemplate template = cb.createTemplate(width, height);
cb.addTemplate(template, 1f, 0f, 0f, 1f, 0f, 0f);
关于矩形变换,详细可以到wiki上学习 https://en.wikipedia.org/wiki/Transformation_matrix
添加文字
template.saveState();
template.beginText();
template.moveText(5f, 5f); //坐标位置是相对template的左下角计算的//template.setColorFill(color);
template.showText("Test Text");
template.endText();
template.stroke();
template.restoreState();
设置文字粗体和斜体,由于没有招到设置的函数,采用其他方式来实现这个效果
换个想法可以根据matrix的思路用setTextMatrix方法来设置
// Text Matrix Paramfloat ta = 1f, tb = 0f, tc = 0f, td = 1f, tx = 0f, ty = 0f;
设置粗体,具体要多大多粗可以根据需要调整
ta = ta + 0.15f;
td = td + 0.05f;
ty = ty - 0.15f;
设置斜体,斜的角度也可以按需调整
tc = tc + 0.3f;
添加文字并设置加粗,斜体
template.saveState();
template.beginText();
template.moveText(5f, 5f);
template.setTextMatrix(ta, tb, tc, td, tx, ty);//这里对文字进行变形以达到想要的效果
template.showText("Test Text");
template.endText();
template.stroke();
template.restoreState();
完