File: ConvTable.java

package info (click to toggle)
h2orestart 0.7.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,168 kB
  • sloc: java: 21,845; makefile: 36; xml: 19
file content (1605 lines) | stat: -rw-r--r-- 89,450 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
/* Copyright (C) 2023 ebandal
 * 
 * This program 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.
 * 
 * This program 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 this program. If not, see <http://www.gnu.org/licenses/>
 */
/* 본 제품은 한글과컴퓨터의 ᄒᆞᆫ글 문서 파일(.hwp) 공개 문서를 참고하여 개발하였습니다.
 * 개방형 워드프로세서 마크업 언어(OWPML) 문서 구조 KS X 6101:2018 문서를 참고하였습니다.
 * 작성자 : 반희수 ebandal@gmail.com  
 * 작성일 : 2022.10
 */
package soffice;

import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import com.sun.star.uno.*;
import com.sun.star.uno.Exception;

import HwpDoc.HwpElement.HwpRecord_BorderFill;
import HwpDoc.HwpElement.HwpRecord_CharShape;
import HwpDoc.HwpElement.HwpRecord_ParaShape;
import HwpDoc.HwpElement.HwpRecord_Style;
import HwpDoc.paragraph.Ctrl;
import HwpDoc.paragraph.Ctrl_AutoNumber;
import HwpDoc.paragraph.Ctrl_Character;
import HwpDoc.paragraph.Ctrl_ShapePic;
import HwpDoc.paragraph.Ctrl_Table;
import HwpDoc.paragraph.HwpParagraph;
import HwpDoc.paragraph.ParaText;
import HwpDoc.paragraph.TblCell;
import soffice.HwpCallback.TableFrame;

import com.sun.star.lang.*;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lib.uno.adapter.ByteArrayToXInputStreamAdapter;
import com.sun.star.style.GraphicLocation;
import com.sun.star.table.BorderLine2;
import com.sun.star.table.BorderLineStyle;
import com.sun.star.table.TableBorder;
import com.sun.star.table.XCell;
import com.sun.star.table.XTableRows;
import com.sun.star.awt.Size;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertySet;
import com.sun.star.drawing.TextVerticalAdjust;
import com.sun.star.drawing.XShape;
import com.sun.star.graphic.XGraphic;
import com.sun.star.graphic.XGraphicProvider;
import com.sun.star.text.*;

public class ConvTable {
    private static final Logger log = Logger.getLogger(ConvTable.class.getName());

    private static int autoNum = 0;

    public static void reset(WriterContext wContext) {
        autoNum = 0;
    }

    public static void endParagraph(XTextCursor cursor) {
        append(cursor, ControlCharacter.PARAGRAPH_BREAK);
    }

    public static void appendPara(XTextCursor cursor, String text) {
        append(cursor, text);
        append(cursor, ControlCharacter.PARAGRAPH_BREAK);
    }

    public static void append(XTextCursor cursor, String text) {
        cursor.setString(text);
        cursor.gotoEnd(false);
    }

    public static void append(XTextCursor cursor, short ctrlChar) {
        XText xText = cursor.getText();
        xText.insertControlCharacter(cursor, ctrlChar, false);
    }

    public static void insertTable(WriterContext wContext, Ctrl_Table table, short paraShapeID, HwpCallback callback,
            int step) {
        // 테이블 그리기 전, 문단모양 설정한다. 문단에 Frame을 넣기때문에 문단 margin에 맞게 여백이 들어가야 한다.
        HwpRecord_ParaShape paraShape = wContext.getParaShape((short) paraShapeID);
        XParagraphCursor paraCursor = UnoRuntime.queryInterface(XParagraphCursor.class, wContext.mTextCursor);
        XPropertySet paraProps = UnoRuntime.queryInterface(XPropertySet.class, paraCursor);
        ConvPara.setParagraphProperties(paraProps, paraShape, wContext.getDocInfo().compatibleDoc, ConvPara.PARA_SPACING);
        
        XTextFrame xFrame = null;
        XText xFrameText = null;
        XTextCursor xFrameCursor = null;

        try {
            TblCell[][] cellArray = new TblCell[table.nRows][table.nCols];
            for (int index = 0; index < table.cells.size(); index++) {
                TblCell cell = table.cells.get(index);
                cellArray[cell.rowAddr][cell.colAddr] = cell;
            }
            // HWP테이블에는 존재하지 않는 Cell이 포함되어 있는 경우가 있다.
            // 이 경우 TableColumnSeparator의 Position 계산이 어려워질뿐 아니라 CellMerge도 어려워진다. all null
            // 칼럼을 제거하고, colSpan을 조정한다.
            cellArray = removeAllNullColumns(cellArray);
            int maxColSize = Arrays.stream(cellArray).map(row -> row.length)
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                    .entrySet().stream()
                    .max(Map.Entry.comparingByValue()).get().getKey();

            Object tableObj = wContext.mMSF.createInstance("com.sun.star.text.TextTable");
            XTextTable xTextTable = UnoRuntime.queryInterface(XTextTable.class, tableObj);

            if (xTextTable == null) {
                log.severe("Could not create a text table.");
                return;
            }
            XPropertySet tableProps = UnoRuntime.queryInterface(XPropertySet.class, xTextTable);
            xTextTable.initialize(cellArray.length, maxColSize);

            if (callback != null && callback.onTableWithFrame() == TableFrame.MAKE) {
                xFrame = makeOuterFrame(wContext, table);
                xFrameText = xFrame.getText();
                xFrameCursor = xFrameText.createTextCursor();
                xFrameText.insertTextContent(xFrameCursor, xTextTable, false);
                if (wContext.version >= 72) {
                    XPropertySet frameProps = UnoRuntime.queryInterface(XPropertySet.class, xFrame);
                    TextContentAnchorType anchorType = (TextContentAnchorType) frameProps.getPropertyValue("AnchorType");
                    if (anchorType == TextContentAnchorType.AT_PARAGRAPH) {
                        xFrameText.insertString(xFrameCursor, " ", true);
                    }
                }
                addCaptionString(wContext, xFrameText, xFrameCursor, table, step + 1);
                step += 1;
            } else {
                wContext.mText.insertTextContent(wContext.mTextCursor, xTextTable, false);
                if (wContext.version >= 72) {
                    TextContentAnchorType anchorType = (TextContentAnchorType) tableProps.getPropertyValue("AnchorType");

                    // 한컴에서 AS_CHAR 가 아니면 PARA_BREAK가 추가되어 있을것임, libreoffice에서는 ANCHOR를 붙일수 없으니 마지막
                    // PARA_BREAK를 제거하자.
                    // 여기서는 없애지 못하므로 (아래의 코드로도 PARA_BREAK 지우지 못한다. Table 이후 나오는 PARA_BREAK 한개를 생략한다.
                    // (oweParaBreak)
                    if (table.treatAsChar == false) {
                        HwpRecurs.removeLastParaBreak(wContext.mTextCursor);
                    }
                }
                // 캡션이 표시될 문단의 오른쪽 spacing을 임의로 조정
                HwpDoc.section.Page page = ConvPage.getCurrentPage().page;
                int rightSpace = page.width - page.marginLeft - page.marginRight - paraShape.marginLeft - table.width;
                addCaptionString(wContext, wContext.mText, wContext.mTextCursor, table, 0, rightSpace, step);
                if (callback != null && callback.onTableWithFrame() == TableFrame.MADE) {

                } else {
                    setParaPosition(tableProps, table, paraShape);
                }
                if (table.treatAsChar) {
                    tableProps.setPropertyValue("Split", false);
                } else {
                    if ((table.attr & 0x03) == 0x02) {
                        tableProps.setPropertyValue("Split", true);
                    } else {
                        tableProps.setPropertyValue("Split", false);
                    }
                }
            }

            
            HwpRecord_BorderFill tableBorderFill = WriterContext.getBorderFill(table.borderFillID);
            if (tableBorderFill != null) {
                TableBorder tBorder = new TableBorder();
                tBorder.LeftLine = Transform.toBorderLine(tableBorderFill.left);
                tBorder.IsLeftLineValid = true;
                tBorder.RightLine = Transform.toBorderLine(tableBorderFill.right);
                tBorder.IsRightLineValid = true;
                tBorder.TopLine = Transform.toBorderLine(tableBorderFill.top);
                tBorder.IsTopLineValid = true;
                tBorder.BottomLine = Transform.toBorderLine(tableBorderFill.bottom);
                tBorder.IsBottomLineValid = true;
                tBorder.VerticalLine = Transform.toBorderLine((HwpRecord_BorderFill.Border) null);
                tBorder.IsVerticalLineValid = true;
                tBorder.HorizontalLine = Transform.toBorderLine((HwpRecord_BorderFill.Border) null);
                tBorder.IsHorizontalLineValid = true;
                tableProps.setPropertyValue("TableBorder", tBorder);
            }
            if (tableBorderFill != null) {
                if (tableBorderFill.fill.isColorFill()) {
                    tableProps.setPropertyValue("BackTransparent", false);
                    tableProps.setPropertyValue("BackColor", tableBorderFill.fill.faceColor);
                } else if (tableBorderFill.fill.isGradFill()) {
                    // CellProperties에는 Gradient 그릴 수 있는 속성이 없다. 중간색으로 칠한다.
                    if (tableBorderFill.fill.colors.length==2) {
                        short r, g, b;
                        r = (short) (((tableBorderFill.fill.colors[0]>>16&0x00FF) + (tableBorderFill.fill.colors[1]>>16&0x00FF))/2);  
                        g = (short) (((tableBorderFill.fill.colors[0]>>8&0x00FF) + (tableBorderFill.fill.colors[1]>>8&0x00FF))/2);  
                        b = (short) (((tableBorderFill.fill.colors[0]&0x00FF) + (tableBorderFill.fill.colors[1]&0x00FF))/2);  
                        int midColor = (r<<16)|(g<<8)|b;
                        tableProps.setPropertyValue("BackColor", midColor);
                    }
                } else if (tableBorderFill.fill.isImageFill()) {
                    setBackGraphic(wContext, tableProps, tableBorderFill.fill.binItemID);
                } else {
                    tableProps.setPropertyValue("BackTransparent", false);
                }
            }


            int width = Transform.translateHwp2Office(table.width);
            short sTableColumnRelativeSum = (Short) tableProps.getPropertyValue("TableColumnRelativeSum");
            double dRatio = (double) sTableColumnRelativeSum / (double) width;

            // adjust cell width
            // prepare column width values, so that adjust cell width.
            int[] colWidth = calculateColumnWidth(cellArray, table.width);
            for (int n = 0; n < colWidth.length; n++) {
                colWidth[n] = Transform.translateHwp2Office(colWidth[n]);
            }

            TableColumnSeparator[] xSeparators = UnoRuntime.queryInterface(TableColumnSeparator[].class,
                    tableProps.getPropertyValue("TableColumnSeparators"));
            double dPosition = 0;
            for (int col = 0; col < colWidth.length; col++) {
                // [20250817] position gap이 최소 2이상이 되도록 한다. 1에서 머지가 안되는 경우 있음. issue #60
                dPosition += (colWidth[col] * dRatio > 1.0 ? colWidth[col] * dRatio : 3);
                xSeparators[col].Position = (short) Math.ceil(dPosition);
            }
            tableProps.setPropertyValue("TableColumnSeparators", xSeparators);
            
            // table row 높이 조정
            XTableRows xTableRows = xTextTable.getRows();
            if (xTableRows != null) {
                int[] rowHeight = calculateRowHeight(cellArray, table.height);
                if (hasNullRow(rowHeight, table.height) == false) {
                    for (int row = 0; row < xTableRows.getCount(); row++) {
                        Object aRowObj = xTableRows.getByIndex(row);
                        XPropertySet tableRowProps = UnoRuntime.queryInterface(com.sun.star.beans.XPropertySet.class,
                                aRowObj);
                        tableRowProps.setPropertyValue("IsAutoHeight", false);
                        tableRowProps.setPropertyValue("Height", Transform.translateHwp2Office(rowHeight[row]));
                    }
                }
            }
            
            // merge cell and fill text.
            for (int row = 0; row < cellArray.length; row++) {
                for (int col = cellArray[row].length - 1; col >= 0; col--) {
                    TblCell cell = cellArray[row][col];
                    String cellAddr = mkCellNameBeforeMerge(cellArray, col, row, row - 1);
                    XCell xCell = xTextTable.getCellByName(cellAddr);
                    if (xCell != null) {
                        // 인접한 Cell Border때문에 border가 지워지지 않는 현상있음. 모든 Cell에 대해 border가 없는 상태로 먼저 만든다.
                        XPropertySet cellProps = UnoRuntime.queryInterface(XPropertySet.class, xCell);
                        HwpRecord_BorderFill.Border nullBorder = null;
                        cellProps.setPropertyValue("LeftBorder", Transform.toBorderLine(nullBorder));
                        cellProps.setPropertyValue("RightBorder", Transform.toBorderLine(nullBorder));
                        cellProps.setPropertyValue("TopBorder", Transform.toBorderLine(nullBorder));
                        cellProps.setPropertyValue("BottomBorder", Transform.toBorderLine(nullBorder));
                        // 테이블 경계선 근처에서 텍스트 잘리지 않도록 함
                        cellProps.setPropertyValue("LeftBorderDistance", 0);
                        cellProps.setPropertyValue("RightBorderDistance", 0);
                        cellProps.setPropertyValue("TopBorderDistance", 0);
                        cellProps.setPropertyValue("BottomBorderDistance", 0);
                        cellProps.setPropertyValue("BorderDistance", 0);
                    }
                    if (cell == null)
                        continue;

                    if (cell.colSpan > 1 || cell.rowSpan > 1) {
                        try {
                            // 한가지 방식으로 통일하면 좋겠으나 extension에서 동작하지 않아 각각 방식을 달리한다.
                            log.finest("CELL ADDR=" + cellAddr + " out of (" + cell.colAddr + ", " + cell.rowAddr
                                    + ") spans (" + cell.colSpan + "," + cell.rowSpan + ")");
                            XTextTableCursor xCellCursor = xTextTable.createCursorByCellName(cellAddr);
                            // column merge는 goRight() 후 mergeRange(). gotoCellByName()은 extension에서 동작 안함.
                            if (cell.colSpan > 1) {
                            	boolean ret = xCellCursor.goRight((short) (cell.colSpan - 1), true);
                                log.finest("GoRight(" + (cell.colSpan - 1) + ") return=" + ret);
                                ret = xCellCursor.mergeRange();
                                log.finest("Merge=" + ret);
                            }
                            // row merge는 gotoCellByName() 후 mergeRange(). goRight()은 extension에서 동작 안함.
                            if (cell.rowSpan > 1) {
                                String cellAddr2 = mkCellNameBeforeMerge(cellArray, cell.colAddr + cell.colSpan - 1,
                                        cell.rowAddr + cell.rowSpan - 1, row - 1);
                                boolean ret = xCellCursor.gotoCellByName(cellAddr2, true);
                                log.finest("GotoCell(" + cellAddr2 + ") return=" + ret);
                                ret = xCellCursor.mergeRange();
                                log.finest("Merge=" + ret);
                            }
                        } catch (com.sun.star.uno.RuntimeException e1) {
                            e1.printStackTrace();
                        }
                    }

                    try {
                        // 셀을 병합한 후에 Border를 그린다.
                        if (xCell != null) {
                            XPropertySet cellProps = UnoRuntime.queryInterface(XPropertySet.class, xCell);
                            HwpRecord_BorderFill cellBorderFill = WriterContext.getBorderFill(cell.borderFill);
                            if (cellBorderFill != null) {
                                cellProps.setPropertyValue("LeftBorder", Transform.toBorderLine(cellBorderFill.left));
                                cellProps.setPropertyValue("RightBorder", Transform.toBorderLine(cellBorderFill.right));
                                cellProps.setPropertyValue("TopBorder", Transform.toBorderLine(cellBorderFill.top));
                                cellProps.setPropertyValue("BottomBorder", Transform.toBorderLine(cellBorderFill.bottom));
                            }
                            // 안쪽여백은 한컴값을 사용하지 않고, 0으로 임의조정한다. 가능한 Cell내 모든 문단을 보여주기 위해  
                            cellProps.setPropertyValue("LeftBorderDistance", 0);
                            cellProps.setPropertyValue("RightBorderDistance", 0);
                            cellProps.setPropertyValue("TopBorderDistance", 0);
                            cellProps.setPropertyValue("BottomBorderDistance", 0);
                            cellProps.setPropertyValue("VertOrient", Transform.toVertAlign(cell.verAlign.ordinal()));

                            if (cellBorderFill != null) {
                                if (cellBorderFill.fill.isColorFill()) {
                                    if (callback != null && callback.onTableWithFrame() == TableFrame.MAKE_PART) {
                                        cellProps.setPropertyValue("BackTransparent", true); // ZOrder 변경이 안되어 이런식으로 만듬.
                                    } else {
                                        cellProps.setPropertyValue("BackTransparent", false);
                                        cellProps.setPropertyValue("BackColor", cellBorderFill.fill.faceColor);
                                    }
                                } else if (cellBorderFill.fill.isGradFill()) {
                                    // CellProperties에는 Gradient 그릴 수 있는 속성이 없다. 중간색으로 칠한다.
                                    if (cellBorderFill.fill.colors.length==2) {
                                        short r, g, b;
                                        r = (short) (((cellBorderFill.fill.colors[0]>>16&0x00FF) + (cellBorderFill.fill.colors[1]>>16&0x00FF))/2);  
                                        g = (short) (((cellBorderFill.fill.colors[0]>>8&0x00FF) + (cellBorderFill.fill.colors[1]>>8&0x00FF))/2);  
                                        b = (short) (((cellBorderFill.fill.colors[0]&0x00FF) + (cellBorderFill.fill.colors[1]&0x00FF))/2);  
                                        int midColor = (r<<16)|(g<<8)|b;
                                        cellProps.setPropertyValue("BackColor", midColor);
                                    }
                                } else if (cellBorderFill.fill.isImageFill()) {
                                    ConvGraphics.fillGraphic(wContext, cellProps, cellBorderFill.fill);
                                }
                            }
                        }
                    } catch (IllegalArgumentException | UnknownPropertyException | PropertyVetoException
                            | WrappedTargetException e) {
                        e.printStackTrace();
                    }

                    setCellPara(cellAddr, cell, xTextTable, table, wContext, callback, step);
                }
            }
        } catch (IllegalArgumentException | Exception e3) {
            e3.printStackTrace();
        }
    }

    private static XTextFrame makeOuterFrame(WriterContext wContext, Ctrl_Table table) throws Exception {
        XTextFrame xFrame = null;

        Object oFrame = wContext.mMSF.createInstance("com.sun.star.text.TextFrame");
        xFrame = (XTextFrame) UnoRuntime.queryInterface(XTextFrame.class, oFrame);
        if (xFrame == null) {
            log.severe("Could not create a text frame.");
            return xFrame;
        }

        XShape tfShape = UnoRuntime.queryInterface(XShape.class, xFrame);
        tfShape.setSize(
                new Size(Transform.translateHwp2Office(table.width), Transform.translateHwp2Office(table.height)));
        XPropertySet frameProps = UnoRuntime.queryInterface(XPropertySet.class, xFrame);

        setFramePosition(frameProps, table);
        setFrameWrapStyle(frameProps, table);

        BorderLine2 frameBorder = new BorderLine2();
        frameBorder.Color = 0x000000;
        frameBorder.LineStyle = BorderLineStyle.NONE;
        frameBorder.InnerLineWidth = 0;
        frameBorder.OuterLineWidth = 0;
        frameBorder.LineDistance = 0;
        frameBorder.LineWidth = 0;
        frameProps.setPropertyValue("TopBorder", frameBorder);
        frameProps.setPropertyValue("BottomBorder", frameBorder);
        frameProps.setPropertyValue("LeftBorder", frameBorder);
        frameProps.setPropertyValue("RightBorder", frameBorder);
        // margin 0으로
        frameProps.setPropertyValue("LeftMargin", 0);
        frameProps.setPropertyValue("RightMargin", 0);
        frameProps.setPropertyValue("TopMargin", 0);
        frameProps.setPropertyValue("BottomMargin", 0);
        // 안쪽여백을 0으로...
        frameProps.setPropertyValue("BorderDistance", 0);

        XText xText = wContext.mTextCursor.getText();
        xText.insertTextContent(wContext.mTextCursor, xFrame, false);
        if (wContext.version >= 72) {
            TextContentAnchorType anchorType = (TextContentAnchorType) frameProps.getPropertyValue("AnchorType");
            if (anchorType == TextContentAnchorType.AT_PARAGRAPH) {
                xText.insertString(wContext.mTextCursor, " ", false);
            }
        }

        // 2024.12.25 테이블 이후 PARA_BRAEK 보이지 않도록 고정크기로 하기 위해 false로 변경하고, TOP align으로 변경
        // 높이 고정시에 캡션이 보이지 않으므로, 캡션이 있으면 true로 하자. 
        if (table.caption == null || table.caption.size()==0) {
            frameProps.setPropertyValue("FrameIsAutomaticHeight", false);
        } else {
            frameProps.setPropertyValue("FrameIsAutomaticHeight", true);
        }
        frameProps.setPropertyValue("TextVerticalAdjust", TextVerticalAdjust.TOP);
        wContext.mTextCursor.gotoEnd(false);

        return xFrame;
    }

