1 回答
TA贡献1887条经验 获得超5个赞
(因为您只使用了标签“itext”,而不是“itext7”,我假设您使用的是 iText 5.5.x。)
您可以PdfContentByte canvas使用PdfShading实例将轴向渐变绘制到 a 上:
PdfShading axial = PdfShading.simpleAxial(pdfWriter, x0, y0, x1, y1, startColor, endColor, extendStart, extendEnd);
canvas.paintShading(axial);
例如,如果您想为现有 PDF 的所有页面添加浅红色到浅绿色渐变,您可以这样做:
PdfReader pdfReader = new PdfReader(SOURCE);
PdfStamper pdfStamper = new PdfStamper(pdfReader, TARGET);
pdfStamper.setRotateContents(false);
for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) {
Rectangle pageSize = pdfReader.getPageSize(page);
PdfShading axial = PdfShading.simpleAxial(pdfStamper.getWriter(),
pageSize.getLeft(pageSize.getWidth()/10), pageSize.getBottom(),
pageSize.getRight(pageSize.getWidth()/10), pageSize.getBottom(),
new BaseColor(255, 200, 200), new BaseColor(200, 255, 200), true, true);
PdfContentByte canvas = pdfStamper.getUnderContent(page);
canvas.paintShading(axial);
}
pdfStamper.close();
或者,如果您想为从头创建的 PDF 的所有页面添加浅红色到浅绿色渐变,您可以这样做:
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, TARGET);
pdfWriter.setPageEvent(new GradientBackground());
document.open();
for (int i=0; i < 20; i++) {
document.add(new Paragraph("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."));
}
document.close();
使用这个助手类
class GradientBackground extends PdfPageEventHelper {
@Override
public void onEndPage(PdfWriter writer, Document document) {
Rectangle pageSize = document.getPageSize();
PdfShading axial = PdfShading.simpleAxial(writer,
pageSize.getLeft(pageSize.getWidth()/10), pageSize.getBottom(),
pageSize.getRight(pageSize.getWidth()/10), pageSize.getBottom(),
new BaseColor(255, 200, 200), new BaseColor(200, 255, 200), true, true);
PdfContentByte canvas = writer.getDirectContentUnder();
canvas.paintShading(axial);
}
}
结果如下所示:
添加回答
举报