Monday, July 28, 2025

DetaSys DETA7 PDF Geometry and Text extractor

 namespace saan_trying_pathspositioningscaling_3000_OFFSETS_PAGES_TRANSFORMATIONS_MATRIX_GRAPHIKS_STATES_graphics_data_extractions_pagewises

{

    //for tekla pdfexchanges the mediabox dont exists

    //////private Stack<GraphicsState> graphicsStateStack = new Stack<GraphicsState>();

    //////private GraphicsState currentGraphicsState = new GraphicsState();

    //////public void EventOccurred(IEventData data, EventType type)

    //////{

    //////    if (type == EventType.RENDER_PATH)

    //////    {

    //////        PathRenderInfo renderInfo = (PathRenderInfo)data;

    //////        ProcessPath(renderInfo);

    //////    }

    //////    else if (type == EventType.RENDER_TEXT)

    //////    {

    //////        TextRenderInfo renderInfo = (TextRenderInfo)data;

    //////        ProcessText(renderInfo);

    //////    }

    //////    else if (type == EventType.SAVE_GRAPHICS_STATE)

    //////    {

    //////        SaveGraphicsState();

    //////    }

    //////    else if (type == EventType.RESTORE_GRAPHICS_STATE)

    //////    {

    //////        RestoreGraphicsState();

    //////    }

    //////    else if (type == EventType.MODIFY_CTM)

    //////    {

    //////        ModifyCtm((Matrix)data);

    //////    }

    //////}

    //////public ICollection<EventType> GetSupportedEvents()

    //////{

    //////    return new HashSet<EventType>

    //////    {

    //////        EventType.RENDER_PATH,

    //////        EventType.RENDER_TEXT,

    //////        EventType.SAVE_GRAPHICS_STATE,

    //////        EventType.RESTORE_GRAPHICS_STATE,

    //////        EventType.MODIFY_CTM

    //////    };

    //////}

        //this is the Graphics and Text extraction Listener

        //this not only extracts the graphics it is to extract the texts also

    public class GraphicsAndText_ExtractionListener : IEventListener

    {

        private readonly List<string> graphicsData = new List<string>();

        private readonly List<string> ListOfStringAsTextDataOnlys = new List<string>();

        private readonly List<string> dxfData = new List<string>();

        private int currentPageNumber;

        private float currentPageWidth;

        private float currentPageHeight;

        private Matrix currentTransformationMatrix = new Matrix();

        private Matrix currentSAANTextTransformationMatrix = new Matrix();

        public void SetPageInfo(int pageNumber, float pageWidth, float pageHeight)

        {

            currentPageNumber = pageNumber;

            currentPageWidth = pageWidth;

            currentPageHeight = pageHeight;

        }// public void SetPageInfo(int pageNumber, float pageWidth, float pageHeight)

        public void EventOccurred(IEventData data, EventType type)

