Ognjen Nikolic
Ognjen Nikolic

Reputation: 11

Get the used color codes in pdf uploaded document. ItextSharp or any similiar library

I am trying to extract color codes used in pdf on similiar way I am extracting text.Is there any .Net library which from I could extract that ? Any example will be more then helpfull.

        public string CheckDocument(FileInfo doc)
    {
        var stream = doc.OpenRead();
        PdfReader reader = new PdfReader(stream);
        StringWriter output = new StringWriter();
        for (int i = 1; i <= reader.NumberOfPages; i++)
            output.WriteLine(PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy()));
        return output.ToString();
    }

Upvotes: 1

Views: 528

Answers (1)

iPDFdev
iPDFdev

Reputation: 5834

You can enumerate colors with PDF4NET like this:

public void EnumerateColors()
{
    PDFFixedDocument document = new PDFFixedDocument("content.pdf");
    PDFContentExtractor ce = new PDFContentExtractor(document.Pages[0]);
    PDFVisualObjectCollection voc = ce.ExtractVisualObjects(false, false);
    for (int i = 0; i < voc.Count; i++)
    {
        switch (voc[i].Type)
        {
            case PDFVisualObjectType.Text:
                PDFTextVisualObject tvo = voc[i] as PDFTextVisualObject;
                if (tvo.TextFragment.Brush != null)
                {
                    PDFRgbColor rgb = tvo.TextFragment.Brush.Color.ToRgbColor();
                    Console.WriteLine("Text fill color: R: {0}; G: {1}; B: {2}", rgb.R, rgb.G, rgb.B);
                }
                if (tvo.TextFragment.Pen != null)
                {
                    PDFRgbColor rgb = tvo.TextFragment.Pen.Color.ToRgbColor();
                    Console.WriteLine("Text stroke color: R: {0}; G: {1}; B: {2}", rgb.R, rgb.G, rgb.B);
                }
                break;
            case PDFVisualObjectType.Path:
                PDFPathVisualObject pvo = voc[i] as PDFPathVisualObject;
                if (pvo.Brush != null)
                {
                    PDFRgbColor rgb = pvo.Brush.Color.ToRgbColor();
                    Console.WriteLine("Path fill color: R: {0}; G: {1}; B: {2}", rgb.R, rgb.G, rgb.B);
                }
                if (pvo.Pen != null)
                {
                    PDFRgbColor rgb = pvo.Pen.Color.ToRgbColor();
                    Console.WriteLine("Path stroke color: R: {0}; G: {1}; B: {2}", rgb.R, rgb.G, rgb.B);
                }
                break;
        }
    }
}

Disclaimer: I work for the company that develops PDF4NET library.

Upvotes: 1

Related Questions