Draw transparent lines with PDFBox

走远了吗. 提交于 2019-12-09 03:24:46

问题


I would like to draw lines and polygons with transparent lines in PDFBox. Here is some sample code of how I am drawing a blue line, but I cannot figure out to change the alpha value of the color.

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);  

回答1:


You cannot use the alpha value of the java.awt.Color as PDFBox only uses the RGB value. As per javadoc of public void setStrokingColor(Color color) it just:

Set the stroking color, specified as RGB.

One option could be that you set the background color as the stroking color to make your line invisible. NOTE - Invisible != Transparent (so you won't get the see through effect)




回答2:


As of PDFBox 2.0 appendRawCommands is deprecated.

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



回答3:


You can achieve this by using a custom extended graphics state:

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.
}


来源:https://stackoverflow.com/questions/4540593/draw-transparent-lines-with-pdfbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!