Export polyline coordinates to CSV file

Discussion forum for C++ and script developers who are using the QCAD development platform or who are looking to contribute to QCAD (translations, documentation, etc).

Moderator: andrew

Forum rules

Always indicate your operating system and QCAD version.

Attach drawing files, scripts and screenshots.

Post one question per topic.

Post Reply
TonyE
Newbie Member
Posts: 4
Joined: Tue Aug 11, 2020 11:43 pm

Export polyline coordinates to CSV file

Post by TonyE » Wed Aug 12, 2020 2:51 pm

Hi all,

I am new to QCAD and looking for advice/assistance.

I am looking to export the coordinates of polylines to a CSV file. Andrew provided me with this reference code and if I knew what I was doing I could probably extend it.

https://github.com/qcad/qcad/blob/maste ... olyline.js

My goal is to export the coordinates of the polyline's nodes with each polyline taking up only one row of the CSV file. I'd also like each row to contain the value of a custom field I've added myself (a type of identification number). For example, each line might look like ID,x1,y1,x2,y2,x3,y3,x4,y4, x5,y5 (only 5 points max since my shapes will almost always be closed triangles, and sometimes closed rectangles).

Any advice is appreciated. Is this even possible?

Thanks,

TonyE

TonyE
Newbie Member
Posts: 4
Joined: Tue Aug 11, 2020 11:43 pm

Re: Export polyline coordinates to CSV file

Post by TonyE » Wed Aug 12, 2020 5:45 pm

Looks like I incorrectly copied the link:

https://github.com/qcad/qcad/blob/maste ... olyline.js

User avatar
andrew
Site Admin
Posts: 9037
Joined: Fri Mar 30, 2007 6:07 am

Re: Export polyline coordinates to CSV file

Post by andrew » Thu Aug 13, 2020 8:51 am

Yes, it's possible. For the ID, you can assign custom properties to the polyline entities (for example in the property editor or in the script). These properties are stored with the DXF/DWG file.

For the coordinates, you can easily adjust the example script accordingly.

CVH
Premier Member
Posts: 3416
Joined: Wed Sep 27, 2017 4:17 pm

Re: Export polyline coordinates to CSV file

Post by CVH » Thu Aug 13, 2020 1:05 pm

Hi,
That won't be a problem.
I made an enhanced version of DumpPolyline a pretty while ago.
It documents almost any basic entities from a selection.
Not ready for the masses but functional.
Meanwhile I moved on to a more complex development task but I do use it 'as is' quite often.

With some copy and paste I'll see what I can do.
Your serial setup is a bit uncommon.
the value of a custom field I've added myself
is another thing.
If it's the list {ID,x1,y1,x2,y2,(x3,y3,(x4,y4,(x5,y5)))}, that I can handle.
'Any' custom field
is too vage.
Or do you mean a custom property of the entity?
That comes as a pair, what to include?

And it should handle files by a dialog or one fixed file name?
I read in your first post ever it should handle drawing layers as well.

One major problem with scripting on this forum is that people ask a lot and share mostly nothing.


Well, that being said, lets us give it a name and a place: Document Polylines.
Place: Misc..Examples..IOExamples..Document Polylines
Goal: Export Polyline to CSV
Input: Selection or all entities on current layer.
Export: as CSV, one poly per line
Location of the script: ..\QCAD\scripts\Misc\Examples\IOExamples\DocPolylines\
Script: ..\QCAD\scripts\Misc\Examples\IOExamples\DocPolylines\DocPolylines.js
Look into the init section for the specifics.

Code: Select all

/**
 * Copyright (c) 2020 by CVH.  Totally free with credit is fine
 * Partially Based on ExDumpPolyline.js extended to CSV export
 * Also based on BlockListExport.js for CSV output
 * both are or earlier copies where part of the QCAD project.
 *
 * This file is donated to the QCAD project.
 * Copyright (c) 2011-2020 by Andrew Mustun. All rights reserved.
 *
 * QCAD is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * QCAD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with QCAD.
 */

include("../IOExamples.js");
// CVH added included File.js as in BlockListExport.js 
include("scripts/File/File.js");

/**
 * \ingroup ecma_misc_examples_ioexamples
 * \class DocPolylines
 * This action documents all selected polyline entities as plain text into a CSV file.
 * Without a selection it will look for polylines in the active layer.
 */
function DocPolylines(guiAction) {
    IOExamples.call(this, guiAction);
}

DocPolylines.prototype = new IOExamples();
DocPolylines.includeBasePath = includeBasePath;

DocPolylines.prototype.beginEvent = function() {
    IOExamples.prototype.beginEvent.call(this);

    var di = this.getDocumentInterface();
    var document = this.getDocument();
    var ids = document.querySelectedEntities();    // Qset with selected
    var entity;                                    // entity in process
    var curLayer;                                  // Documents current layer
    var msg;                                       // Messages
    var listSeparator = ",";                       // Fixed list separator

    // Try current layer without selection:
    if (ids.length == 0) {
        curLayer = document.getCurrentLayerId();
        ids = document.queryLayerEntities(curLayer, false);
    } // -> Continue with selection or alternative

    // Terminate without entities selected:
    var idn = ids.length;
    if (idn == 0) {
        msg = qsTr("No entities selected!");    // translated message
        qDebug(msg);    // Push warning to stdout
        EAction.handleUserWarning(msg);    // Push warning to history (Win)
        this.terminate();
        return;
    } // -> Continue with selection

    var fileName = this.getFileName();    // .getFileName as in BlockListExport.js
    if (isNull(fileName)) {
        msg = qsTr("No file selected!");    // translated message
        qDebug(msg);    // Push warning to stdout
        EAction.handleUserWarning(msg);    // Push warning to history (Win)
        this.terminate();
        return;
    } // -> Continue with a fileName

    var file = new QFile(fileName);
    var flags = new QIODevice.OpenMode(QIODevice.WriteOnly | QIODevice.Text);
    if (!file.open(flags)) {
        msg = qsTr("No file opened!");    // translated message
        qDebug(msg);    // Push warning to stdout
        EAction.handleUserWarning(msg);    // Push warning to history (Win)
        this.terminate();
        return;
    } // -> Continue with an open file

    var ts = new QTextStream(file);
    ts.setCodec("UTF-8");
    
    // Write file header:
    msg = qsTr("CSV export of selected polylines")
    if (!isNull(curLayer)) {
        msg = qsTr("CSV export of polylines on active layer")
    }
    ts.writeString(msg + "\n");
    ts.writeString("polyID, Xn, Yn (n Vertices)" + "\n");


debugger;    // To pause and open the debugger window
//    Use "C:\Program Files\QCAD\qcad.exe" -rescan -enable-script-debugger -always-load-scripts
//    to launch QCAD. Debugger mode is not always a stable environment.

    //Type: Polyline entity types #Done# Reproducible
    for (i=0; i<idn; i++) {    // Cycle through selection
        id = ids[i];
        entity = document.queryEntity(id);
        if (isPolylineEntity(entity)) {
            // Get & write the custom property 'ID' if any:
            var polyCustom = entity.getCustomProperty("QCAD", "ID", "NaN");
            ts.writeString(polyCustom);
            // Get & write the vertices:
            var vn = entity.countVertices();
            for (var k=0; k<vn; k++) {    // Cycle through all vertices
                var v = entity.getVertexAt(k);
                ts.writeString(listSeparator);
                ts.writeString(parseFloat(v.x));
                ts.writeString(listSeparator);
                ts.writeString(parseFloat(v.y));
            // The values are not formatted and will have up to 15 significant numbers
            // Remember that Z coordinates are not included nor validated
            // Remember that bulging is not included nor validated
            } // Loop vertices
        // Insert EOL:
        ts.writeString("\n");
        } // End isPolylineEntity
    } // Loop selection

    // Insert EOF:
    ts.writeString("End of file");

    // Terminate command:
    file.close();
    msg = qsTr("Export complete:  ");    // translated message
    qDebug(msg);    // Push End to stdout
    EAction.handleUserMessage(msg + fileName);    // Push message to history (Win)
    this.terminate();
    return;
}

// CVH added: .getFileName as in BlockListExport.js
DocPolylines.prototype.getFileName = function() {
    var drawingFileName = this.getDocument().getFileName();

    var fi;
    var fileName;
    var initialPath = "";
    if (drawingFileName.length === 0) {
        var path = RSettings.getStringValue("DocPolylines/Path", QDir.homePath());
        fi = new QFileInfo(path);
        initialPath = fi.absoluteFilePath() + QDir.separator +
                      stripDirtyFlag(EAction.getMdiChild().windowTitle) + ".csv";
    } else {
        fi = new QFileInfo(drawingFileName);
        initialPath = fi.path() + QDir.separator + fi.completeBaseName() + ".csv";
    }

    var appWin = EAction.getMainWindow();
    var ret = File.getSaveFileName(appWin, qsTr("Document Polylines (CSV)"),
                                   initialPath, [ qsTr("CSV") + " (*.csv)" ]);
    if (isNull(ret)) {
        return undefined;
    }
    fileName = ret[0];

    if (fileName === "") {
        return undefined;
    }

    if (drawingFileName.length === 0) {
        RSettings.setValue("DocPolylines/Path", new QFileInfo(fileName).absolutePath());
    }

    return fileName;
};

