使用PDFBox绘制透明线条
我想在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);
您不能使用java.awt.Color
的alpha值,因为PDFBox仅使用RGB值。 根据public void setStrokingColor(Color color)
javadoc,它只是:
设置描边为RGB的描边颜色。
一种选择可能是您将背景颜色设置为描边颜色,以使您的线条不可见。 注意 –不可见!=透明(所以你不会看到透视效果)
您可以使用自定义扩展图形状态来实现此目的:
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”); //在这里画线。 }
从PDFBox 2.0 appendRawCommands
,不推荐使用appendRawCommands
。
float alpha = 0.5f; PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState(); graphicsState.setStrokingAlphaConstant(alpha); stream.setGraphicsStateParameters(graphicsState); // draw line here