    private static void setParaPosition(XPropertySet xProps, Ctrl_Table shape, HwpRecord_ParaShape paraShape) {
        int posX = 0;
        int posY = 0;

        HwpDoc.section.Page page = ConvPage.getCurrentPage().page;
        if (shape.treatAsChar == true) {
            posX = Transform.translateHwp2Office(shape.horzOffset) - Transform.translateHwp2Office(page.marginLeft);
            posX = Math.max(posX, 0);
            try {
                xProps.setPropertyValue("LeftMargin", posX);
                xProps.setPropertyValue("Width", Transform.translateHwp2Office(shape.width));
                switch (paraShape.align) {
                case LEFT: // 왼쪽 정렬
                    xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT);
                    break;
                case RIGHT: // 오른쪽 정렬
                    xProps.setPropertyValue("HoriOrient", HoriOrientation.RIGHT);
                    break;
                case CENTER: // 가운데 정렬
                case JUSTIFY: // 양쪽 정렬
                    xProps.setPropertyValue("HoriOrient", HoriOrientation.CENTER);
                    break;
                case DISTRIBUTE: // 배분 정렬
                case DISTRIBUTE_SPACE: // 나눔 정렬
                    xProps.setPropertyValue("HoriOrient", HoriOrientation.NONE);
                    break;
                }
            } catch (IllegalArgumentException | UnknownPropertyException | PropertyVetoException
                    | WrappedTargetException e) {
                e.printStackTrace();
            }
        } else {
            try {
                switch (shape.vertRelTo) {
                case PARA:
                case PAGE:
                    switch (shape.vertAlign) {
                    case TOP:
                        posY = Transform.translateHwp2Office(shape.vertOffset);
                        if (posY > 0) {
                            xProps.setPropertyValue("TopMargin", posY);
                        }
                        break;
                    case BOTTOM:
                        // TextTable에는 VertOrient가 없으니, 위에서부터 계산해야 함.
                        posY = Transform.translateHwp2Office(page.height)
                               - Transform.translateHwp2Office(shape.height)
                               - Transform.translateHwp2Office(shape.vertOffset);
                        xProps.setPropertyValue("TopMargin", posY);
                        break;
                    }
                    break;
                }
            } catch (IllegalArgumentException | UnknownPropertyException | PropertyVetoException
                    | WrappedTargetException e) {
                e.printStackTrace();
            }

            try {
                switch (shape.horzRelTo) {
                case PAPER:
                    switch (shape.horzAlign) {
                    case LEFT: // LEFT
                    case INSIDE:
                        posX = Transform.translateHwp2Office(shape.horzOffset)
                                - Transform.translateHwp2Office(page.marginLeft);
                        posX = Math.max(posX, 0);
                        xProps.setPropertyValue("LeftMargin", posX);
                        xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT_AND_WIDTH);
                        xProps.setPropertyValue("Width", Transform.translateHwp2Office(shape.width));
                        break;
                    case CENTER:
                        posX = Transform.translateHwp2Office(page.width) / 2
                                + Transform.translateHwp2Office(shape.horzOffset);
                        posX = posX - Transform.translateHwp2Office(page.marginLeft);
                        posX = posX - Transform.translateHwp2Office(shape.width) / 2;
                        xProps.setPropertyValue("LeftMargin", posX);
                        xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT_AND_WIDTH);
                        xProps.setPropertyValue("Width", Transform.translateHwp2Office(shape.width));
                        break;
                    case RIGHT: // RIGHT
                    case OUTSIDE:
                        posX = Transform.translateHwp2Office(page.width)
                                - Transform.translateHwp2Office(page.marginLeft)
                                - Transform.translateHwp2Office(shape.horzOffset);
                        posX = posX - Transform.translateHwp2Office(shape.width);
                        xProps.setPropertyValue("LeftMargin", posX);
                        xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT_AND_WIDTH);
                        xProps.setPropertyValue("Width", Transform.translateHwp2Office(shape.width));
                        break;
                    }
                    break;
                case PAGE:
                    switch (shape.horzAlign) {
                    case LEFT: // LEFT
                    case INSIDE:
                        posX = Transform.translateHwp2Office(shape.horzOffset);
                        posX = Math.max(posX, 0);
                        xProps.setPropertyValue("LeftMargin", posX);
                        xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT_AND_WIDTH);
                        xProps.setPropertyValue("Width", Transform.translateHwp2Office(shape.width));
                        break;
                    case CENTER:
                        posX = (Transform.translateHwp2Office(page.width)
                                - Transform.translateHwp2Office(page.marginLeft)
                                - Transform.translateHwp2Office(page.marginRight)) / 2;
                        posX = posX + Transform.translateHwp2Office(shape.horzOffset)
                                - Transform.translateHwp2Office(shape.width) / 2;
                        xProps.setPropertyValue("LeftMargin", posX);
                        xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT_AND_WIDTH);
                        xProps.setPropertyValue("Width", Transform.translateHwp2Office(shape.width));
                        break;
                    case RIGHT: // RIGHT
                    case OUTSIDE:
                        posX = Transform.translateHwp2Office(page.width)
                                - Transform.translateHwp2Office(page.marginLeft)
                                - Transform.translateHwp2Office(page.marginRight);
                        posX = posX - Transform.translateHwp2Office(shape.horzOffset)
                                - Transform.translateHwp2Office(shape.width);
                        xProps.setPropertyValue("LeftMargin", posX);
                        xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT_AND_WIDTH);
                        xProps.setPropertyValue("Width", Transform.translateHwp2Office(shape.width));
                        break;
                    }
                    break;
                case COLUMN:
                case PARA:
                    switch (shape.horzAlign) {
                    case LEFT: // LEFT. 왼쪽맞춤 일때 width,rightMargin이 필요(width+rightMargin이 전체 Para Width). 왼쪽에서부터
                               // 일때 width,leftMargin이 필요(width+leftMargin이 전체 width일 필요 없음).
                    case INSIDE:
                        posX = Transform.translateHwp2Office(shape.horzOffset)
                                + Transform.translateHwp2Office(paraShape.marginLeft / 2);
                        xProps.setPropertyValue("LeftMargin", posX);
                        xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT_AND_WIDTH);
                        xProps.setPropertyValue("Width", Transform.translateHwp2Office(shape.width));
                        break;
                    case CENTER: // 가운데맞춤일때 width,leftMargin이 필요 (width+leftMagin+leftMargin이 전체 width.
                                 // leftMargin=rightMargin 으로 봄)
                        posX = (Transform.translateHwp2Office(page.width)
                                - Transform.translateHwp2Office(page.marginLeft)
                                - Transform.translateHwp2Office(page.marginRight)) / 2;
                        posX = posX + Transform.translateHwp2Office(shape.horzOffset)
                                - Transform.translateHwp2Office(shape.width) / 2;
                        xProps.setPropertyValue("LeftMargin", posX);
                        xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT_AND_WIDTH);
                        xProps.setPropertyValue("Width", Transform.translateHwp2Office(shape.width));
                        break;
                    case RIGHT: // RIGHT. 오른쪽맞춤 일때, width, leftMargin이 필요(width+leftMargin이 전체 Para Width 이어야 함)
                    case OUTSIDE:
                        posX = Transform.translateHwp2Office(page.width)
                                - Transform.translateHwp2Office(page.marginLeft)
                                - Transform.translateHwp2Office(page.marginRight);
                        posX = posX - Transform.translateHwp2Office(shape.horzOffset)
                                - Transform.translateHwp2Office(shape.width);
                        xProps.setPropertyValue("LeftMargin", posX);
                        xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT_AND_WIDTH);
                        xProps.setPropertyValue("Width", Transform.translateHwp2Office(shape.width));
                        break;
                    }
                    break;
                }
            } catch (IllegalArgumentException | UnknownPropertyException | PropertyVetoException
                    | WrappedTargetException e) {
                e.printStackTrace();
            }
        }
    }

    private static void setParaWrapStyle(XPropertySet xPropSet, Ctrl_Table shape) {

        // wrapStyle; // 0:어울림, 1:자리차지, 2:글 뒤로, 3:글 앞으로
        // wrapText; // 0:양쪽, 1:왼쪽, 2:오른쪽, 3:큰쪽
        try {
            switch (shape.textWrap) {
            case SQUARE: // 어울림
                WrapTextMode wrapText = WrapTextMode.NONE;
                switch (shape.textFlow) {
                case 0x0: // 양쪽
                    wrapText = WrapTextMode.PARALLEL;
                    break;
                case 0x1: // 왼쪽
                    wrapText = WrapTextMode.LEFT;
                    break;
                case 0x2: // 오른쪽
                    wrapText = WrapTextMode.RIGHT;
                    break;
                case 0x3: // 큰쪽
                    wrapText = WrapTextMode.DYNAMIC;
                    break;
                }
                xPropSet.setPropertyValue("TextWrap", wrapText);
                break;
            case TOP_AND_BOTTOM: // 자리차지
                xPropSet.setPropertyValue("TextWrap", WrapTextMode.NONE);
                break;
            case BEHIND_TEXT: // 글 뒤로
                xPropSet.setPropertyValue("TextWrap", WrapTextMode.THROUGH);
                break;
            case IN_FRONT_OF_TEXT: // 글 앞으로
                xPropSet.setPropertyValue("TextWrap", WrapTextMode.THROUGH);
                break;
            }
        } catch (IllegalArgumentException | UnknownPropertyException | PropertyVetoException
                | WrappedTargetException e) {
            e.printStackTrace();
        }
    }

    private static void setFramePosition(XPropertySet xProps, Ctrl_Table table) {
        int posX = 0;
        int posY = 0;

        try {
            if (table.treatAsChar == true) {
                xProps.setPropertyValue("AnchorType", TextContentAnchorType.AS_CHARACTER);
                xProps.setPropertyValue("VertOrient", VertOrientation.CENTER); // Top, Bottom, Center, fromBottom
                // xProps.setPropertyValue("VertOrientPosition", posY);
                xProps.setPropertyValue("VertOrientRelation", RelOrientation.TEXT_LINE); // Base line, Character, Row

                xProps.setPropertyValue("HoriOrient", HoriOrientation.CENTER); // 0:NONE=From left
                xProps.setPropertyValue("HoriOrientRelation", RelOrientation.PRINT_AREA); // 1:paragraph text area
            } else {
                HwpDoc.section.Page page = ConvPage.getCurrentPage().page;

                switch (table.vertRelTo) {
                case PAPER: // Anchor to Page
                    xProps.setPropertyValue("AnchorType", TextContentAnchorType.AT_PARAGRAPH);
                    switch (table.vertAlign) {
                    case TOP:
                        xProps.setPropertyValue("VertOrientRelation", RelOrientation.PAGE_FRAME); // 7:EntirePage,
                                                                                                  // 8:PageTextArea
                        if (table.vertOffset == 0) {
                            xProps.setPropertyValue("VertOrient", VertOrientation.TOP); // 1:Top, 2:Bottom, 2:Center,
                                                                                        // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("VertOrient", VertOrientation.NONE); // 0:NONE=From top
                            // page상단으로부터 frame상단까지의 offset
                            posY = Transform.translateHwp2Office(table.vertOffset);
                            xProps.setPropertyValue("VertOrientPosition", posY);
                        }
                        break;
                    case CENTER:
                        xProps.setPropertyValue("VertOrientRelation", RelOrientation.PAGE_FRAME); // 7:EntirePage,
                                                                                                  // 8:PageTextArea
                        if (table.vertOffset == 0) {
                            xProps.setPropertyValue("VertOrient", VertOrientation.CENTER); // 1:Top, 2:Bottom, 2:Center,
                                                                                           // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("VertOrient", VertOrientation.NONE); // 0:NONE=From top
                            // 중간지점에서 frame 중심까지의 offset -> page상단부터의 frame상단까지 offset으로 계산
                            posY = (Transform.translateHwp2Office(page.height)
                                    - Transform.translateHwp2Office(table.height)) / 2
                                    + Transform.translateHwp2Office(table.vertOffset);
                            xProps.setPropertyValue("VertOrientPosition", posY);
                        }
                        break;
                    case BOTTOM:
                        xProps.setPropertyValue("VertOrientRelation", RelOrientation.PAGE_FRAME); // 7:EntirePage,
                                                                                                  // 8:PageTextArea
                        if (table.vertOffset == 0) {
                            xProps.setPropertyValue("VertOrient", VertOrientation.BOTTOM); // 1:Top, 2:Bottom, 2:Center,
                                                                                           // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("VertOrient", VertOrientation.NONE); // 0:NONE=From top
                            // page하단에서 frame 하단까지의 offset을 -> page상단부터의 frame상단까지 offset으로 계산
                            posY = Transform.translateHwp2Office(page.height)
                                    - Transform.translateHwp2Office(table.height)
                                    - Transform.translateHwp2Office(table.vertOffset);
                            xProps.setPropertyValue("VertOrientPosition", posY);
                        }
                        break;
                    }
                    break;
                case PAGE:
                    // 그림에서 AnchorType을 AT_PAGE로 줄때 crash 발생
                    xProps.setPropertyValue("AnchorType", TextContentAnchorType.AT_PARAGRAPH);
                    switch (table.vertAlign) {
                    case TOP:
                        xProps.setPropertyValue("VertOrientRelation", RelOrientation.PAGE_PRINT_AREA); // 7:EntirePage,
                                                                                                       // 8:PageTextArea
                        if (table.vertOffset == 0) {
                            xProps.setPropertyValue("VertOrient", VertOrientation.TOP); // 1:Top, 2:Bottom, 2:Center,
                                                                                        // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("VertOrient", VertOrientation.NONE); // 0:NONE=From top
                            // page상단으로부터 frame상단까지의 offset
                            posY = Transform.translateHwp2Office(table.vertOffset);
                            xProps.setPropertyValue("VertOrientPosition", posY);
                        }
                        break;
                    case CENTER:
                        xProps.setPropertyValue("VertOrientRelation", RelOrientation.PAGE_PRINT_AREA); // 7:EntirePage,
                                                                                                       // 8:PageTextArea
                        if (table.vertOffset == 0) {
                            xProps.setPropertyValue("VertOrient", VertOrientation.CENTER); // 1:Top, 2:Bottom, 2:Center,
                                                                                           // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("VertOrient", VertOrientation.NONE); // 0:NONE=From top
                            // 중간지점에서 frame 중심까지의 offset -> page상단부터의 frame상단까지 offset으로 계산
                            int pageHeight = Transform.translateHwp2Office(page.height)
                                    - Transform.translateHwp2Office(page.marginTop)
                                    - Transform.translateHwp2Office(page.marginBottom);
                            posY = (pageHeight - Transform.translateHwp2Office(table.height)) / 2;
                            posY += Transform.translateHwp2Office(table.vertOffset);
                            xProps.setPropertyValue("VertOrientPosition", posY);
                        }
                        break;
                    case BOTTOM:
                        xProps.setPropertyValue("VertOrientRelation", RelOrientation.PAGE_PRINT_AREA); // 7:EntirePage,
                                                                                                       // 8:PageTextArea
                        if (table.vertOffset == 0) {
                            xProps.setPropertyValue("VertOrient", VertOrientation.BOTTOM); // 1:Top, 2:Bottom, 2:Center,
                                                                                           // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("VertOrient", VertOrientation.NONE); // 0:NONE=From top
                            // 쪽 하단에서 frame 하단까지의 offset을 -> 쪽 상단부터의 frame상단까지 offset으로 계산
                            int pageHeight = Transform.translateHwp2Office(page.height)
                                    - Transform.translateHwp2Office(page.marginTop)
                                    - Transform.translateHwp2Office(page.marginBottom);
                            posY = pageHeight - Transform.translateHwp2Office(table.height)
                                    - Transform.translateHwp2Office(table.vertOffset);
                            xProps.setPropertyValue("VertOrientPosition", posY);
                        }
                        break;
                    }
                    break;
                case PARA:
                    xProps.setPropertyValue("AnchorType", TextContentAnchorType.AT_PARAGRAPH);
                    switch (table.vertAlign) {
                    case TOP:
                        xProps.setPropertyValue("VertOrientRelation", RelOrientation.PRINT_AREA); // 7:EntirePage,
                                                                                                  // 8:PageTextArea
                        if (table.vertOffset == 0) {
                            xProps.setPropertyValue("VertOrient", VertOrientation.TOP); // 1:Top, 2:Bottom, 2:Center,
                                                                                        // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("VertOrient", VertOrientation.NONE); // 0:NONE=From top
                            // para상단으로부터 frame상단까지의 offset
                            posY = Math.max(Transform.translateHwp2Office(table.vertOffset), 0); // 음수값일때 0으로 대체
                            xProps.setPropertyValue("VertOrientPosition", posY);
                        }
                        break;
                    }
                    break;

                }

                switch (table.horzRelTo) {
                case PAPER:
                    switch (table.horzAlign) {
                    case LEFT: // LEFT
                    case INSIDE:
                        xProps.setPropertyValue("HoriOrientRelation", RelOrientation.PAGE_FRAME); // 7:EntirePage,
                                                                                                  // 8:PageTextArea
                        if (table.horzOffset == 0) {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT); // 1:Top, 2:Bottom, 2:Center,
                                                                                         // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.NONE); // 0:NONE=From top
                            // page상단으로부터 frame상단까지의 offset
                            posX = Transform.translateHwp2Office(table.horzOffset);
                            xProps.setPropertyValue("HoriOrientPosition", posX);
                        }
                        break;
                    case CENTER:
                        xProps.setPropertyValue("HoriOrientRelation", RelOrientation.PAGE_FRAME); // 7:EntirePage,
                                                                                                  // 8:PageTextArea
                        if (table.horzOffset == 0) {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.CENTER); // 1:Top, 2:Bottom, 2:Center,
                                                                                           // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.NONE); // 0:NONE=From top
                            // 중간지점에서 frame 중심까지의 offset -> page상단부터의 frame상단까지 offset으로 계산
                            posX = (Transform.translateHwp2Office(page.width)
                                    - Transform.translateHwp2Office(table.width)) / 2
                                    + Transform.translateHwp2Office(table.horzOffset);
                            xProps.setPropertyValue("HoriOrientPosition", posX);
                        }
                        break;
                    case RIGHT: // RIGHT
                    case OUTSIDE:
                        xProps.setPropertyValue("HoriOrientRelation", RelOrientation.PAGE_FRAME); // 7:EntirePage,
                                                                                                  // 8:PageTextArea
                        if (table.horzOffset == 0) {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.RIGHT); // 1:Top, 2:Bottom, 2:Center,
                                                                                          // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.NONE); // 0:NONE=From top
                            // page하단에서 frame 하단까지의 offset을 -> page상단부터의 frame상단까지 offset으로 계산
                            posX = Transform.translateHwp2Office(page.width)
                                    - Transform.translateHwp2Office(table.width)
                                    - Transform.translateHwp2Office(table.horzOffset);
                            xProps.setPropertyValue("HoriOrientPosition", posX);
                        }
                        break;
                    }
                    break;
                case PAGE:
                    switch (table.horzAlign) {
                    case LEFT: // LEFT
                    case INSIDE:
                        xProps.setPropertyValue("HoriOrientRelation", RelOrientation.PAGE_PRINT_AREA); // 7:EntirePage,
                                                                                                       // 8:PageTextArea
                        if (table.horzOffset == 0) {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT); // 1:Top, 2:Bottom, 2:Center,
                                                                                         // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.NONE); // 0:NONE=From left
                            // page상단으로부터 frame상단까지의 offset
                            posX = Transform.translateHwp2Office(table.horzOffset);
                            xProps.setPropertyValue("HoriOrientPosition", posX);
                        }
                        break;
                    case CENTER:
                        xProps.setPropertyValue("HoriOrientRelation", RelOrientation.PAGE_PRINT_AREA); // 7:EntirePage,
                                                                                                       // 8:PageTextArea
                        if (table.horzOffset == 0) {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.CENTER); // 1:Top, 2:Bottom, 2:Center,
                                                                                           // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.NONE); // 0:NONE=From left
                            // 중간지점에서 frame 중심까지의 offset -> page상단부터의 frame상단까지 offset으로 계산
                            int pageWidth = Transform.translateHwp2Office(page.width)
                                    - Transform.translateHwp2Office(page.marginLeft)
                                    - Transform.translateHwp2Office(page.marginRight);
                            posX = (pageWidth - Transform.translateHwp2Office(table.width)) / 2;
                            posX += Transform.translateHwp2Office(table.horzOffset);
                            xProps.setPropertyValue("HoriOrientPosition", posX);
                        }
                        break;
                    case RIGHT: // RIGHT
                    case OUTSIDE:
                        xProps.setPropertyValue("HoriOrientRelation", RelOrientation.PAGE_PRINT_AREA); // 7:EntirePage,
                                                                                                       // 8:PageTextArea
                        if (table.horzOffset == 0) {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.RIGHT); // 1:Top, 2:Bottom, 2:Center,
                                                                                          // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.NONE); // 0:NONE=From left
                            // page하단에서 frame 하단까지의 offset을 -> page상단부터의 frame상단까지 offset으로 계산
                            int pageWidth = Transform.translateHwp2Office(page.width)
                                    - Transform.translateHwp2Office(page.marginLeft)
                                    - Transform.translateHwp2Office(page.marginRight);
                            posX = pageWidth - Transform.translateHwp2Office(table.width)
                                    - Transform.translateHwp2Office(table.horzOffset);
                            xProps.setPropertyValue("HoriOrientPosition", posX);
                        }
                        break;
                    }
                    break;
                case COLUMN:
                case PARA:
                    switch (table.horzAlign) {
                    case LEFT: // LEFT
                    case INSIDE:
                        xProps.setPropertyValue("HoriOrientRelation", RelOrientation.PRINT_AREA); // 1:paragraph text
                                                                                                  // area
                        if (table.horzOffset == 0) {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.LEFT); // 1:Top, 2:Bottom, 2:Center,
                                                                                         // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.NONE); // 0:NONE=From left
                            // page상단으로부터 frame상단까지의 offset
                            posX = Transform.translateHwp2Office(table.horzOffset);
                            xProps.setPropertyValue("HoriOrientPosition", posX);
                        }
                        break;
                    case CENTER:
                        xProps.setPropertyValue("HoriOrientRelation", RelOrientation.PRINT_AREA); // 7:EntirePage,
                                                                                                  // 8:PageTextArea
                        if (table.horzOffset == 0) {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.CENTER); // 1:Top, 2:Bottom, 2:Center,
                                                                                           // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.NONE); // 0:NONE=From left
                            // 중간지점에서 frame 중심까지의 offset -> page상단부터의 frame상단까지 offset으로 계산
                            int pageWidth = Transform.translateHwp2Office(page.width)
                                    - Transform.translateHwp2Office(page.marginLeft)
                                    - Transform.translateHwp2Office(page.marginRight);
                            posX = (pageWidth - Transform.translateHwp2Office(table.width)) / 2;
                            posX += Transform.translateHwp2Office(table.horzOffset);
                            xProps.setPropertyValue("HoriOrientPosition", posX);
                        }
                        break;
                    case RIGHT: // RIGHT
                    case OUTSIDE:
                        xProps.setPropertyValue("HoriOrientRelation", RelOrientation.PRINT_AREA); // 7:EntirePage,
                                                                                                  // 8:PageTextArea
                        if (table.horzOffset == 0) {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.RIGHT); // 1:Top, 2:Bottom, 2:Center,
                                                                                          // 0:NONE(From top)
                        } else {
                            xProps.setPropertyValue("HoriOrient", HoriOrientation.NONE); // 0:NONE=From left
                            // page하단에서 frame 하단까지의 offset을 -> page상단부터의 frame상단까지 offset으로 계산
                            int pageWidth = Transform.translateHwp2Office(page.width)
                                    - Transform.translateHwp2Office(page.marginLeft)
                                    - Transform.translateHwp2Office(page.marginRight);
                            posX = pageWidth - Transform.translateHwp2Office(table.width)
                                    - Transform.translateHwp2Office(table.horzOffset);
                            xProps.setPropertyValue("HoriOrientPosition", posX);
                        }
                        break;
                    }
                    break;
                }
            }
        } catch (IllegalArgumentException | UnknownPropertyException | PropertyVetoException
                | WrappedTargetException e) {
            e.printStackTrace();
        }
    }

    private static void setFrameWrapStyle(XPropertySet xPropSet, Ctrl_Table shape) {

        // wrapStyle; // 0:어울림, 1:자리차지, 2:글 뒤로, 3:글 앞으로
        // wrapText; // 0:양쪽, 1:왼쪽, 2:오른쪽, 3:큰쪽
        try {
            switch (shape.textWrap) {
            case SQUARE: // 어울림
                xPropSet.setPropertyValue("Opaque", true);
                xPropSet.setPropertyValue("AllowOverlap", true); // THROUGH에서는 효과 없음.

                WrapTextMode wrapText = WrapTextMode.NONE;
                switch (shape.textFlow) {
                case 0x0: // 양쪽
                    wrapText = WrapTextMode.PARALLEL;
                    break;
                case 0x1: // 왼쪽
                    wrapText = WrapTextMode.LEFT;
                    break;
                case 0x2: // 오른쪽
                    wrapText = WrapTextMode.RIGHT;
                    break;
                case 0x3: // 큰쪽
                    wrapText = WrapTextMode.DYNAMIC;
                    break;
                }
                if (shape.treatAsChar == false) {
                	try {
                		xPropSet.setPropertyValue("SurroundContour", false);// contour는 THROUGH에서는 효과 없음
                	} catch (UnknownPropertyException e) {
                        e.printStackTrace();
                	}
                }
            	try {
            		xPropSet.setPropertyValue("TextWrap", wrapText);
            	} catch (UnknownPropertyException e) {
                    e.printStackTrace();
            	}
                break;
            case TOP_AND_BOTTOM: // 자리차지
                xPropSet.setPropertyValue("Opaque", true);
                if (shape.treatAsChar == false) {
                	try {
                		xPropSet.setPropertyValue("AllowOverlap", false); // issue #65 수정
                	} catch (UnknownPropertyException e) {
                        e.printStackTrace();
                	}
                }
                try {
                	xPropSet.setPropertyValue("TextWrap", WrapTextMode.NONE);
            	} catch (UnknownPropertyException e) {
                    e.printStackTrace();
            	}
                break;
            case BEHIND_TEXT: // 글 뒤로
                xPropSet.setPropertyValue("Opaque", false);
                if (shape.treatAsChar == false) {
                	try {
	                    xPropSet.setPropertyValue("AllowOverlap", true); // THROUGH에서는 효과 없음.
	                    xPropSet.setPropertyValue("IsAutomaticContour", false);
                	} catch (UnknownPropertyException e) {
                        e.printStackTrace();
                	}
                }
                try {
                	xPropSet.setPropertyValue("TextWrap", WrapTextMode.THROUGH);
            	} catch (UnknownPropertyException e) {
                    e.printStackTrace();
            	}
                break;
            case IN_FRONT_OF_TEXT: // 글 앞으로
                xPropSet.setPropertyValue("Opaque", true);
                if (shape.treatAsChar == false) {
                	try {
                		xPropSet.setPropertyValue("AllowOverlap", true); // THROUGH에서는 효과 없음.
                	} catch (UnknownPropertyException e) {
                        e.printStackTrace();
                	}
                }
                try {
                	xPropSet.setPropertyValue("TextWrap", WrapTextMode.DYNAMIC);
            	} catch (UnknownPropertyException e) {
                    e.printStackTrace();
            	}
                break;
            }
            // xPropSet.setPropertyValue("ZOrder", shape.zOrder);
        } catch (UnknownPropertyException | PropertyVetoException  | WrappedTargetException e) {
            e.printStackTrace();
        }
    }

    static void addCaptionString(WriterContext wContext, XText xFrameText, XTextCursor xFrameCursor, Ctrl_Table table,
            int step) {
        addCaptionString(wContext, xFrameText, xFrameCursor, table, 0, 0, step);
    }

    static void addCaptionString(WriterContext wContext, XText xFrameText, XTextCursor xFrameCursor, Ctrl_Table table,
            int leftSpacing, int rightSpacing, int step) {
        if (table.caption == null || table.caption.size() == 0)
            return;

        XParagraphCursor paraCursor = UnoRuntime.queryInterface(XParagraphCursor.class, xFrameCursor);
        XPropertySet paraProps = UnoRuntime.queryInterface(XPropertySet.class, paraCursor);

        List<String> capStr = new ArrayList<String>();
        short[] charShapeID = new short[1];
        Optional<Ctrl> ctrlOp = table.caption.stream().filter(c -> c.p != null)
        		                             .flatMap(c -> c.p.stream())
        		                             .filter(c -> c instanceof ParaText).findFirst();
        if (ctrlOp.isPresent()) {
            charShapeID[0] = (short) ((ParaText) ctrlOp.get()).charShapeId;
        }

        HwpCallback callback = new HwpCallback() {
            @Override
            public void onAutoNumber(Ctrl_AutoNumber autoNumber, int paraStyleID, int paraShapeID) {
                capStr.add(Integer.toString(++autoNum));
            };

            @Override
            public boolean onTab(String info) {
                capStr.add("\t");
                return true;
            };

            @Override
            public boolean onText(String content, int charShapeId, int charPos, boolean append) {
                capStr.add(content);
                charShapeID[0] = (short) charShapeId;
                return true;
            }

            @Override
            public boolean onParaBreak() {
                capStr.add("\r");
                return true;
            }
        };
        HwpRecurs.printParaRecurs(wContext, wContext, table.caption.get(0), callback, step);
        if (capStr.size() > 0) {
            if (step > 2) { // 본문위에 table은 step=2, Frame내에 들어간 table은 step=3
                if (capStr.get(capStr.size() - 1).equals("\r")) { // 마지막이 PARA_BREAK라면 출력하지 않음.
                    capStr.remove(capStr.size() - 1);
                }
            }

            String styleName = ConvPara.getStyleName((int) table.caption.get(0).paraStyleID);
            HwpRecord_ParaShape captionParaShape = wContext.getParaShape(table.caption.get(0).paraShapeID);
            HwpRecord_CharShape captionCharShape = wContext.getCharShape(charShapeID[0]);

            try {
                paraProps.setPropertyValue("ParaStyleName", styleName);
                ConvPara.setParagraphProperties(paraProps, captionParaShape, wContext.getDocInfo().compatibleDoc, captionCharShape.lineSpaceAlpha);
                HwpRecord_BorderFill borderFill = wContext.getBorderFill(captionCharShape.borderFillIDRef);
                ConvPara.setCharacterProperties(paraProps, captionCharShape, borderFill, step);
                paraProps.setPropertyValue("ParaTopMargin", Transform.translateHwp2Office(table.captionSpacing));
                paraProps.setPropertyValue("ParaBottomMargin", Transform.translateHwp2Office(table.captionSpacing));
                paraProps.setPropertyValue("ParaLeftMargin", Transform.translateHwp2Office(leftSpacing));
                paraProps.setPropertyValue("ParaRightMargin", Transform.translateHwp2Office(rightSpacing));
                for (String cap : capStr) {
                    xFrameText.insertString(xFrameCursor, cap, false);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    public static String mkCellNameBeforeMerge(TblCell[][] cellArray, int x, int y, int mergedY) {
        // cell에 대한 알파벳을 가져오려면,
        // null을 포함하고 (아직 머지하기 전의 알파벳을 구해야 하므로), nullColCount
        // 이전 row에서 rowpan으로 인한 colspan 분량을 빼고, otherRowsColSpan
        // 현재 row에서 자리 차지하는 알파벳 갯수 증가. curRowsCount

        int nullColCount = 0;
        for (int col = 0; col < x; col++) {
            if (cellArray[y][col] == null) {
                nullColCount++;
            }
        }

        int otherRowsColSpan = Arrays.stream(cellArray).flatMap(row -> Arrays.stream(row))
                .filter(cell -> cell != null && cell.rowAddr <= mergedY && cell.colAddr <= x
                        && cell.rowAddr + (cell.rowSpan - 1) >= y)
                .map(cell -> Integer.valueOf(cell.colSpan)).reduce(0, Integer::sum);

        int curRowsCount = (int) Arrays.stream(cellArray).flatMap(row -> Arrays.stream(row))
                .filter(cell -> cell != null)
                .filter(cell -> (cell.rowAddr <= mergedY && cell.rowAddr + (cell.rowSpan - 1) >= y && cell.colAddr < x)
                        || (cell.rowAddr == y && cell.colAddr < x))
                .count();

        int xx = (nullColCount + curRowsCount - otherRowsColSpan) / 26;
        int xxx = (nullColCount + curRowsCount - otherRowsColSpan) % 26;
        return (xx > 0 ? "" + ((char) ('a' + (xxx))) : "" + ((char) ('A' + xxx))) + (y + 1);
    }

    private static void setCellPara(String cellName, TblCell cell, XTextTable xtable, Ctrl_Table table,
            WriterContext wContext, HwpCallback cb, int step) {
        XCell xCell = xtable.getCellByName(cellName);
        if (xCell == null) {
            log.fine("Can't get CellName:" + cellName);
            return;
        }
        XText cellText = UnoRuntime.queryInterface(XText.class, xCell);
        if (cellText == null) {
            log.fine("Can't get CellText");
            return;
        }
        XTextCursor cellCursor = cellText.createTextCursor();
        if (cellCursor == null)
            return;

        WriterContext childContext = new WriterContext();
        childContext.mContext = wContext.mContext;
        childContext.mDesktop = wContext.mDesktop;
        childContext.mMCF = wContext.mMCF;
        childContext.mMSF = wContext.mMSF;
        childContext.mMyDocument = wContext.mMyDocument;
        childContext.userHomeDir = wContext.userHomeDir;
        childContext.mText = cellText;
        childContext.mTextCursor = cellCursor;

        // parabreak 앞으로 이동
        cellCursor.gotoStart(false);

        for (int paraIndex = 0; paraIndex < cell.paras.size(); paraIndex++) {
            boolean isLastPara = (paraIndex == cell.paras.size() - 1) ? true : false;
            HwpParagraph para = cell.paras.get(paraIndex);

            String styleName = ConvPara.getStyleName((int) para.paraStyleID);
            log.finer("StyleID=" + para.paraStyleID + ", StyleName=" + styleName);
            if (styleName == null || styleName.isEmpty()) {
                log.fine("Style Name is empty");
            }

            short[] charShapeID = new short[1];
            if (para.p != null) {
            	Optional<Ctrl> ctrlOp = para.p.stream().filter(ctrl -> ctrl!=null).findFirst();
                if (ctrlOp.isPresent()) {
                	Ctrl ctrl = ctrlOp.get();
                	if (ctrl instanceof ParaText) {
                        charShapeID[0] = (short) ((ParaText) ctrlOp.get()).charShapeId;
                	} else if (ctrl instanceof Ctrl_Character) {
                		charShapeID[0] = (short) ((Ctrl_Character) ctrlOp.get()).charShapeId;
                	}
                }
            }
            HwpRecord_Style paraStyle = wContext.getParaStyle(para.paraStyleID);
            HwpRecord_ParaShape paraShape = wContext.getParaShape(para.paraShapeID);
            HwpRecord_CharShape charShape = wContext.getCharShape(charShapeID[0]);

            if (para.p == null || para.p.size() == 0) {
                if (isLastPara == false) {
                    HwpRecurs.insertParaString(childContext, "\r", para.lineSegs, styleName, paraStyle, paraShape,
                            charShape, true, true, step);
                }
                continue;
            }

            HwpCallback callback = new HwpCallback() {
                @Override
                public void onAutoNumber(Ctrl_AutoNumber autoNumber, int paraStyleID, int paraShapeID) {
                };

                @Override
                public boolean onTab(String info) {
                    HwpRecurs.insertParaString(childContext, "\t", para.lineSegs, styleName, paraStyle, paraShape,
                            charShape, true, true, step);
                    return true;
                };

                @Override
                public boolean onText(String content, int charShapeId, int charPos, boolean append) {
                    String styleNameTemp = ConvPara.getStyleName((int) para.paraStyleID);
                    HwpRecord_Style paraStyleTemp = wContext.getParaStyle(para.paraStyleID);
                    HwpRecord_ParaShape paraShape = wContext.getParaShape(para.paraShapeID);
                    HwpRecord_ParaShape paraShapeTemp = null;
                    try {
                        paraShapeTemp = HwpRecord_ParaShape.clone(paraShape);
                        if (cell.paras.size()==1) {
                            // Cell내 문단이 1개만 있는 경우, 선 간격을 최소로 한다. LibreOffice와 Hwp 간격 차이를 해소하기 위함.
                            paraShapeTemp.lineSpacing = 100;
                            paraShapeTemp.lineSpacingType = 0x3;
                        }
                    } catch (java.lang.ClassNotFoundException | IOException e) {
                        e.printStackTrace();
                    }
                    HwpRecord_CharShape charShapeTemp = HwpRecord_CharShape.clone(wContext.getCharShape((short) charShapeId));
                    // 테이블내에서는 자간을 원래(-50%~50%)보다 작게(-60%~47%) 변경해서 쓴다. 육안으로 크게 차이가 나지 않는 범위내에서 테이블 셀에 가능한 모두 보이도록 하기 위함
                    for (int i=0; i<charShapeTemp.spacing.length; i++) {
                        charShapeTemp.spacing[i] -= ((100-charShapeTemp.spacing[i])/15);
                    }
                    HwpRecurs.insertParaString(childContext, content, para.lineSegs, styleNameTemp, paraStyleTemp,
                                               paraShapeTemp, charShapeTemp, append, true, step);
                    return true;
                }

                @Override
                public boolean onParaBreak() {
                    if (isLastPara == false) {
                    	return false;
                    } else {
                    	return true;
                    }
                }
            };
            HwpRecurs.printParaRecurs(childContext, wContext, para, callback, 2);
        }
    }

    private static TblCell[][] removeAllNullColumns(TblCell[][] cellArray) {
        TblCell[][] newCellArray = null;
        List<Integer> allNullColList = new ArrayList<Integer>();

        int rowSize = cellArray.length;
        int maxColSize = Arrays.stream(cellArray).map(row -> row.length)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream()
                .max(Map.Entry.comparingByValue()).get().getKey();

        for (int col = 0; col < maxColSize; col++) {
            int nCol = col;
            boolean exists = IntStream.range(0, rowSize).mapToObj(r -> cellArray[r][nCol]).anyMatch(c -> c != null);
            if (exists == false) {
                allNullColList.add(col);
            }
        }

        if (allNullColList.size() > 0) {
            // Collections.reverse(allNullColList);
            newCellArray = new TblCell[cellArray.length][maxColSize - allNullColList.size()];
            for (int oldCol = 0, newCol = 0; oldCol < maxColSize; oldCol++) {
                if (allNullColList.contains(oldCol) == false) {
                    // all null 칼럼이 아니면,
                    for (int row = 0; row < newCellArray.length; row++) {
                        newCellArray[row][newCol] = cellArray[row][oldCol];
                        if (newCellArray[row][newCol] != null) {
                            newCellArray[row][newCol].rowAddr = (short) row;
                            newCellArray[row][newCol].colAddr = (short) newCol;
                        }
                    }
                    newCol++;
                } else {
                    // all null 칼럼이라면,
                    for (int row = 0; row < newCellArray.length; row++) {
                        log.finest("Removing null column. originalCol=" + oldCol + ", row=" + row);
                        if (newCol > 0) {
                            int nRow = row, nNewCol = newCol;
                            Optional<Integer> lastColOp = Arrays.stream(newCellArray[row]).filter(c -> c != null)
                                    .filter(c -> c.colAddr < nNewCol).map(c -> Integer.valueOf(c.colAddr))
                                    .reduce(Integer::max);
                            if (lastColOp.isPresent()) {
                                int lastCol = lastColOp.get();
                                if (newCellArray[row][lastCol].colSpan > 1) {
                                    newCellArray[row][lastCol].colSpan -= 1;
                                }
                            }
                        }
                    }
                }
            }

        } else {
            newCellArray = cellArray;
        }
        return newCellArray;
    }

    private static int calculateEquasion(List<TblCell> list, int[] colWidth, int col, int span, boolean isColumn) {
        int ret = 0;

        if (span == 1) {
            for (TblCell cell : list) {
                if (isColumn) {
                    if (cell.width > 0 && cell.colSpan == 1 && cell.colAddr == col) {
                        ret = cell.width;
                        break;
                    }
                } else {
                    if (cell.height > 0 && cell.rowSpan == 1 && cell.rowAddr == col) {
                        ret = cell.height;
                        break;
                    }
                }
            }
        } else {
            // 예) span==5 일때
            // [-4] [-3] [-2] [-1] [ 0] [ ] [ ] [ ] [ ]
            // [ ] [-3] [-2] [-1] [ 0] [ 1] [ ] [ ] [ ]
            // [ ] [ ] [-2] [-1] [ 0] [ 1] [ 2] [ ] [ ]
            // [ ] [ ] [ ] [-1] [ 0] [ 1] [ 2] [ 3] [ ]
            // [ ] [ ] [ ] [ ] [ 0] [ 1] [ 2] [ 3] [ 4]
            // int span_width[] = new int[5];
            // for (TblCell cell: list) {
            // if (cell.width>0 && cell.colSpan==5 && cell.colAddr==col-4) {
            // span_width[0] = cell.width;
            // } else if (cell.width>0 && cell.colSpan==5 && cell.colAddr==col-3) {
            // span_width[1] = cell.width;
            // } else if (cell.width>0 && cell.colSpan==5 && cell.colAddr==col-2) {
            // span_width[2] = cell.width;
            // } else if (cell.width>0 && cell.colSpan==5 && cell.colAddr==col-1) {
            // span_width[3] = cell.width;
            // } else if (cell.width>0 && cell.colSpan==5 && cell.colAddr==col) {
            // span_width[4] = cell.width;
            // }
            // }
            // if (span_width[0]>0 && colWidth[col-4]>0 && colWidth[col-3]>0 &&
            // colWidth[col-2]>0 && colWidth[col-1]>0) {
            // ret = span_width[0] - colWidth[col-4] - colWidth[col-3] - colWidth[col-2] -
            // colWidth[col-1];
            // } else if (span_width[1]>0 && colWidth[col-3]>0 && colWidth[col-2]>0 &&
            // colWidth[col-1]>0 && colWidth[col+1]>0) {
            // ret = span_width[1] - colWidth[col-3] - colWidth[col-2] - colWidth[col-1] -
            // colWidth[col+1];
            // } else if (span_width[2]>0 && colWidth[col-2]>0 && colWidth[col-1]>0 &&
            // colWidth[col+1]>0 && colWidth[col+2]>0) {
            // ret = span_width[2] - colWidth[col-2] - colWidth[col-1] - colWidth[col+1] -
            // colWidth[col+2];
            // } else if (span_width[3]>0 && colWidth[col-1]>0 && colWidth[col+1]>0 &&
            // colWidth[col+2]>0 && colWidth[col+3]>0) {
            // ret = span_width[3] - colWidth[col-1] - colWidth[col+1] - colWidth[col+2] -
            // colWidth[col+3];
            // } else if (span_width[4]>0 && colWidth[col+1]>0 && colWidth[col+2]>0 &&
            // colWidth[col+3]>0 && colWidth[col+4]>0) {
            // ret = span_width[4] - colWidth[col+1] - colWidth[col+2] - colWidth[col+3] -
            // colWidth[col+4];
            // }

            int span_width[] = new int[span];
            for (TblCell cell : list) {
                for (int idx = 0; idx < span; idx++) {
                    if (isColumn) {
                        if (cell.width > 0 && cell.colSpan == span && cell.colAddr == col - (span - 1) + idx) {
                            span_width[idx] = cell.width;
                        }
                    } else {
                        if (cell.height > 0 && cell.rowSpan == span && cell.rowAddr == col - (span - 1) + idx) {
                            span_width[idx] = cell.height;
                        }
                    }
                }
            }
            for (int idx = 0; idx < span; idx++) {
                boolean proceed = true;
                if (span_width[idx] <= 0)
                    continue;

                for (int colStart = col - (span - 1) + idx; colStart <= col + idx; colStart++) {
                    if (colStart == col)
                        continue;
                    if (colWidth[colStart] <= 0) {
                        proceed = false;
                        break;
                    }
                }

                if (proceed) {
                    ret = span_width[idx];
                    for (int colStart = col - (span - 1) + idx; colStart <= col + idx; colStart++) {
                        if (colStart == col)
                            continue;
                        ret -= colWidth[colStart];
                    }
                    break;
                }
            }
        }

        return ret;
    }

    private static int[] calculateColumnWidth(TblCell[][] cellArray, int totalWidth) {
        int nWidth = cellArray[0].length;
        int[] colWidth = new int[nWidth];

        // print
        for (int row = 0; row < cellArray.length; row++) {
            log.finest("CELLS [" + row + "]=" + Arrays.stream(cellArray[row])
                    .map(cell -> cell == null ? "" : String.valueOf(cell.width)).collect(Collectors.joining(",")));
        }

        // span loop
        for (int span = 1; span < nWidth; span++) {
            if (Arrays.stream(colWidth).filter(w -> w == 0).count() == 0) {
                log.finest("Span Loop:"
                        + Arrays.stream(colWidth).mapToObj(w -> String.valueOf(w)).collect(Collectors.joining(",")));
                break;
            }
            // column loop
            for (int col = 0; col < nWidth; col++) {
                if (colWidth[col] != 0)
                    continue;
                int nSpan = span;
                int nCol = col;
                List<TblCell> colWidthList = Arrays.stream(cellArray).flatMap(Arrays::stream)
                        .filter(cell -> cell != null && cell.colSpan == nSpan && cell.colAddr <= nCol
                                && cell.colAddr + nSpan >= nCol)
                        .collect(Collectors.toList());
                colWidth[col] = calculateEquasion(colWidthList, colWidth, col, span, true);
            }
        }

        // span loop
        for (int span = 2; span < nWidth; span++) {
            if (Arrays.stream(colWidth).filter(w -> w == 0).count() == 0) {
                log.finest("Span Loop:"
                        + Arrays.stream(colWidth).mapToObj(w -> String.valueOf(w)).collect(Collectors.joining(",")));
                break;
            }
            // column loop
            for (int col = 0; col < nWidth; col++) {
                if (colWidth[col] != 0)
                    continue;
                int nSpan = span;
                int nCol = col;
                List<TblCell> colWidthList = Arrays.stream(cellArray).flatMap(Arrays::stream)
                        .filter(cell -> cell != null && cell.colSpan == nSpan && cell.colAddr <= nCol
                                && cell.colAddr + nSpan >= nCol)
                        .collect(Collectors.toList());
                colWidth[col] = calculateEquasion(colWidthList, colWidth, col, span, true);
            }
        }

        log.finest("caculated:"
                + Arrays.stream(colWidth).mapToObj(w -> String.valueOf(w)).collect(Collectors.joining(",")));
        long emptyCols = Arrays.stream(colWidth).filter(w -> w <= 0).count();
        long widthSum = Arrays.stream(colWidth).filter(w -> w > 0).sum();
        if (emptyCols > 0) {
            int delta = (int) ((totalWidth - widthSum) / emptyCols);
            for (int col = 0; col < nWidth; col++) {
                if (colWidth[col] <= 0) {
                    colWidth[col] = delta;
                }
            }
        }

        int[] reducedColWidth = IntStream.range(0, nWidth - 1).map(i -> colWidth[i]).toArray();
        log.finest("reduced:"
                + Arrays.stream(reducedColWidth).mapToObj(w -> String.valueOf(w)).collect(Collectors.joining(",")));

        return reducedColWidth;
    }

    private static int[] calculateRowHeight(TblCell[][] cellArray, int totalHeight) {
        int nRow = cellArray.length;
        int[] rowHeight = new int[nRow];

        if (nRow == 1) {
        	rowHeight[0] = Arrays.stream(cellArray[0]).filter(c -> c!=null)
        			             .mapToInt(c -> c.height).min().orElse(0); 
        }
        // print
        for (int row = 0; row < cellArray.length; row++) {
            log.finest("CELLS [" + row + "]=" + Arrays.stream(cellArray[row])
                    .map(cell -> cell == null ? "" : String.valueOf(cell.height)).collect(Collectors.joining(",")));
        }

        // span loop
        for (int span = 1; span < nRow; span++) {
            if (Arrays.stream(rowHeight).filter(w -> w == 0).count() == 0) {
                log.finest("Span Loop:"
                        + Arrays.stream(rowHeight).mapToObj(w -> String.valueOf(w)).collect(Collectors.joining(",")));
                break;
            }
            // row loop
            for (int row = 0; row < nRow; row++) {
                if (rowHeight[row] != 0)
                    continue;
                int nSpan = span;
                int nR = row;
                List<TblCell> rowHeightList = Arrays.stream(cellArray).flatMap(Arrays::stream)
                        .filter(cell -> cell != null && cell.rowSpan == nSpan && cell.rowAddr <= nR
                                && cell.rowAddr + nSpan >= nR)
                        .collect(Collectors.toList());
                rowHeight[row] = calculateEquasion(rowHeightList, rowHeight, row, span, false);
            }
        }

        // span loop
        for (int span = 2; span < nRow; span++) {
            if (Arrays.stream(rowHeight).filter(w -> w == 0).count() == 0) {
                log.finest("Span Loop:"
                        + Arrays.stream(rowHeight).mapToObj(w -> String.valueOf(w)).collect(Collectors.joining(",")));
                break;
            }
            // row loop
            for (int row = 0; row < nRow; row++) {
                if (rowHeight[row] != 0)
                    continue;
                int nSpan = span;
                int nR = row;
                List<TblCell> rowHeightList = Arrays.stream(cellArray).flatMap(Arrays::stream)
                        .filter(cell -> cell != null && cell.rowSpan == nSpan && cell.rowAddr <= nR
                                && cell.rowAddr + nSpan >= nR)
                        .collect(Collectors.toList());
                rowHeight[row] = calculateEquasion(rowHeightList, rowHeight, row, span, false);
            }
        }

        log.finest("caculated:"
                + Arrays.stream(rowHeight).mapToObj(w -> String.valueOf(w)).collect(Collectors.joining(",")));
        return rowHeight;
    }

    private static boolean hasNullRow(int[] rowHeight, int totalHeight) {
        long sum = Arrays.stream(rowHeight).sum();
        if (Math.abs(totalHeight-sum) > totalHeight*5/100)
            return true;

        long cnt = Arrays.stream(rowHeight).filter(w -> w == 0).count();
        if (cnt > 0)
            return true;
        else
            return false;
    }
    
    private static void setBackGraphic(WriterContext wContext, XPropertySet xStyleProps, String binDataID) throws Exception {
        // image ByteArray로 그림 그리기
        Object graphicProviderObject = wContext.mMCF.createInstanceWithContext("com.sun.star.graphic.GraphicProvider", wContext.mContext);
        XGraphicProvider xGraphicProvider = UnoRuntime.queryInterface(XGraphicProvider.class, graphicProviderObject);

        byte[] imageAsByteArray = null;
        String imageType = "";

        imageAsByteArray = wContext.getBinBytes(binDataID);
        imageType = wContext.getBinFormat(binDataID);

        if (imageAsByteArray == null || imageAsByteArray.length == 0) {
            log.severe("Something Wrong!!!. skip drawing");
            return;
        }

        PropertyValue[] v = new PropertyValue[2];
        v[0] = new PropertyValue();
        v[0].Name = "InputStream";
        v[0].Value = new ByteArrayToXInputStreamAdapter(imageAsByteArray);
        v[1] = new PropertyValue();
        v[1].Name = "MimeType";
        switch (imageType.toLowerCase()) {
        case "png":
            v[1].Value = "image/png";
            break;
        case "bmp":
            v[1].Value = "image/bmp";
            break;
        case "wmf":
            v[1].Value = "image/x-wmf";
            break;
        case "jpg":
            v[1].Value = "image/jpeg";
            break;
        case "gif":
            v[1].Value = "image/gif";
            break;
        case "tif":
            v[1].Value = "image/tiff";
            break;
        case "svg":
            v[1].Value = "image/svg+xml";
            break;
        }

        XGraphic graphic = xGraphicProvider.queryGraphic(v);

        if (graphic == null) {
            log.severe("Error loading the image");
        } else {
            xStyleProps.setPropertyValue("BackGraphic", graphic);
            xStyleProps.setPropertyValue("BackTransparent", false);
            xStyleProps.setPropertyValue("BackGraphicLocation", GraphicLocation.MIDDLE_MIDDLE);
        }
    }

}