[英]How to get a BaseColor from a color source in iText
我正在使用 iText 解析 PDF 文档,我想知道页面中线条和矩形的颜色。 我正在使用此代码进行解析:
private PdfDictionary getColorDictionary(PdfDictionary resourcesDic) {
PdfDictionary colorDict = resourcesDic.getAsDict(PdfName.COLORSPACE);
return colorDict;
}
public void decode(File file) throws IOException {
PdfReader reader = new PdfReader(file.toURI().toURL());
int numberOfPages = reader.getNumberOfPages();
ProcessorListener listener = new ProcessorListener ();
PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);
for (int pageNumber = 1; pageNumber <= numberOfPages; pageNumber++) {
PdfDictionary pageDic = reader.getPageN(pageNumber);
PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);
PdfDictionary colorSpaceDic = getColorDictionary(resourcesDic);
listener.setResources(colorSpaceDic);
processor.processContent(ContentByteUtils.getContentBytesForPage(reader, pageNumber), resourcesDic);
}
}
我的听众有以下代码,我将其简化为仅显示获取每个页面中的图形元素的部分:
public class ProcessorListener implements ExtRenderListener {
private PdfDictionary colorSpaceDic = null;
public void setResources(PdfDictionary colorSpaceDic) {
this.colorSpaceDic = colorSpaceDic;
}
@Override
public void beginTextBlock() {
}
@Override
public void renderText(TextRenderInfo tri) {
}
@Override
public void renderImage(ImageRenderInfo iri) {
}
@Override
public Path renderPath(PathPaintingRenderInfo renderInfo) {
GraphicsState graphicsState;
try {
graphicsState = getGraphicsState(renderInfo);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
return null;
}
if ((renderInfo.getOperation() & PathPaintingRenderInfo.STROKE) != 0) {
PdfName resource = graphicsState.getColorSpaceStroke();
if (resource != null && colorSpaceDic != null) {
PdfObject obj = colorSpaceDic.get(resource);
System.err.println("STROKE: " + obj);
}
}
if ((renderInfo.getOperation() & PathPaintingRenderInfo.FILL) != 0) {
PdfName resource = graphicsState.getColorSpaceStroke();
if (resource != null && colorSpaceDic != null) {
PdfObject obj = colorSpaceDic.get(resource);
System.err.println("FILL: " + obj);
}
}
}
return null;
}
此代码正确执行,但与 afill 或 stroke 关联的每个PDFObject
都是PRIndirectReference
。 如何获取与此参考相关的BaseColor
?
我还尝试使用以下代码(例如用于填充):
BaseColor fillColor = graphicsState.getFillColor();
但颜色始终为空。 文档中不仅有黑色形状(我假设这是默认的),而且还有绿色或蓝色线条。
根据 mkl 的说法,我使用 Acrobat Reader(打印选项)或 Edge 将 PDF 文档保存到另一个文档,并且结果文档中没有空颜色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.