Java 使用PDFBox绘制透明线

Java 使用PDFBox绘制透明线,java,pdfbox,Java,Pdfbox,我想用PDFBox中的透明线绘制线和多边形。下面是我如何绘制蓝线的一些示例代码,但我无法确定如何更改颜色的alpha值 PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(document, page); contentStream

我想用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"); // draw your line here. } PDExtendedGraphicsState graphicsState=新的PDExtendedGraphicsState(); 图形状态设定行程α常数(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开始,不推荐使用AppendRaw命令

    float alpha = 0.5f;
    PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
    graphicsState.setStrokingAlphaConstant(alpha);
    stream.setGraphicsStateParameters(graphicsState);
    // draw line here

这个问题的其他答案清楚地表明,PDF中的透明度是可能的,即使使用PDFBox也是如此。不知何故,这会导致流上的setGraphicsStateParameters()中出现NullPointerException,或者graphicsState对象上出现null?GraphicsState不应为null,因为它正在初始化。内容流没有资源。这可能取决于代码,因为有时不需要资源,但当内容流需要资源对象时,应该自动实例化它。解决方案是使用stream.setResources(newpdresources());