有个需求是所有页面地图一致,但是页面数量是动态的,不可能每张页面都手动去添加底图,itext的触发事件我们可以使用一个itext触发页面事件的接口,来满足我们的这个需求,那就是直接继承PdfPageEventHelper 重写里面的一些方法来达到我们的目的。
import java.io.IOException;
import java.net.MalformedURLException;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
/**
* Description <br/>
* date: 2018-3-13 下午4:22:43<br/>
*
* @author Chentao
* @version
* @see
* @param
*/
public class BackGroundImage extends PdfPageEventHelper {
private String imgPath;
private byte[] img1;
private byte[] img2;
public byte[] getImg1() {
return img1;
}
public void setImg1(byte[] img1) {
this.img1 = img1;
}
public byte[] getImg2() {
return img2;
}
public void setImg2(byte[] img2) {
this.img2 = img2;
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
public BackGroundImage() {
}
public BackGroundImage(String imgPath) {
this.imgPath = imgPath;
}
public BackGroundImage(byte[] img1, byte[] img2) {
super();
this.img1 = img1;
this.img2 = img2;
}
public BackGroundImage(byte[] img1) {
super();
this.img1 = img1;
}
@Override
public void onStartPage(PdfWriter writer, Document document) {
Image image1 = null;
try {
if (imgPath != null) {
image1 = Image.getInstance(imgPath);
} else if (img1 != null && img2 == null) {
image1 = Image.getInstance(img1);
} else if (img1 != null && img2 != null) {
if (document.getPageNumber() % 2 == 0) {
image1 = Image.getInstance(img2);
} else {
image1 = Image.getInstance(img1);
}
} else {
return;
}
image1.setAbsolutePosition(0, 0);
image1.scaleAbsolute(document.getPageSize());
document.add(image1);
super.onStartPage(writer, document);
} catch (BadElementException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
如何调用呢?
创建pdf
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, baos);
writer.setPageEvent(new BackGroundImage(backGroundImage1, backGroundImage2));
document.open();
在doucument.open前就调用。
如果只传1张就是同一一张底图,如果传两张就是奇树偶数页底图。
有啥问题欢迎指出。