猿问

IText - 如何将渐变设置为 PDF 文档的背景?

我正在使用 iText 生成 PDF 文档,我想将渐变设置为页面背景。这可能吗?


四季花海
浏览 393回答 1
1回答

慕工程0101907

(因为您只使用了标签“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++) {&nbsp; &nbsp; Rectangle pageSize = pdfReader.getPageSize(page);&nbsp; &nbsp; PdfShading axial = PdfShading.simpleAxial(pdfStamper.getWriter(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pageSize.getLeft(pageSize.getWidth()/10), pageSize.getBottom(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pageSize.getRight(pageSize.getWidth()/10), pageSize.getBottom(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new BaseColor(255, 200, 200), new BaseColor(200, 255, 200), true, true);&nbsp; &nbsp; PdfContentByte canvas = pdfStamper.getUnderContent(page);&nbsp; &nbsp; 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++) {&nbsp; &nbsp; 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 {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onEndPage(PdfWriter writer, Document document) {&nbsp; &nbsp; &nbsp; &nbsp; Rectangle pageSize = document.getPageSize();&nbsp; &nbsp; &nbsp; &nbsp; PdfShading axial = PdfShading.simpleAxial(writer,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pageSize.getLeft(pageSize.getWidth()/10), pageSize.getBottom(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pageSize.getRight(pageSize.getWidth()/10), pageSize.getBottom(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new BaseColor(255, 200, 200), new BaseColor(200, 255, 200), true, true);&nbsp; &nbsp; &nbsp; &nbsp; PdfContentByte canvas = writer.getDirectContentUnder();&nbsp; &nbsp; &nbsp; &nbsp; canvas.paintShading(axial);&nbsp; &nbsp; }}结果如下所示:
随时随地看视频慕课网APP

相关分类

Java
我要回答