我正在Rmarkdown中生成对象列表,并将它们放入txt文件中,然后从文件中读取内容以编织PDF。但是,当前我只能插入\n
,而不能插入分页符。如果有5张表(每页1张表),我想生成5页的PDF,但是我尝试了\pagebreak
,但是不起作用。有什么建议吗?
以下是我的代码。假设您可以直接在markdown文件中使用和编辑它。
---
title: "My_RMarkdown_Document"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE, comment = NA)
```
```{r txt file, include=FALSE}
if(file.exists('./output.txt'))
file.remove('./output.txt')
obj_filepath <- file.path('./output.txt')
```
```{r, include=FALSE}
for(f in 1:5){
context <- "I am generating a list of tables in Rmarkdown \nand put them into a txt file, \nand then read content from the file to knit a PDF. \nHowever, \ncurrently I can only insert \\\\n but not page break. \nI want to generate a PDF with 5 pages if there are 5 tables (1 table/page), \nI tried \\\\pagebreak but doesn't work. \nAny suggestions? \nMany thanks."
cat(toString(context), file = obj_filepath, append = TRUE)
cat(toString('\n'), file = obj_filepath, append = TRUE)
cat(toString('\n'), file = obj_filepath, append = TRUE)
}
cat(toString('\n'), file = obj_filepath, append = TRUE)
tools::md5sum(normalizePath(obj_filepath))
```
```{r output, include=TRUE}
str_tbl <- readLines(obj_filepath)
cat(str_tbl, sep = '\n')
```
答案 0 :(得分:1)
我认为有两件事要做。首先,为了包括RMarkdown可以正确解释的逐字LaTeX代码,您需要设置knitr块选项results='asis'
。
```{r output, include=TRUE, results='asis'}
str_tbl <- readLines(obj_filepath)
cat(str_tbl, sep = '\n')
```
完成此操作后,字符串"\\pagebreak"
将被正确解释为LaTeX命令。因此,以下代码将成功创建分页符。
cat('\n', file = obj_filepath, append = TRUE)
cat('\n', file = obj_filepath, append = TRUE)
cat("\\pagebreak", file = obj_filepath, append = TRUE)
cat('\n', file = obj_filepath, append = TRUE)
这是完整的文档:
---
title: "My_RMarkdown_Document"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE, comment = NA)
```
```{r txt file, include=FALSE}
if(file.exists('./output.txt'))
file.remove('./output.txt')
obj_filepath <- file.path('./output.txt')
```
```{r, include=FALSE}
for(f in 1:5){
context <- "I am generating a list of tables in Rmarkdown \nand put them into a txt file, \nand then read content from the file to knit a PDF. \nHowever, \ncurrently I can only insert \\\\n but not page break. \nI want to generate a PDF with 5 pages if there are 5 tables (1 table/page), \nI tried \\\\pagebreak but doesn't work. \nAny suggestions? \nMany thanks."
cat(context, file = obj_filepath, append = TRUE)
cat("\n", file = obj_filepath, append = TRUE)
cat("\n", file = obj_filepath, append = TRUE)
cat("\\pagebreak", file = obj_filepath, append = TRUE)
cat("\n", file = obj_filepath, append = TRUE)
}
cat('\n', file = obj_filepath, append = TRUE)
tools::md5sum(normalizePath(obj_filepath))
```
```{r output, include=TRUE, results='asis'}
str_tbl <- readLines(obj_filepath)
cat(str_tbl, sep = '\n')
```
答案 1 :(得分:0)
是否更改\f
代替您的\n
之一来创建分页符?
它似乎可以在我的系统上运行