The knitr and rmarkdown packages are used in conjunction with pandoc to convert R code and figures to a variety of formats including PDF, and word. Here, I’m exploring how to convert HTML back to markdown format. This post came about when I was searching how to convert XML to markdown, which I still haven’t found an easy way to do. Pandoc is not the only way to convert HTML to markdown (see turndown, html2text)
Pandoc is packaged within RStudio and on Windows, the executables are located within Program Files/RStudio/bin/pandoc. The rmarkdown package contains wrapper functions for using pandoc within RStudio.
Here, I am trying to convert this example HTML page back to markdown using the function pandoc_convert. First, pandoc_convert requires an actual file which means it does not accept a quoted string of HTML code in its input argument.
The example html:
Enter a title, displayed at the top of the window.
Enter the main heading, usually the same as the title.
Be bold in stating your key points. Put them in a list: The first item in your list
The second item; italicize key words
Improve your image by including an image. Add a link to your favorite Web site.
Break up your page with a horizontal rule or two. Finally, link to another page in your own Web site.
© Wiley Publishing, 2011
I saved the HTML example here as example.html.
html_page Enter the main heading, usually the same as the title. Be bold in stating your key points. Put them in a list: The first item in your list The second item; italicize key words Improve your image by including an image. Add a link to your favorite Web site. Break up your page with a horizontal rule or two. Finally, link to another page in your own Web site. © Wiley Publishing, 2011 pandoc can convert between many different formats, and for markdown, it has multiple variants including the github flavored variant (for Github), and php markdown extra (the variant used by WordPress sites).
The safest variant to pick is markdown_strict which is the original markdown variant.
Pandoc requires the file path which in my case, is located in a different directory rather than my working directory.
library(rmarkdown)
file_path Lastly, this was tested using pandoc version 1.19.2.1. Pandoc 2.5 was released last month.