        {

            if (type == EventType.RENDER_PATH)

            {

                PathRenderInfo renderInfo = (PathRenderInfo)data;

                string pathDetails = GetPathDetails(renderInfo);

                graphicsData.Add(pathDetails);

                AddToDxfData(renderInfo, currentPageNumber);

            }// if (type == EventType.RENDER_PATH)

            //graphiks look ok for the Revit pdf files

            //texts are not coming

            //////if (type == EventType.END_TEXT)

            //////{

            //////    TextRenderInfo ___textrenderinfo = (TextRenderInfo)data;

            //////    string ___found_text = ___textrenderinfo.GetText();

            //////    string TextDetailsFound = GetTextDetails(___textrenderinfo);

            //////    ListOfStringAsTextDataOnlys.Add(TextDetailsFound);

            //////    AddTextContentsToToDxfData(___textrenderinfo, currentPageNumber);//to implement

            //////   // to implement 

            //////   // TextRegionEventFilter .Add(

            //////   //////PathRenderInfo renderInfo = (PathRenderInfo)data;

            //////   //////string pathDetails = GetPathDetails(renderInfo);

            //////   //////graphicsData.Add(pathDetails);

            //////   //////AddToDxfData(renderInfo, currentPageNumber);

            //////}//  if (type == EventType.END_TEXT)

            if (type == EventType.RENDER_TEXT)

            {

                TextRenderInfo ___textrenderinfo = (TextRenderInfo)data;

                string ___found_text = ___textrenderinfo.GetText();

                string TextDetailsFound = GetTextDetails(___textrenderinfo);

                ListOfStringAsTextDataOnlys.Add(TextDetailsFound);

                AddTextContentsToToDxfData(___textrenderinfo, currentPageNumber);//to implement

                                                                                 // to implement 

                // TextRegionEventFilter .Add(

                //////PathRenderInfo renderInfo = (PathRenderInfo)data;

                //////string pathDetails = GetPathDetails(renderInfo);

                //////graphicsData.Add(pathDetails);

                //////AddToDxfData(renderInfo, currentPageNumber);

            }//  if (type == EventType.RENDER_TEXT)

            //////if (type == EventType.END_TEXT)

            //////{

            //////    TextRenderInfo ___textrenderinfo = (TextRenderInfo)data;

            //////    string ___found_text = ___textrenderinfo.GetText();

            //////    string TextDetailsFound = GetTextDetails(___textrenderinfo);

            //////    ListOfStringAsTextDataOnlys.Add(TextDetailsFound);

            //////    AddTextContentsToToDxfData(___textrenderinfo, currentPageNumber);//to implement

            //////                                                                     // to implement 

            //////    // TextRegionEventFilter .Add(

            //////    //////PathRenderInfo renderInfo = (PathRenderInfo)data;

            //////    //////string pathDetails = GetPathDetails(renderInfo);

            //////    //////graphicsData.Add(pathDetails);

            //////    //////AddToDxfData(renderInfo, currentPageNumber);

            //////}//  if (type == EventType.END_TEXT)

            //////if (type == EventType.BEGIN_TEXT)

            //////{

            //////    TextRenderInfo ___textrenderinfo = (TextRenderInfo)data;

            //////    string ___found_text = ___textrenderinfo.GetText();

            //////    string TextDetailsFound = GetTextDetails(___textrenderinfo);

            //////    ListOfStringAsTextDataOnlys.Add(TextDetailsFound);

            //////    AddTextContentsToToDxfData(___textrenderinfo, currentPageNumber);//to implement

            //////                                                                     // to implement 

            //////    // TextRegionEventFilter .Add(

            //////    //////PathRenderInfo renderInfo = (PathRenderInfo)data;

            //////    //////string pathDetails = GetPathDetails(renderInfo);

            //////    //////graphicsData.Add(pathDetails);

            //////    //////AddToDxfData(renderInfo, currentPageNumber);

            //////}//  if (type == EventType.BEGIN_TEXT)

        }// public void EventOccurred(IEventData data, EventType type)

        //////public ICollection<EventType> GetSupportedEvents()

        //////{

        //////    return new HashSet<EventType> { EventType.RENDER_PATH };

        //////}// public ICollection<EventType> GetSupportedEvents()

        public ICollection<EventType> GetSupportedEvents()

        {

            return new HashSet<EventType>

            {

                 EventType.BEGIN_TEXT,

                 EventType.RENDER_PATH,

                 EventType.RENDER_TEXT,

                 EventType.END_TEXT

                //EventType.SAVE_GRAPHICS_STATE,

               // EventType.RESTORE_GRAPHICS_STATE,

                //EventType.MODIFY_CTM

            };

        }

        private string GetPathDetails(PathRenderInfo renderInfo)

        {

            StringBuilder details = new StringBuilder();

            details.AppendLine($"Page Number: {currentPageNumber}, Page Width: {currentPageWidth}, Page Height: {currentPageHeight}");

            details.AppendLine("Path Details:");

            details.AppendLine($"Operation: {renderInfo.GetOperation()}");

            details.AppendLine($"Rule: {renderInfo.GetRule()}");

            foreach (Subpath subpath in renderInfo.GetPath().GetSubpaths())

            {

                foreach (IShape shape in subpath.GetSegments())

                {

                    if (shape is Line)

                    {

                        Line line = (Line)shape;

                        float[] start = TransformPoint(line.p1, renderInfo.GetCtm());

                        float[] end = TransformPoint(line.p2, renderInfo.GetCtm());

                        details.AppendLine($"Line: Start({start[0]}, {start[1]}) - End({end[0]}, {end[1]})");

                    }

                    else if (shape is BezierCurve)

                    {

                        BezierCurve curve = (BezierCurve)shape;

                        int controlPointCounter = 0;

                        foreach (DETA7.Kernel.Geom.Point controlPoint in curve.controlPoints)

                        {

                            float[] transformedControlPoint = TransformPoint(controlPoint, renderInfo.GetCtm());

                            details.AppendLine($"Curve: Control Point {controlPointCounter} - x: {transformedControlPoint[0]}, y: {transformedControlPoint[1]}");

                            controlPointCounter++;

                        }// foreach (DETA7.Kernel.Geom.Point controlPoint in curve.controlPoints)

                    }// else if (shape is BezierCurve)

                }// foreach (IShape shape in subpath.GetSegments())

            }// foreach (Subpath subpath in renderInfo.GetPath().GetSubpaths())

            return details.ToString();

        }// private string GetPathDetails(PathRenderInfo renderInfo)

        //////private string GetTextDetails(TextRenderInfo FoundTextRenderInfo)

        //////{

        //////    StringBuilder detailsForTexts = new StringBuilder();

        //////    // To implement 

