Search code examples
rflextableofficer

Alignment/fitting of a flextable to page width in R


I'm creating a pretty basic report adding small tables to a docx in a loop. I'd like to fit them to the width of the page or at least align the table (not cells' content) to the left. It should be quite an easy task but I found only references related to:

  • alignment of cell content (package manual)
  • docs built in Rmarkdown (1,2)

I tried the solutions suggested in the references but they did not work. Here what I'm using (commented rows to show other attempts):

  tbl.params = flextable(fdata) %>%
    delete_part(part = "header") %>%
    #autofit() %>%
    border_remove() %>%
    border_inner_h(part="body", border = small_border ) %>%
    hline_top( border = big_border, part="body") %>%
    bold(j=1) %>%
    set_table_properties(layout = "autofit")
    #fit_to_width(7.5)

Am I making a mistake or missing something? I'm looking for solutions in "pure" Officer (if available).


Solution

  • The following script add a flextable in a docx document. The column withs are adjusted by Word and the table is left aligned:

    library(officer)
    library(flextable)
    
    ftab <- flextable( head( mtcars ) )
    ftab <- set_table_properties(ftab, layout = "autofit")
    doc <- read_docx()
    doc <- body_add_flextable(doc, value = ftab, align = "left")
    print(doc, target = "fileout.docx")
    

    enter image description here