向PowerPoint添加包含图片的flextable的替代方案问询
Yep, you're absolutely correct about the current limitation where plot_chunk elements in flextable don't get included when exporting directly to PPTX via print(ft, preview = "pptx"). And your idea of converting the flextable to an image first is a perfect workaround—especially since you prefer the non-editable output anyway.
Here's how to make this work, using your example code as a base:
Step 1: Install Required Package
First, you'll need the webshot2 package to convert the flextable to an image. If you don't have it installed yet:
install.packages("webshot2") # You might also need to install PhantomJS if prompted; webshot2 usually handles this automatically webshot2::install_phantomjs()
Step 2: Modified Code to Export as Image + Insert into PPTX
We'll convert the flextable to a temporary PNG file, then use officer to add that image to a new PPTX document:
library(flextable) library(data.table) library(officer) library(dplyr) library(webshot2) # Your original data and flextable creation code z <- as.data.table(ggplot2::diamonds) z <- z[, list( price = mean(price, na.rm = TRUE), list_col = list(.SD$x) ), by = "cut"] ft <- flextable(data = z) %>% compose(j = "list_col", value = as_paragraph( plot_chunk(value = list_col, type = "dens", col = "pink", width = 1.5, height = .4, free_scale = TRUE) )) %>% colformat_double(big.mark = " ", suffix = " $") %>% set_header_labels(list_col = "density") %>% autofit() # Convert flextable to a temporary high-resolution image temp_img <- tempfile(fileext = ".png") save_as_image(ft, path = temp_img, zoom = 2) # Zoom=2 ensures crisp output in PPTX # Create a new PPTX and insert the image pptx_doc <- read_pptx() %>% add_slide(layout = "Title and Content", master = "Office Theme") %>% ph_with( value = external_img(temp_img, width = 8, height = 3), location = ph_location_type(type = "body") ) # Save the final PPTX file print(pptx_doc, target = "flextable_with_density_plots.pptx") # Optional: Clean up the temporary image file file.remove(temp_img)
Key Notes:
save_as_imageworks withwebshot2to render the full table (including embedded density plots) as a high-quality image. Thezoom = 2parameter prevents pixelation when the image is displayed in the PPTX.- Use
external_imgto load the temporary image, thenph_withto place it on a slide. Adjust thewidthandheightvalues to fit your slide layout needs. - The temporary image file is automatically cleaned up (or you can explicitly remove it with
file.removeif you want).
This method ensures all your plot chunks are preserved in the final PPTX, and since it's an image, you get the non-editable output you prefer.
内容的提问来源于stack exchange,提问作者Swyler