        //////    detailsForTexts.AppendLine("Text= " +FoundTextRenderInfo.text);

        //////    detailsForTexts.AppendLine("textMatrix = " + FoundTextRenderInfo.textMatrix.ToString());

        //////    detailsForTexts.AppendLine("GetUnscaledWidth = " + FoundTextRenderInfo.GetUnscaledWidth().ToString());

        //////    return detailsForTexts.ToString();

        //////}//private string GetTextDetails(TextRenderInfo FoundTextRenderInfo)

        //////private void AddTextContentsToToDxfData(TextRenderInfo FoundTextRenderInfo, int pageNumber)

        //////{

        //////    float offsetspageswises = 30000 * (pageNumber - 1);

        //////    DETA7.Kernel.Geom.Point TextInsertionsPoint= FoundTextRenderInfo.

        //////    float[] transformedControlPoint = TransformPoint(controlPoint, FoundTextRenderInfo.GetCtm());

        //////    To implement dxf generations codes

        //////        renderInfo.

        //////}//private void AddTextContentsToToDxfData(TextRenderInfo renderInfo, int pageNumber)

        /// <summary>

        /// 

        /// 

        /// 

        /// 

        /// 

        /// </summary>

        /// <param name="renderInfo"></param>

        /// <param name="pageNumber"></param>

        private string GetTextDetails(TextRenderInfo FoundTextRenderInfo)

        {

            StringBuilder detailsForTexts = new StringBuilder();

            detailsForTexts.AppendLine("Text = " + FoundTextRenderInfo.GetText());

            detailsForTexts.AppendLine("Text Matrix = " + FoundTextRenderInfo.GetTextMatrix().ToString());

            detailsForTexts.AppendLine("Unscaled Width = " + FoundTextRenderInfo.GetUnscaledWidth().ToString());

            LineSegment baseline = FoundTextRenderInfo.GetBaseline();

            detailsForTexts.AppendLine("Baseline Start = " + baseline.GetStartPoint().ToString());

            detailsForTexts.AppendLine("Baseline End = " + baseline.GetEndPoint().ToString());

            detailsForTexts.AppendLine("Font Size = " + FoundTextRenderInfo.GetFontSize().ToString());

            detailsForTexts.AppendLine("Text Rise = " + FoundTextRenderInfo.GetRise().ToString());

            return detailsForTexts.ToString();

        }//private string GetTextDetails(TextRenderInfo FoundTextRenderInfo)

        private void AddTextContentsToToDxfData(TextRenderInfo FoundTextRenderInfo, int pageNumber)

