IText - 如何将渐变设置为PDF文档的背景?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IText - 如何将渐变设置为PDF文档的背景?相关的知识,希望对你有一定的参考价值。
我正在使用iText生成PDF文档,我想将渐变设置为页面背景。这可能吗?
答案
(因为你只使用标签“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的内部课程)
结果如下:
以上是关于IText - 如何将渐变设置为PDF文档的背景?的主要内容,如果未能解决你的问题,请参考以下文章