r - 如何使用 r 中的 media_extract 从单词中提取图像?
问题描述
我正在使用 rmarkdown 生成一份报告,该报告提取并显示从 word 中提取的图像。
为此,我使用了officer包。它有一个名为 media_extract 的函数,可以“从 rdocx 或 rpptx 对象中提取文件”。
总之,我正在努力寻找没有 media_path 列的图像。
media_path 用作 media_extract 函数中的参数来定位图像。请参阅下面的包文档中的示例代码:
example_pptx <- system.file(package = "officer",
"doc_examples/example.pptx")
doc <- read_pptx(example_pptx)
content <- pptx_summary(doc)
image_row <- content[content$content_type %in% "image", ]
media_file <- image_row$media_file
png_file <- tempfile(fileext = ".png")
media_extract(doc, path = media_file, target = png_file)
文件路径是使用任一生成的;docx_summary 或 pptx_summary,取决于文件类型,它们创建文件的数据框摘要。pptx_summary 包含一个 media_path 列,它显示图像的文件路径。docx_summary 数据框不包含此列。另一个stackoverflow帖子为此提出了一个使用 word/media/subdir 的解决方案,它似乎有效,但是我不确定这意味着什么或如何使用它?
如何使用 word/media/ subdir 作为媒体路径从 word doc 中提取图像?
解决方案
我继续研究这个并找到了答案,所以我想我会分享!
我从 docx 中提取图像的困难是由于media_file
摘要数据框中没有一列(使用 生成docx_summary
),该列用于定位所需的图像。此列存在于为 pptx 生成的数据框中,pptx_summary
并用于包文档中的示例代码。
在没有此列的情况下,您需要使用文档子目录(当 docx 为 XML 格式时的文件路径)来定位图像,如下所示:
media_path <- "/word/media/image3.png"
如果你想看看这个结构是什么样的,你可以右键单击你的文档>7-Zip>提取文件.. 将创建一个包含文档内容的文件夹,否则只需更改图像编号以选择所需的图像。注意:有时图像的名称不符合 image.png 格式,因此您可能需要提取文件以找到所需图像的名称。
将 media_extract 与 docx 一起使用的示例。
#extracting image from word doc using officer package
report <- read_docx("/Users/user.name/Documents/mydoc.docx")
png_file <- tempfile(fileext = ".png")
media_file <- "/word/media/image3.png"
media_extract(report, path = media_file, target = png_file)
您正在寻找的输出是TRUE
. 然后可以使用knitr
(或其他方法)将图像包含在报告中。
include_graphics(png_file)
推荐阅读
- python - 如何拆分文本文件中的文本块并将其保存到对象或列表中?
- javascript - 用于闭环的javascript
- android - 如何使 EditText 可以处理 14 KB 文本 (Kotlin)
- php - laravel voyager 只是保持加载并且不起作用
- c# - ItextSharp 不使用 c# 维护 pdf 中的列宽
- ruby-on-rails - 在其他控制器中使用设计时没有响应
- amazon-web-services - Python 代码在 AWS EC2 G4 实例上自动终止
- javascript - 从另一个函数括号传递变量
- php - 如何加入“IN”结果并检查“where” active = 1?
- api - CodeIgniter,在 $this- 响应之后调用另一个函数