        {

            float offsetspageswises = 30000 * (pageNumber - 1);

            LineSegment baseline = FoundTextRenderInfo.GetBaseline();

            Vector startPoint = baseline.GetStartPoint();

            float x = startPoint.Get(Vector.I1);

            float y = startPoint.Get(Vector.I2);

            string text = FoundTextRenderInfo.GetText();

            // DXF TEXT entity

            //  TO DO

            //  string dxfTextEntity =  $"0\nTEXT\n8\n0\n10\n{offsetspageswises + x}\n20\n{y}\n30\n0.0\n40\n{FoundTextRenderInfo.GetFontSize()}\n1\n{text}\n";

      //      LineSegment baseline = FoundTextRenderInfo.GetBaseline();

            Vector start = baseline.GetStartPoint();

            Vector end = baseline.GetEndPoint();

            float dx = end.Get(Vector.I1) - start.Get(Vector.I1);

            float dy = end.Get(Vector.I2) - start.Get(Vector.I2);

            float rotationAngle = (float)(Math.Atan2(dy, dx) * (180.0 / Math.PI)); // DXF expects degrees

            float fontHeight = FoundTextRenderInfo.GetFontSize();

            float fontWidth = FoundTextRenderInfo.GetUnscaledWidth(); // Optional: scale this if needed

            LineSegment ascentLine = FoundTextRenderInfo.GetAscentLine();

            float textHeight = ascentLine.GetLength(); // More accurate than GetFontSize()

            //  string dxfTextEntity = $"0\nTEXT\n8\n0\n10\n{offsetspageswises + x}\n20\n{y}\n30\n0.0\n40\n{FoundTextRenderInfo.GetFontSize()}\n1\n{text}";

            //this also dont put the proper text height on dxf (sometimes texts look larger on dxf(than the pdf) sometimes looks smaller in dxf than it is in pdf(i think we need to do some additional rendering calculations for the text heights and text widths 

            ///          string dxfTextEntity = $"0\nTEXT\n8\n0\n10\n{offsetspageswises + x}\n20\n{y}\n30\n0.0\n40\n{fontHeight}\n50\n{rotationAngle}\n1\n{text}";

            ///     

            //////detailsForTexts.AppendLine("Text = " + FoundTextRenderInfo.GetText());

            //////detailsForTexts.AppendLine("Text Matrix = " + FoundTextRenderInfo.GetTextMatrix().ToString());

            //////detailsForTexts.AppendLine("Unscaled Width = " + FoundTextRenderInfo.GetUnscaledWidth().ToString());

            //////LineSegment baseline = FoundTextRenderInfo.GetBaseline();

            //////detailsForTexts.AppendLine("Baseline Start = " + baseline.GetStartPoint().ToString());

            //////detailsForTexts.AppendLine("Baseline End = " + baseline.GetEndPoint().ToString());

            //////detailsForTexts.AppendLine("Font Size = " + FoundTextRenderInfo.GetFontSize().ToString());

            //////detailsForTexts.AppendLine("Text Rise = " + FoundTextRenderInfo.GetRise().ToString());

            float fontSize = FoundTextRenderInfo.GetFontSize();

           // string fontName= FoundTextRenderInfo.GetFont()fontName

                string fontName = FoundTextRenderInfo.GetFont().GetFontProgram().GetFontNames().GetFontName();

            //string color = FoundTextRenderInfo.GetFillColor().ToString();

            string color = FoundTextRenderInfo.GetFillColor().ToString();

            float wordspacingfound = FoundTextRenderInfo.GetWordSpacing();

            int aciColor = 0;

            int r = 0;

            int g = 0;

            int b = 0;

            try

            {

            DETA7.Kernel.Colors.Color fillColor = FoundTextRenderInfo.GetFillColor();

             r = (int)(fillColor.GetColorValue()[0] * 255);

             g = (int)(fillColor.GetColorValue()[1] * 255);

             b = (int)(fillColor.GetColorValue()[2] * 255);

             aciColor = GetClosestAciColor(r, g, b); // You can define this function or use fixed values

            }

            catch (Exception excp)

            {

                aciColor = 6;

            }

            // Create layer name

            string layerName = $"{fontSize}_{rotationAngle}_{wordspacingfound}_{fontName}_{color}";

            layerName = layerName.Replace(",", "_")

                .Replace(".", "_").Replace(";", "_").Replace(" ", "_")

                .Replace("+", "_").Replace("/", "_").Replace("\\", "_")

                .Replace("DETA7_Kernel_Colors_", "");

          //  string dxfTextEntity = $"0\nTEXT\n8\n{layerName}\n10\n{offsetspageswises + x}\n20\n{y}\n30\n0.0\n40\n{textHeight}\n50\n{rotationAngle}\n1\n{text}";

            string dxfTextEntity = $"0\nTEXT\n8\n{layerName}\n10\n{offsetspageswises + x}\n20\n{y}\n30\n0.0\n40\n{textHeight}\n50\n{rotationAngle}\n62\n{aciColor}\n1\n{text}";

            string trueColor = $"420\n{(r << 16) + (g << 8) + b}";

            //sanjoynath text

            string dxfTextEntity_saans = $"0\nTEXT\n8\n0\n10\n{offsetspageswises + x}\n20\n{y}\n30\n0.0\n40\n{0.01}\n50\n{rotationAngle}\n1\n"+"SANJOYNATH";

            dxfData.Add(dxfTextEntity);

            dxfData.Add(dxfTextEntity_saans);//SanjoyNath texts

            // Create layer name

            // string layerName = $"{fontSize}_{rotationAngle}_{fontName}_{color}";

            // Add

            //////// Add text to DXF content

            //////dxfContent.AppendLine("0");

            //////dxfContent.AppendLine("TEXT");

            //////dxfContent.AppendLine("8");

            //////dxfContent.AppendLine(layerName);

            //////dxfContent.AppendLine("10");

            //////dxfContent.AppendLine(offsetX.ToString());

            //////dxfContent.AppendLine("20");

            //////dxfContent.AppendLine(offsetY.ToString());

            //////dxfContent.AppendLine("40");

            //////dxfContent.AppendLine(fontSize.ToString());

            //////dxfContent.AppendLine("50");

            //////dxfContent.AppendLine(rotationAngle.ToString());

            //////dxfContent.AppendLine("1");

            //////dxfContent.AppendLine(text);

        }//private void AddTextContentsToToDxfData(TextRenderInfo FoundTextRenderInfo, int pageNumber)

        private int GetClosestAciColor(int r, int g, int b)

