Add styling rules in pandoc tables for odt/docx output (table borders)

前端 未结 6 1536
一整个雨季
一整个雨季 2020-12-24 02:42

I\'m generating some odt/docx reports via markdown using knitr and pandoc and am now wondering how you\'d go about formating tables. Primarily I\'m interested in adding rule

6条回答
  •  长情又很酷
    2020-12-24 03:19

    Same suggestion as edi9999: hack the xml content of converted docx. And the following is my R code for doing that.

    The tblPr variable contains the definition of style to be added to the tables in docx. You could modify the string to satisfy your own need.

    require(XML)
    
    docx.file <- "report.docx"
    tblPr <- ''
    
    ## unzip the docx converted by Pandoc
    system(paste("unzip", docx.file, "-d temp_dir"))
    document.xml <- "temp_dir/word/document.xml"
    
    doc <- xmlParse(document.xml)
    tbl <- getNodeSet(xmlRoot(doc), "//w:tbl")
    tblPr.node <- lapply(1:length(tbl), function (i)
                       xmlRoot(xmlParse(tblPr)))
    added.Pr <- names(xmlChildren(tblPr.node[[1]]))
    for (i in 1:length(tbl)) {
        tbl.node <- tbl[[i]]
        if ('tblPr' %in% names(xmlChildren(tbl.node))) {
            children.Pr <- xmlChildren(xmlChildren(tbl.node)$tblPr)
            for (j in length(added.Pr):1) {
                if (added.Pr[j] %in% names(children.Pr)) {
                    replaceNodes(children.Pr[[added.Pr[j]]],
                                 xmlChildren(tblPr.node[[i]])[[added.Pr[j]]])
                } else {
                    ## first.child <- children.Pr[[1]]
                    addSibling(children.Pr[['tblStyle']],
                               xmlChildren(tblPr.node[[i]])[[added.Pr[j]]],
                               after=TRUE)
                }
            }
        } else {
            addSibling(xmlChildren(tbl.node)[[1]], tblPr.node[[i]], after=FALSE)
        }
    }
    
    ## save hacked xml back to docx
    saveXML(doc, document.xml, indent = F)
    setwd("temp_dir")
    system(paste("zip -r ../", docx.file, " *", sep=""))
    setwd("..")
    system("rm -fr temp_dir")
    

提交回复
热议问题