[SOLVED] Adding columns to a Word document table (FPVectorial) lazarus / 54-FPvectorial ---------------------------------------------------------------------- JD · 2019-04-15 22:06 Hi there everyone, I am using the FPVectorial library to create a Word/ODF document that contains a table with 2 columns. According to the example on this page http://wiki.lazarus.freepascal.org/fpvectorial_- _Text_Document_Support#Simple_Table in the Wiki, a table is created with ONE column by default and to add another column, it is necessary to use AddColWidths. However, AddColWidths is no longer available!! It looks like the code has been refactored and AddColWidths has been removed. My code is as shown below: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i     AttitudesTable                 := Page.AddTable;    AttitudesTable.PreferredWidth   := Dimension(100, dimPercent);    AttitudesTable.ColWidthsUnits   := dimMillimeter;    AttitudesTable.AddColWidths(50);      <------ This does not work any more!!!  How can I create a second column in my Attitudes table? Thanks a lot for your kind assistance. Cheers, JD ---------------------------------------------------------------------- JD · 2019-04-16 11:43 Any ideas? Anyone? ---------------------------------------------------------------------- JD · 2019-04-16 12:57 Alternatively, can one add 2 cells horizontally side by side in the same row? JD ---------------------------------------------------------------------- Mike.Cornflake · 2019-04-16 16:29 I'm away from code right now, but what happens when you run the example code? Also - I note you have typed AddColWidths.  The call is (or should be) AddColWidth (ie singluar) Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Table.AddColWidth(50); UPDATE: Ug.  Looking at the pas file online (https://svn.freepascal.org/svn/la zarus/trunk/components/fpvectorial/fpvectorial.pas), I concur that call is no longer present.  No idea who removed it or why :-(   It'll be more than a few days before I get a chance to look at this though. UPDATE2: It's been more than 4 years since I wrote that code.  Looking through docxvectorialwriter.pas.Procedure ProcessTable(ATable: TvTable);  ColWidths is optional.  It's sufficient to add Cells to a row to determine column count. Reading the comments on the wiki - looks like ColWidths is ONLY essential if you're merging cells AND writing to ODT. All I can suggest is you try, and in a few days I'll try and understand if a change has been made and why. ---------------------------------------------------------------------- JD · 2019-04-16 17:46 @Mike.Cornflake Thank you very much for your reply. I was getting desperate.  I looked at the code for TvTable. It is defined as follows: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   (*      Note on the grid used for the table       For the table shown below, three ColWidths must be defined.       First row should only have 2 cells. First cell spans 2 columns.      Second row should only have 2 cells. Second cell spans 2 columns.      Third row should have 3 cells.  Each cell only spans 1 column (default)    X,Y +-----+------+---------+       |            |         |       +-----+----------------+       |     |                |       +-----+------+---------+       |     |      |         |       +-----+------+---------+        The table draws at X,Y and downwards  *)   // TvTable.Style should be a Table Style, not a Paragraph Style  // and is optional.  TvTable = class(TvEntityWithStyle)  private    Rows: TFPList;    ColWidthsInMM: array of Double;   // calculated during Render    TableWidth, TableHeight: Double;  // in mm; calculated during Render    procedure CalculateColWidths(constref ARenderInfo: TvRenderInfo);    procedure CalculateRowHeights(constref ARenderInfo: TvRenderInfo);  public    ColWidths: array of Double;     // Can be left empty for simple tables                                    // MUST be fully defined for merging cells    ColWidthsUnits : TvUnits;         // Cannot mix ColWidth Units.    Borders : TvTableBorders;         // Defaults: single/black/inside and out    PreferredWidth : TvDimension;     // Optional. Units mm.    SpacingBetweenCells: Double;      // Units mm. Gap between Cells.    CellSpacingLeft, CellSpacingRight, CellSpacingTop,      CellSpacingBottom: Double;      // space around each side of cells, in mm    BackgroundColor : TFPColor;       // Optional.     constructor create(APage : TvPage); override;    destructor destroy; override;   function AddRow: TvTableRow;    function GetRowCount : Integer;    function GetRow(AIndex: Integer) : TvTableRow;    //    function GetColCount(): Integer;    //    procedure Render(var ARenderInfo: TvRenderInfo; ADoDraw: Boolean = True); override;    function GenerateDebugTree(ADestRoutine: TvDebugAddItemProc; APageItem: Pointer): Pointer; override;  end;  There does not seem to be any way to add several columns to a table. By the way, I must congratulate the authors of fpvectorial because it produces perfect Microsoft Word documents. I was pleasantly surprised. I just need to be able to create multi- columned tables in those Word documents. Cheers, JD ---------------------------------------------------------------------- Mike.Cornflake · 2019-04-16 18:44 > There does not seem to be any way to add several columns to a table. Add multiple cells to a row.   Go on, try it :-)   As I said before, looking at docxwriter, this should be sufficient. ---------------------------------------------------------------------- JD · 2019-04-17 09:30 Quote from: Mike.Cornflake on April 16, 2019, 08:44:52 pm> There does not seem to be any way to add several columns to a table. Add multiple cells to a row.   Go on, try it :-)   As I said before, looking at docxwriter, this should be sufficient. I tried it but the resulting Word document is corrupted and cannot be opened. I added a second Cell := Row.AddCell; a line Cell2 := Row.AddCell; a fluent programming style with Cell := Row.AddCell.Row.AddCell; It all created unreadable Word documents This is what I'm trying to do. I am trying to create a work schedule document with 2 columns: Days & Hours Worked. The code I'm using is as follows (of course in the real world, the hours will be input manually): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.Button1Click(Sender: TObject);var  Document: TvVectorialDocument;  Page: TvTextPageSequence;  BoldTextStyle: TvStyle;  HeaderParagraph, Paragraph: TvParagraph;  DaysTable: TvTable;  Row: TvTableRow;  Cell, Cell2: TvTableCell;  intRow, intTotalRows: integer;  DaysArray, HoursWorkedArray: array of string;begin  //  DaysArray := ['DAYS', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];  HoursWorkedArray := ['HOURS WORKED', '4', '7', '8', '8', '4', '8', '0'];   // Create the document  Document := TvVectorialDocument.Create;   //  try     //  Adds the defaut Paragraph Styles    //    StyleTextBody, StyleHeading1,    //    StyleHeading2 & StyleHeading3    Document.AddStandardTextDocumentStyles(vfUnknown);     // Add our own Style    BoldTextStyle             := Document.AddStyle();    BoldTextStyle.Kind        := vskTextSpan;    BoldTextStyle.Name        := 'Bold';    BoldTextStyle.Font.Bold   := True;    BoldTextStyle.SetElements := BoldTextStyle.SetElements + [spbfFontBold];     // Add a page and a paragraph    Page                    := Document.AddTextPageSequence;    //    HeaderParagraph         := Page.AddParagraph;    HeaderParagraph.Style     := Document.StyleHeading1Centralized;    HeaderParagraph.AddText('WORK SCHEDULE');    HeaderParagraph           := Page.AddParagraph;     // Add the Days table    DaysTable                  := Page.AddTable;    DaysTable.PreferredWidth   := Dimension(100, dimPercent);    DaysTable.ColWidthsUnits   := dimMillimeter;     // Get the number of rows to add to the table    intTotalRows := Length(DaysArray);    //  for intRow := 0 to Pred(intTotalRows) do    begin      Row                          := DaysTable.AddRow;      if intRow = 0 then      begin        Row.BackgroundColor := RGBToFPColor(192, 192, 192); // Grey Shading        Row.Header := True; // Tell the table this is a Header Row      end;      Cell                           := Row.AddCell;      Paragraph                      := Cell.AddParagraph;      Paragraph.Style                := Document.StyleTextBody;      Paragraph.AddText(DaysArray[intRow]).Style := BoldTextStyle;    end;     try      // Save the document      Document.WriteToFile('Work schedule.docx', vfDOCX);    except      raise;    end;  finally    Document.Free;  end;end;  The resulting Microsoft Word document created from the code above is in the attachment. This is where I am as of today. Any help will be greatly appreciated. Thanks, JD ---------------------------------------------------------------------- Mike.Cornflake · 2019-04-17 10:01 Yup - as you say - it's broken.  I've confirmed the full write test I wrote no longer works. Here's the original function Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function TvTable.AddColWidth(AValue: Double): Integer;begin  SetLength(ColWidths, Length(ColWidths) + 1);  ColWidths[High(ColWidths)] := AValue;end; ColWidths is an array of double, and it's in TvTable.Public.   So you can implement your own AddColWidth and see if that produces a working docx :-( Sorry about this :-( Mike UPDATE: In order to get fpvtextwritetest2 to run, I added the following helper routine. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i     Procedure AddColWidth(ATable: TvTable; AValue: Double);    begin      SetLength(ATable.ColWidths, Length(ATable.ColWidths) + 1);      ATable.ColWidths[High(ATable.ColWidths)] := AValue;    end;   I then changed all calls from Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i     CurTable.AddColWidth( 15);    CurTable.AddColWidth(20);    CurTable.AddColWidth(20);    CurTable.AddColWidth(20);    CurTable.AddColWidth(79.5); // For Word (and possibly odt), this only has to be close. to Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i     AddColWidth(CurTable, 15);    AddColWidth(CurTable, 20);    AddColWidth(CurTable, 20);    AddColWidth(CurTable, 20);    AddColWidth(CurTable, 79.5); // For Word (and possibly odt), this only has to be close. Result Word Document was well formed and worked. When I'm back on land I'll submit a patch and get the original code restored.   Either that or get the author of revision 55389 to update the wiki.  My preference is original code restored. ---------------------------------------------------------------------- JD · 2019-04-17 10:38 @Mike.Cornflake No need to be sorry. I added a class helper to my code as follows: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  { TvTableHelper }  TvTableHelper = class helper for TvTable  public    function AddColWidth(AValue: Double): Integer;  end; { TvTableHelper } function TvTableHelper.AddColWidth(AValue: Double): Integer;begin  SetLength(ColWidths, Length(ColWidths) + 1);  ColWidths[High(ColWidths)] := AValue;end;   My new document creation code now becomes: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.Button1Click(Sender: TObject);var  Document: TvVectorialDocument;  Page: TvTextPageSequence;  BoldTextStyle: TvStyle;  HeaderParagraph, Paragraph: TvParagraph;  DaysTable: TvTable;  Row: TvTableRow;  Cell, Cell2: TvTableCell;  intRow, intTotalRows: integer;  DaysArray, HoursWorkedArray: array of string;begin  //  DaysArray := ['DAYS', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];  HoursWorkedArray := ['HOURS WORKED', '4', '7', '8', '8', '4', '8', '0'];   // Create the document  Document := TvVectorialDocument.Create;   //  try     //  Adds the defaut Paragraph Styles    //    StyleTextBody, StyleHeading1,    //    StyleHeading2 & StyleHeading3    Document.AddStandardTextDocumentStyles(vfUnknown);     // Add our own Style    BoldTextStyle             := Document.AddStyle();    BoldTextStyle.Kind        := vskTextSpan;    BoldTextStyle.Name        := 'Bold';    BoldTextStyle.Font.Bold   := True;    BoldTextStyle.SetElements := BoldTextStyle.SetElements + [spbfFontBold];     // Add a page and a paragraph    Page                    := Document.AddTextPageSequence;    //    HeaderParagraph         := Page.AddParagraph;    HeaderParagraph.Style     := Document.StyleHeading1Centralized;    HeaderParagraph.AddText('WORK SCHEDULE');    HeaderParagraph           := Page.AddParagraph;     // Add the Days table    DaysTable                  := Page.AddTable;    DaysTable.PreferredWidth   := Dimension(100, dimPercent);    DaysTable.ColWidthsUnits   := dimMillimeter;    // Add 2 columns    DaysTable.AddColWidth(50);    DaysTable.AddColWidth(50);     // Get the number of rows to add to the table    intTotalRows := Length(DaysArray);    //    for intRow := 0 to Pred(intTotalRows) do  begin      Row                            := DaysTable.AddRow;      if intRow = 0 then      begin        Row.BackgroundColor := RGBToFPColor(192, 192, 192); // Grey Shading        Row.Header := True; // Tell the table this is a Header Row      end;      Cell                         := Row.AddCell;      Paragraph                    := Cell.AddParagraph;      Paragraph.Style                := Document.StyleTextBody;      Paragraph.AddText(DaysArray[intRow]).Style := BoldTextStyle;    end;     try      // Save the document      Document.WriteToFile('Work schedule.docx', vfDOCX);    except      raise;    end;  finally    Document.Free;  end;end;  But it stll creates a table with one column!! What is it that I am missing? Thanks a lot for your assistance, JD ---------------------------------------------------------------------- JD · 2019-04-17 10:39 I didn't see the updates you added to your last post. I'll try them now..... ---------------------------------------------------------------------- JD · 2019-04-17 10:56 It worked!!!! Thanks a lot Mike.Cornflake. I'll post the final solution later today to help those who might be facing a similar problem. JD ---------------------------------------------------------------------- Mike.Cornflake · 2019-04-17 10:59 I've never used Class Helpers.  Can't see why your code didn't work, but glad we finally got there :-)  Many thanks for your patience with this issue. ---------------------------------------------------------------------- JD · 2019-04-17 11:03 Quote from: Mike.Cornflake on April 17, 2019, 12:59:59 pmI've never used Class Helpers.  Can't see why your code didn't work, but glad we finally got there :-)  Many thanks for your patience with this issue. The code with the class helper and your own code all work perfectly now.  Class helpers extend the functionality of existing classes without the need of modifying the classes themselves. I use them when I am not the author of a class and I either don't have the source code for the class OR I don't want to modify it so that I don't break anything. JD ---------------------------------------------------------------------- JD · 2019-04-17 14:20 Here is the sample published project in case anyone has a similar problem. JD ---------------------------------------------------------------------- Dean Qin · 2019-10-24 13:10 Quote from: JD on April 17, 2019, 04:20:20 pmHere is the sample published project in case anyone has a similar problem. JD Hi, JD thanks for your example, it's very helpful. I have another question, do you know why we should add a space after a single char , otherwise it will become empty? As i tested, every single char such as 'A', 'B', or '1', '2'... will be empty in saved docx or odt file ---------------------------------------------------------------------- Mike.Cornflake · 2019-10-24 19:05 G'day, Heh.  I've only been offshore twice this year, and both times bugs in my code have been found. Apologies @JD, when I got back onshore I completely forgot to follow up and get the trunk code fixed.  And I see CellSpacing has now failed QuoteAs i tested, every single char such as 'A', 'B', or '1', '2'... will be empty in saved docx or odt file @qindj Right - I've confirmed that indeed there is a bug.  I'll get to it, but in the meantime you're going to need to keep appending those spaces.  I'm away from IDE at the moment (Yes, offshore again working 12 hours shifts). The following are my quick notes to assist with chasing this when I have time.   I'm planned to be back on shore Nov 4, so I should reply sometime in the weekend following that.  If you haven't heard, ping me (pm or here) and remind me. The issue is likely in docxvectorialwriter.pas, Line 703.  For some reason AddTextRun doesn't look like it's being run (in the xml of the resulting word document, not only is the there no text, but there's no w:r tag written either, and that's done in AddtextRun).  Oh, or AddTextRun  is being passed an empty string.  Ah, that's makes more sense.  If it's being passed with an empty string, then the following code needs to be tightened to ONLY strip CR or LF.  Line 696: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i         // Strip out the trailing line break        // added by TStringList.Text        If DefaultTextLineBreakStyle = tlbsCRLF Then          sTemp := Copy(sTemp, 1, Length(sTemp) - 2)        Else          sTemp := Copy(sTemp, 1, Length(sTemp) - 1); If my suspicion is right about that code being overzealous and stripping two chars when there is only one to be stripped, then I'd expect missing characters all over the place.  Replacement code for the above should be TrimChars(, [CR, LF]).  There will be one floating around somewhere.  Not sure, but have to resume work now :-( Cheers Mike UPDATE:   OK, I've broken out an IDE.  No, it wasn't the above code. Issue is actually in AddTextRun.  I'm parsing over the passed string - looking for internal LF, CR, TAB, so I can turn large collections of text in to actual word paragraphs. Except, I start my looking at the wrong index :-( Quick fix: Line 554 of docxvectorialwriter.pas needs to be changed to: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i           If i >= iStart Then     (it was previously i > iStart, so worked for strings with length > 1) Better fix: Mike remembers this time and supplies an actual patch, fixing both this and @JD's issue. ---------------------------------------------------------------------- Dean Qin · 2019-10-25 06:05 @Mike Thank you for your time & explaination, I use the fix you suggested and It works now (Single char without space) ---------------------------------------------------------------------- jjbazaar · 2024-04-30 16:36 Quote from: JD on April 17, 2019, 04:20:20 pmHere is the sample published project in case anyone has a similar problem. JD I know this is old but wanted to say thank you. I need this for a project I'm working on in a time crunch, as most of us do. FYI, as of this writing, the published example hasn't been updated as far as I can tell. 4/30/24. jjbazaar ---------------------------------------------------------------------- Mike.Cornflake · 2024-05-03 08:45 G'day, Thanks for the nudge.  Now 5 years on, and I still haven't fixed anything.  But I've now checked, and it looks like someone else has.  Whoever you are, many thanks :-) This is back: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i TtvTable.AddColWidth() This has been implemented Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   If i >= iStart Then   I tested with the Trunk version of Lazarus, so I don't know when the fixes were applied.  Err, and it's not called Trunk anymore, can't remember what git calls it, but either way - latest code. I then compiled: "B:\Apps\Dev\lazarus_trunk\lazarus\components\fpvecto rial\examples\fpvtextwritetest2\fpvtextwritetest2.lpi" Had to disable the pdf_test define at the top of fpvtextwritetest2.pas to bring in the table code.  But the code worked, and produced a Word Document with tables that I expected.  I then tried the SimpleTable code on the wiki:  https://wiki.freepascal.org/fpvectorial_-_Text_Document_Support That also worked.  Table didn't exactly match the screenshot, but close enough.  I suspect the differences are Word 365 x Word 2010 issue.  Looks like no updates are required on the wiki.  Phew :-) Many thanks to the community for maintaining this.