flextable autofit in a Rmarkdown to word doc causes table to go outside page margins

I have written a function to fit the table to the page which works well for now, although I'm still a bit surprised that there is no built in function to do this which would (for example) know the width of the page itself, so if any one knows any still keen to hear.

FitFlextableToPage <- function(ft, pgwidth = 6){

  ft_out <- ft %>% autofit()

  ft_out <- width(ft_out, width = dim(ft_out)$widths*pgwidth /(flextable_dim(ft_out)$widths))
  return(ft_out)
}

FYI - I ran into this same problem today and used your code (thank you). But it still was bothering me because I couldn't get it quite right. I noticed on the Officedown package website (same author; https://github.com/davidgohel/officedown) they used set_table_properties(layout = "autofit") so I tried that. For whatever reason it worked as expected when doing that! I also was using officedown with default settings, so maybe the two worked well together.


I had a similar issue using the autofit() function. When I add the function fit_to_width() to the end of the pipe, it solves the issue.

Using part of your example from above, the following line of code would autofit the columns, then resize to fit the max table width in inches given as the second argument (here I am going for 1/2 inch doc margins):


mytable %>% autofit() %>% fit_to_width(7.5)

One caveat of this is that for some of my tables, adding the fit_to_width() function slowed the rendering process considerably. For those tables, I used @bumbledore's suggested set_table_properties(layout = "autofit") and it worked great (and for the record, I am also using officedown with default settings).