        {

            // Basic ACI color map (partial, can be extended)

            Dictionary<int, (int R, int G, int B)> aciColors = new Dictionary<int, (int, int, int)>

    {

        {1, (255, 0, 0)},     // Red

        {2, (255, 255, 0)},   // Yellow

        {3, (0, 255, 0)},     // Green

        {4, (0, 255, 255)},   // Cyan

        {5, (0, 0, 255)},     // Blue

        {6, (255, 0, 255)},   // Magenta

        {7, (255, 255, 255)}, // White

        {8, (128, 128, 128)}, // Gray

        {9, (192, 192, 192)}  // Light Gray

    };

            int closestIndex = 7; // Default to white

            double minDistance = double.MaxValue;

            foreach (var kvp in aciColors)

            {

                int aci = kvp.Key;

                var (r2, g2, b2) = kvp.Value;

                double distance = Math.Sqrt(Math.Pow(r - r2, 2) + Math.Pow(g - g2, 2) + Math.Pow(b - b2, 2));

                if (distance < minDistance)

                {

                    minDistance = distance;

                    closestIndex = aci;

                }

            }

            return closestIndex;

        }//private int GetClosestAciColor(int r, int g, int b)

        private void AddToDxfData(PathRenderInfo renderInfo, int pageNumber)

        {

            float offsetspageswises = 30000 * (pageNumber - 1);

            // Extract styling info

            float lineWidth = renderInfo.GetLineWidth();

            string lineType = renderInfo.GetLineDashPattern()?.ToString() ?? "Continuous";

            string lineCap = renderInfo.GetLineCapStyle().ToString();

            string lineJoin = renderInfo.GetLineJoinStyle().ToString();

            DETA7.Kernel.Colors.Color strokeColor = renderInfo.GetStrokeColor();

            string STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED = "";

            //////int r = (int)(strokeColor.GetColorValue()[0] * 255);

            //////int g = (int)(strokeColor.GetColorValue()[1] * 255);

            //////int b = (int)(strokeColor.GetColorValue()[2] * 255);

            //////int aciColor = GetClosestAciColor(r, g, b);

            int aciColor = 0;

            int r = 0;

            int g = 0;

            int b = 0;

            try

            {

               /// DETA7.Kernel.Colors.Color fillColor = FoundTextRenderInfo.GetFillColor();

                r = (int)(strokeColor.GetColorValue()[0] * 255);

                g = (int)(strokeColor.GetColorValue()[1] * 255);

                b = (int)(strokeColor.GetColorValue()[2] * 255);

                aciColor = GetClosestAciColor(r, g, b); // You can define this function or use fixed values

            }

            catch (Exception excp)

            {

                aciColor = 6;

            }

            // Create DXF-safe layer name

            //  string rawLayerName = $"{lineWidth}_{lineType}_{lineCap}_{lineJoin}_{aciColor}";

            //12_5424_0_GHQWKA_Arial_DETA7_Kernel_Colors_DeviceGray

            //strokeColor

            string rawLayerName = $"{lineWidth}_{lineType}_{lineCap}_{lineJoin}_{strokeColor.ToString()}";

            string layerName = System.Text.RegularExpressions.Regex.Replace(rawLayerName, @"[^a-zA-Z0-9_]", "_")

                .Replace("DETA7_Kernel_Colors_","");

           ////// layerName = layerName +"_"+ renderInfo.GetPath().GetSubpaths().Count;

            int subpathcount = 0;

            int linecountinshape = 0;

            int BezierCurvecountinshape = 0;

            subpathcount = renderInfo.GetPath().GetSubpaths().Count;

            foreach (Subpath subpath in renderInfo.GetPath().GetSubpaths())

            {

                List<IShape> segments = subpath.GetSegments().ToList();

                // Ensure loop closure if needed

                //  if (segments.Count > 1 && segments[0] is Line first && segments[1] is Line last)

                if (segments.Count > 1 && segments[0] is Line first && segments[segments.Count-1] is Line last)

                {

                    if (!PointsEqual(first.p1, last.p2))

                    {

                        segments.Add(new Line(last.p2, first.p1));

                        //SAAN ADDS THESE

                        STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED = "CLOSED";

                        aciColor = 3;

                        if (STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("CLOSED"))

                        {

                            //dont add

                        }//if(!STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("CLOSED"))

                        else

                        {

                            layerName = layerName + "_" + STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED;

                        }//end of else of   if (STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("CLOSED"))

                    }//if (!PointsEqual(first.p1, last.p2))

                    else

                    {

                        //SAAN ADDS THESE

                        STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED = "OPEN";

                        aciColor = 1;

                        //////   layerName = layerName + "_" + STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED;

                        ///

                        if (STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("OPEN"))

                        {

                            //dont add

                        }//if(!STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("OPEN"))

                        else

                        {

                            layerName = layerName + "_" + STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED;

                        }//end of else of   if (STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("OPEN"))

                    }//END OF ELSE OF if (!PointsEqual(first.p1, last.p2))

                }// if (segments.Count > 1 && segments[0] is Line first && segments[segments.Count-1] is Line last)

                // layerName = layerName + "_" + renderInfo.GetPath().GetSubpaths().Count;

                foreach (IShape shape in segments)

                {

                    if (shape is Line line)

                    {

                        linecountinshape++;

                        float[] start = TransformPoint(line.p1, renderInfo.GetCtm());

                        float[] end = TransformPoint(line.p2, renderInfo.GetCtm());

                        //         string dxfLine = $"0\nLINE\n8\n{layerName}\n10\n{offsetspageswises + start[0]}\n20\n{start[1]}\n30\n0.0\n11\n{offsetspageswises + end[0]}\n21\n{end[1]}\n31\n0.0\n62\n{aciColor}\n370\n{(int)(lineWidth * 100)}";

                        //SAAN ADDS THESE

                        STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED = "LINEAR";

                        aciColor = 22;

                        // layerName = layerName + "_" + STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED;

                        if (STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("LINEAR"))

                        {

                            //dont add

                        }//if(!STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("LINEAR"))

                        else

                        {

                            layerName = layerName + "_" + STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED;

                        }//end of else of   if (STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("LINEAR"))

                        string dxfLine = $"0\nLINE\n8\n{layerName}\n10\n{offsetspageswises + start[0]}\n20\n{start[1]}\n30\n0.0\n11\n{offsetspageswises + end[0]}\n21\n{end[1]}\n31\n0.0\n62\n{aciColor}";

                        dxfData.Add(dxfLine);

                    }

                    else if (shape is BezierCurve curve)

                    {

                        BezierCurvecountinshape++;

                        float[] start = TransformPoint(curve.controlPoints[0], renderInfo.GetCtm());

                        float[] control1 = TransformPoint(curve.controlPoints[1], renderInfo.GetCtm());

                        float[] control2 = TransformPoint(curve.controlPoints[2], renderInfo.GetCtm());

                        float[] end = TransformPoint(curve.controlPoints[3], renderInfo.GetCtm());

                        int numSegments = 10;

                        float tStep = 1.0f / numSegments;

                        float[] prevPoint = start;

                        for (int i = 1; i <= numSegments; i++)

                        {

                            float t = i * tStep;

                            float[] point = CalculateBezierPoint(t, start, control1, control2, end);

                          ///  string dxfCurveSegment = $"0\nLINE\n8\n{layerName}\n10\n{offsetspageswises + prevPoint[0]}\n20\n{prevPoint[1]}\n30\n0.0\n11\n{offsetspageswises + point[0]}\n21\n{point[1]}\n31\n0.0\n62\n{aciColor}\n370\n{(int)(lineWidth * 100)}";

                            //SAAN ADDS THESE

                             STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED = "BEZIERED";

                             aciColor = 11;

                            if (STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("BEZIERED"))

                            {

                                //dont add

                            }//if(!STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("BEZIERED"))

                            else

                            {

                                layerName = layerName + "_" + STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED;

                            }//end of else of   if (STRING_LINEPATHCATEGORY___CLOSED_OPEN_LINEAR_BEZIERED.Contains("BEZIERED"))

                            string dxfCurveSegment = $"0\nLINE\n8\n{layerName}\n10\n{offsetspageswises + prevPoint[0]}\n20\n{prevPoint[1]}\n30\n0.0\n11\n{offsetspageswises + point[0]}\n21\n{point[1]}\n31\n0.0\n62\n{aciColor}";

                            dxfData.Add(dxfCurveSegment);

                            prevPoint = point;

                        }//for (int i = 1; i <= numSegments; i++)

                    }// else if (shape is BezierCurve curve)

                }// foreach (IShape shape in segments)

            }// foreach (Subpath subpath in renderInfo.GetPath().GetSubpaths())

            ///cant we add all the LINE to dxf after all the data accumulations are done???????? if we can do that then we can filter things with more proper layer names such that we can filter the data more properly with the global conditions

            ///for each path there are several subpaths and several line shapes several beziere shapes and classifying these line shapes , beziere shapes closedness of polygons , if the curve is like circle or if that is like splines or if these total path objects semantically looks like ellipse or circles or rectangles or if there are object bounding box AABB like properties then we can accumulate all these things properly

            /////if we can put the informations to the layers of these objects in the dxf files then it is more  helpful to extract more meaningfull informations for engineering drawings

        }////  private void AddToDxfData(PathRenderInfo renderInfo, int pageNumber)

        // Helper to check if two points are equal within a tolerance

        private bool PointsEqual(DETA7.Kernel.Geom.Point p1, DETA7.Kernel.Geom.Point p2, float tolerance = 0.01f)

        {

            return Math.Abs(p1.GetX() - p2.GetX()) < tolerance && Math.Abs(p1.GetY() - p2.GetY()) < tolerance;

        }//private bool PointsEqual(DETA7.Kernel.Geom.Point p1, DETA7.Kernel.Geom.Point p2, float tolerance = 0.01f)

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>

        ///  NOT IN USE

        /// </summary>

        /// <param name="renderInfo"></param>

        /// <param name="pageNumber"></param>

        private void AddToDxfData___THISWASWORKINGNOWENHANCING(PathRenderInfo renderInfo, int pageNumber)

        {

            float offsetspageswises = 30000 * (pageNumber - 1);

            foreach (Subpath subpath in renderInfo.GetPath().GetSubpaths())

            {

                foreach (IShape shape in subpath.GetSegments())

                {

                    if (shape is Line)

                    {

                        Line line = (Line)shape;

                        float[] start = TransformPoint(line.p1, renderInfo.GetCtm());

                        float[] end = TransformPoint(line.p2, renderInfo.GetCtm());

                        dxfData.Add($"0\nLINE\n8\n0\n10\n{offsetspageswises + start[0]}\n20\n{start[1]}\n30\n0.0\n11\n{offsetspageswises + end[0]}\n21\n{end[1]}\n31\n0.0");

                    }

                    else if (shape is BezierCurve)

                    {

                        BezierCurve curve = (BezierCurve)shape;

                        float[] start = TransformPoint(curve.controlPoints[0], renderInfo.GetCtm());

                        float[] control1 = TransformPoint(curve.controlPoints[1], renderInfo.GetCtm());

                        float[] control2 = TransformPoint(curve.controlPoints[2], renderInfo.GetCtm());

                        float[] end = TransformPoint(curve.controlPoints[3], renderInfo.GetCtm());

                        // Approximate the Bezier curve with a series of lines

                        int numSegments = 10; // Number of line segments to approximate the curve

                        float tStep = 1.0f / numSegments;

                        float[] prevPoint = start;

                        for (int i = 1; i <= numSegments; i++)

                        {

                            float t = i * tStep;

                            float[] point = CalculateBezierPoint(t, start, control1, control2, end);

                            dxfData.Add($"0\nLINE\n8\n0\n10\n{offsetspageswises + prevPoint[0]}\n20\n{prevPoint[1]}\n30\n0.0\n11\n{offsetspageswises + point[0]}\n21\n{point[1]}\n31\n0.0");

                            prevPoint = point;

                        }// for (int i = 1; i <= numSegments; i++)

                    }// else if (shape is BezierCurve)

                }// foreach (IShape shape in subpath.GetSegments())

            }// foreach (Subpath subpath in renderInfo.GetPath().GetSubpaths())

        }// private void AddToDxfData(PathRenderInfo renderInfo, int pageNumber)

        private float[] CalculateBezierPoint(float t, float[] p0, float[] p1, float[] p2, float[] p3)

        {

            float u = 1 - t;

            float tt = t * t;

            float uu = u * u;

            float uuu = uu * u;

            float ttt = tt * t;

            float[] point = new float[2];

            point[0] = uuu * p0[0]; // uuu * p0

            point[0] += 3 * uu * t * p1[0]; // 3 * uu * t * p1

            point[0] += 3 * u * tt * p2[0]; // 3 * u * tt * p2

            point[0] += ttt * p3[0]; // ttt * p3

            point[1] = uuu * p0[1]; // uuu * p0

            point[1] += 3 * uu * t * p1[1]; // 3 * uu * t * p1

            point[1] += 3 * u * tt * p2[1]; // 3 * u * tt * p2

            point[1] += ttt * p3[1]; // ttt * p3

            return point;

        }// private float[] CalculateBezierPoint(float t, float[] p0, float[] p1, float[] p2, float[] p3)

        ////////////private float[] TransformPoint(Vector point, Matrix matrix)

        ////////////{

        ////////////    float x = point.Get(Vector.I1);

        ////////////    float y = point.Get(Vector.I2);

        ////////////    float transformedX = matrix.Get(Matrix.I11) * x + matrix.Get(Matrix.I12) * y + matrix.Get(Matrix.I13);

        ////////////    float transformedY = matrix.Get(Matrix.I21) * x + matrix.Get(Matrix.I22) * y + matrix.Get(Matrix.I23);

        ////////////    return new float[] { transformedX, transformedY };

        ////////////}// private float[] TransformPoint(Vector point, Matrix matrix)

        //////private float[] TransformPoint(DETA7.Kernel.Geom.Point point, Matrix matrix)

        //////{

        //////    float x = (float)point.GetX();

        //////    float y = (float)point.GetY();

        //////    float transformedX = matrix.Get(Matrix.I11) * x + matrix.Get(Matrix.I12) * y + matrix.Get(Matrix.I13);

        //////    float transformedY = matrix.Get(Matrix.I21) * x + matrix.Get(Matrix.I22) * y + matrix.Get(Matrix.I23);

        //////    return new float[] { transformedX, transformedY };

        //////}// private float[] TransformPoint(DETA7.Kernel.Geom.Point point, Matrix matrix)

        private float[] TransformPoint(Vector point, Matrix matrix)

        {

            float x = point.Get(Vector.I1);

            float y = point.Get(Vector.I2);

            float transformedX = matrix.Get(Matrix.I11) * x + matrix.Get(Matrix.I12) * y + matrix.Get(Matrix.I13);

            float transformedY = matrix.Get(Matrix.I21) * x + matrix.Get(Matrix.I22) * y + matrix.Get(Matrix.I23);

            return new float[] { transformedX, transformedY };

        }// private float[] TransformPoint(Vector point, Matrix matrix)

        private float[] TransformPoint(DETA7.Kernel.Geom.Point point, Matrix matrix)

        {

            float x = (float)point.GetX();

            float y = (float)point.GetY();

            float transformedX = matrix.Get(Matrix.I11) * x + matrix.Get(Matrix.I12) * y + matrix.Get(Matrix.I13);

            float transformedY = matrix.Get(Matrix.I21) * x + matrix.Get(Matrix.I22) * y + matrix.Get(Matrix.I23);

            return new float[] { transformedX, transformedY };

        }// private float[] TransformPoint(DETA7.Kernel.Geom.Point point, Matrix matrix)

        public void WriteGraphicsData(string outputFilePath)

        {

            graphicsData.AddRange(ListOfStringAsTextDataOnlys);

            File.WriteAllLines(outputFilePath, graphicsData);

        }// public void WriteGraphicsData(string outputFilePath)

        public void WriteDxfData(string outputFilePath)

        {

            List<string> dxfContent = new List<string>();

            List<string> dxfHeader = new List<string>

            {

                "0",

                "SECTION",

                "2",

                "HEADER",

                "0",

                "ENDSEC",

                "0",

                "SECTION",

                "2",

                "TABLES",

                "0",

                "ENDSEC",

                "0",

                "SECTION",

                "2",

                "BLOCKS",

                "0",

                "ENDSEC",

                "0",

                "SECTION",

                "2",

                "ENTITIES"

            };

            List<string> dxfFooter = new List<string>

            {

                "0",

                "ENDSEC",

                "0",

                "SECTION",

                "2",

                "OBJECTS",

                "0",

                "ENDSEC",

                "0",

                "EOF"

            };

            dxfContent = new List<string>();

            dxfContent.AddRange(dxfHeader);

            dxfContent.AddRange(dxfData);

            dxfContent.AddRange(dxfFooter);

            File.WriteAllLines(outputFilePath, dxfContent);

        }// public void WriteDxfData(string outputFilePath)

    }// public class GraphicsAndText_ExtractionListener : IEventListener

    public class PdfGraphicsExtractor_to_singles_30000_offsets_dxf____trying_with_new_scales_translations

    {

        public static void publicstaticvoid___read_inputFilePath_dump_pagewise_graphics_data(string selected_pdffilesnames)

        {

            string inputFilePath = selected_pdffilesnames;

            string outputFilePath = inputFilePath + "___dumping_pagewises_graphics_data.txt";

            string dxfFilePath = inputFilePath + "___pagewises_graphics_data.dxf";

            PdfReader reader = new PdfReader(inputFilePath);

            PdfDocument pdfDoc = new PdfDocument(reader);

            GraphicsAndText_ExtractionListener listener = new GraphicsAndText_ExtractionListener();

            // Create a PdfCanvasProcessor

            PdfCanvasProcessor processor = new PdfCanvasProcessor(listener);

            // Process each page

            for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)

            {

                PdfPage page = pdfDoc.GetPage(i);

                float pageWidth = page.GetPageSize().GetWidth();

                float pageHeight = page.GetPageSize().GetHeight();

                listener.SetPageInfo(i, pageWidth, pageHeight);

                processor.ProcessPageContent(page);

            }// for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)

            // Write the extracted graphics data to a file

            listener.WriteGraphicsData(outputFilePath);

            // Write the extracted graphics data to a DXF file

            listener.WriteDxfData(dxfFilePath);

            // Close the PdfDocument

            pdfDoc.Close();

            Console.WriteLine("Graphics extraction and DXF generation completed successfully.");

            System.Windows.Forms.MessageBox.Show("Graphics extraction and DXF generation completed successfully.");

        }//public static void publicstaticvoid___read_inputFilePath_dump_pagewise_graphics_data(string selected_pdffilesnames)

    }//  public class PdfGraphicsExtractor_to_singles_30000_offsets_dxf____trying_with_new_scales_translations

}//namespace saan_trying_pathspositioningscaling_3000_OFFSETS_PAGES_TRANSFORMATIONS_MATRIX_GRAPHIKS_STATES_graphics_data_extractions_pagewises

No comments:

Post a Comment