DocPolylines.init = function(basePath) {
    var action = new RGuiAction(qsTr("Document &Polylines"), RMainWindowQt.getMainWindow());
    action.setRequiresDocument(true);
    action.setRequiresSelection(false);    // Selection handling build in
    action.setScriptFile(basePath + "/DocPolylines.js");
    action.setIcon(basePath + "/PolyCsvExport.svg");
    action.setDefaultShortcut(new QKeySequence("d,p,c"));
    action.setDefaultCommands(["docpoly", "dpc"]);    // An Array!
    var tip = qsTr("Document Polylines as CSV export")
    action.setStatusTip(tip);    // Overtakes and displays left in the Status Bar
    action.setToolTip(tip);    // Displays aside Toolbars
    action.setGroupSortOrder(71100);
    action.setSortOrder(300);
    action.setWidgetNames(["IOExamplesMenu"]);
};
Hopes this serves you.
Regards,
CVH
Last edited by CVH on Sat Nov 28, 2020 5:10 am, edited 1 time in total.

CVH
Premier Member
Posts: 3416
Joined: Wed Sep 27, 2017 4:17 pm

Re: Export polyline coordinates to CSV file

Post by CVH » Thu Aug 13, 2020 2:33 pm

Typo:

Code: Select all

if (!isNull(curLayer) {
Should be

Code: Select all

 if (!isNull(curLayer)) {

Code: Select all

 action.setIcon(basePath + "/DocPolylines.svg");
Changed in

Code: Select all

 action.setIcon(basePath + "/PolyCsvExport.svg");
Edited in code in former post.
Icon added :P
Place it in the same folder as DocPolylines.js

Regards,
CVH
Attachments
PolyCsvExport.svg
Icon file
(30.53 KiB) Downloaded 571 times

CVH
Premier Member
Posts: 3416
Joined: Wed Sep 27, 2017 4:17 pm

Re: Export polyline coordinates to CSV file

Post by CVH » Sat Aug 15, 2020 6:25 am

Got a PM to pay for the development.
That was odd because:
A) The script is functional as is.
B) The script header says it all:
"Totally free with credit is fine."
"This file is donated to the QCAD project."

Explained a bit further how to include this script and the respons was:
Works beautifully! I cannot thank you enough. This is exactly what I was looking for. I sincerely appreciate your help.

There are still issues with it ... :!:
Remember that it was collected on the fly while replying a topic.

One is the key-in shortcut.
DPC is not executed, DP is.
QCAD does'nt trow a conflict.
Should I report this or is Andrew lurking?

So I looked up an inuitive alternative.
Found out that you have to trial this adding one character at a time.
- D goes but DP not.
- Shift+D isn't an option.
- Ctrl+D, conflicts.
- Alt+D, no conflicts, no go, that activates the Draw menu.
- With an 'X' from 'export' its even harder.

In the end I settled for NO shortcut key-in. :(

Code: Select all

 Remove or disable:   action.setDefaultShortcut(new QKeySequence("d,p,c")); 
As the commands are set to ... long= 'docpoly' ... short='dpc' one can still use:
[Spacebar]..d..p..c..[Enter] :P

Another issue would be the one-line format what is not suited for many vertices.
So this won't be the best replacement for dumpPoly.
A solution would be: Vertices per line or Polys per line option.

Then we have:
- CSV formatting .,. vs ,;, Mine is the latter. :|
We could use the QCAD App preferenced list separator.
But then again there are those issues with QCAD formatting. :?
- Number formatting. On the fly I settled with parsefloat().
That may look very odd with all its '0' and '9' because a binary fractional is never accurate in decimal notation.
Or the other way around.
But who am I to choose for 4, 6 or even 12 decimal digits?
What about trailing zero's?
- An Empty file with no polys in the selection, apart from header and the EOF.
Looking into the restriction of the selection to polys.
Or should I test for it and warn the user there are none.
- .getFileName can return an empty filename from the file dialog. And, it will write to that file!
- Cancelling an overwrite will reset your folder browsing.

So, now I am questioning if an UI should be in place or to use the Option Toolbar ...
Regards,
CVH

John Hyslop
Premier Member
Posts: 473
Joined: Mon Sep 30, 2019 6:21 am
Location: Melbourne - Australia

Re: Export polyline coordinates to CSV file

Post by John Hyslop » Wed Sep 02, 2020 8:07 am

Hi CVH

I can't get QCADCAM to start, is this the correct place? I have debug mod set in application settings?
I've no idea where I'm going wrong???

Copied both your icon and js file in locations noted...

Cheers
John
Attachments
is the the right place.jpg
is the the right place.jpg (81.04 KiB) Viewed 15597 times
IF IT IS TO BE IT IS UP TO ME [ Ten most powerful 2 letter words ]

CVH
Premier Member
Posts: 3416
Joined: Wed Sep 27, 2017 4:17 pm

Re: Export polyline coordinates to CSV file

Post by CVH » Wed Sep 02, 2020 8:30 am

Hi John, All,
DocPolylines is an Import / Export example script.
The menu setup and the folder setup are like mirrors. :wink:

The script and icon files should be placed here:
... QCAD\scripts\Misc\Examples\IOExamples\DocPolylines\*.*
And I think:
... QCADCAM\scripts\Misc\Examples\IOExamples\DocPolylines\*.*

The text file is no part of that, files can't be written to the OS protected regions. :shock:

Regards,
CVH

John Hyslop
Premier Member
Posts: 473
Joined: Mon Sep 30, 2019 6:21 am
Location: Melbourne - Australia

Re: Export polyline coordinates to CSV file

Post by John Hyslop » Wed Sep 02, 2020 9:34 am

Hi CVH

The text file is my own to let me know what it does.. I tried removing it to see if it was the problem, but not?
I'll try your other suggestions..

Need to run...

Cheers
John
PS It worked thanks, I had it in the wrong path Examples doh :oops:
IF IT IS TO BE IT IS UP TO ME [ Ten most powerful 2 letter words ]

CVH
Premier Member
Posts: 3416
Joined: Wed Sep 27, 2017 4:17 pm

Re: Export polyline coordinates to CSV file

Post by CVH » Wed Sep 02, 2020 11:24 am

Hi All,
Came up with new icons. Green it is.
(A little fight with Inkscape text and gradient fill) :wink:

Iconfile:
PolyCsvExport.svg
(31.24 KiB) Downloaded 553 times
Fast Install:
- Copy the svg over to the DocPolylines folder.

All included in new zipper.

Regards,
CVH
Attachments
DocPolylines.zip
(21.17 KiB) Downloaded 565 times

LMIM
Newbie Member
Posts: 4
Joined: Tue Mar 09, 2021 4:59 pm

Re: Export polyline coordinates to CSV file

Post by LMIM » Tue Mar 09, 2021 5:27 pm

Hi all,

I am new in this forum. I registered due to this topic.

I can´t understand how to use this. I have no idea about JavaScript. I read several times the thread but I can't undertand how to run the solution.

Could please anyone tell me a a little more detailed steps to run this "plugin" ?

Thanks in advance!

CVH
Premier Member
Posts: 3416
Joined: Wed Sep 27, 2017 4:17 pm

Re: Export polyline coordinates to CSV file

Post by CVH » Tue Mar 09, 2021 7:44 pm

Hi,

The details to install this addon are somewhat higher:
viewtopic.php?f=30&t=7497#p29342
The last version is from date of Sep 02, 2020 : all in a zip file

Create the folder structure and place the files in that folder.
Next time you start QCAD you will find the tool under Misc > Script Examples > Import/Export

Regards,
CVH

LMIM
Newbie Member
Posts: 4
Joined: Tue Mar 09, 2021 4:59 pm

Re: Export polyline coordinates to CSV file

Post by LMIM » Wed Mar 10, 2021 11:39 pm

Thanks a lot! It worked perfectly! Thanks!

I was trying to copy/open/import my geometry of Polylines generated in autocad but i can't.

I tried a lot of ways and in after several trys I reached it, but I don't know exactly how i did it. Could you please tell me where should I read about the alternatives and restrictions to bring a geometry from autocad to Qcad?

Thanks again!

CVH
Premier Member
Posts: 3416
Joined: Wed Sep 27, 2017 4:17 pm

Re: Export polyline coordinates to CSV file

Post by CVH » Thu Mar 11, 2021 7:30 am

Hi,
The tool export each simple polyline to a one-liner in CSV as required by the user TonyE.

To merge autocad geometry I would use the native dxf format. :wink:
- autocad exported as dxf

And then there are some options: :P
- Open with QCAD
- Import in a QCAD drawing as entities or as block
- Use as library item in QCAD

If that doesn't suite you then please open a new topic and clarify what to export/import ...
An example file could be handy ...

Regards,
CVH

Post Reply

Return to “QCAD Programming, Script Programming and Contributing”