题
我想在PDFBox中绘制带有透明行的线条和多边形。这是我如何绘制蓝线的一些示例代码,但我无法确定更改颜色的alpha值。
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.setStrokingColor(66, 177, 230);
contentStream.drawLine(100, 100, 200, 200);
解决方案
您不能使用alpha值 java.awt.Color
由于PDFBox仅使用RGB值。根据Javadoc的 public void setStrokingColor(Color color)
这只是:
设置抚摸颜色,指定为RGB。
一种选择是,您将背景颜色设置为抚摸颜色,以使您的行不可见。笔记 - 无形!=透明(因此您将无法获得效果)
其他提示
从PDFBOX 2.0开始 appendRawCommands
被弃用。
float alpha = 0.5f;
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
graphicsState.setStrokingAlphaConstant(alpha);
stream.setGraphicsStateParameters(graphicsState);
// draw line here
您可以使用自定义的扩展图形状态来实现这一目标:
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState(); graphicsState.setStrokingAlphaConstant(0.5f); COSName graphicsStateName = page.getResources().add(graphicsState); try (PDPageContentStream cs = new PDPageContentStream(document, page, true, true, true)) { cs.appendRawCommands("/" + graphicsStateName.getName() + " gs\n"); // draw your line here. }
不隶属于 StackOverflow