我正在使用iText生成PDF文档,并且我想将渐变设置为页面背景。这可能吗?
答案 0 :(得分:0)
(因为您只使用了标签“ itext”,而不是“ itext7”,所以我假设您使用的是iText 5.5.x。)
您可以使用PdfContentByte canvas
实例在PdfShading
上绘制轴向渐变:
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();
(AddGradientBackground测试testStampGradientBackground
)
或者,如果您想为从头开始创建的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();
(AddGradientBackground测试testCreateWithGradientBackground
)
使用此帮助程序类
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);
}
}
(AddGradientBackground中的内部类)
结果如下: