[英]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.