I am using pagedown::chrome_print() to convert slidy presentations created with Rmarkdown to pdf -- it does a better job than saving as PDF from Chrome. However, despite studying the help file, I cannot figure out how to add page numbers. Is there a way to do this?
(Note that pagedown here refers to the R package, not the JavaScript markdown previewer.)
Sorry if the help page is not clear on this point.
It is possible to pass header/footer options to Chrome using pagedown::chrome_print().
These options are the ones defined by the Chrome DevTools Protocol for the Page.printToPDF method.
You can customise the header and the footer with an HTML template. Chrome also offers the following values: date, title, url, pageNumber and totalPages.
Following the explanations on this help page, here is an example to print the page numbers:
library(htmltools)
footer <- div(
style = "font-size: 8pt; text-align: right; width: 100%; padding-right: 12pt;",
span(class = "pageNumber"), "/", span(class = "totalPages")
)
pagedown::chrome_print(
"slidy.Rmd",
options = list(
landscape = TRUE,
displayHeaderFooter = TRUE,
footerTemplate = format(footer, indent = FALSE),
marginTop = 0,
marginBottom = 0.4
)
)
I got it to work with a custom CSS file. I created a file called custom.css and included in that file was
#page {
#bottom-right {
content: counter(page);
}
}
Then I used that along with the other pagedown defaults with a header like this
title: "My Report"
output:
pagedown::html_paged:
css: ["custom.css", "default-fonts", "default"]
Related
When using a theme for an html output, such as LUX, and creating tables with DT's datatable function, the theme stylizes the output tables, including capitalizing the column names.
Here is the Yaml
---
title: "Untitled"
format: html
editor: visual
theme: LUX
---
And here is an example
library(DT)
datatable(head(iris), extensions = 'Buttons', caption = "Companies Summary",options=list(
dom = 'Bfrtip',
buttons = c('csv', 'excel'),
initComplete = JS(
"function(settings, json) {",
"$(this.api().table().container()).css({'font-size': '70%'});","}")))
column names capitalized, corresponding to the html theme
In the example above, the font changes according to the theme, however the font size and the buttons size in the whole table and everything around it are responding to the command
table().container()).css({'font-size': '70%'})
except for the column names which are behaving according to the theme.
The ideal look I am looking for is to simply prevent the theme from stylizing the tables produced by datatables. or at least control the specific behavior of the theme and prevent it from styling the column names:
column names unchanged, no theme in the yaml
I tried controlling headers with
table().header()).css({'font-size': '70%'})
but the problem remains.
I am sure it will come down to customizing the theme, however, I don't know html and css. Any help is appreciated.
A possible solution to the problem could be using a custom.scss to overwrite the CSS property defined by the theme.
---
title: "Untitled"
format: html
theme: [lux, custom.scss]
---
```{r}
library(DT)
datatable(head(iris), extensions = 'Buttons', caption = "Companies Summary",options=list(
dom = 'Bfrtip',
buttons = c('csv', 'excel'),
initComplete = JS(
"function(settings, json) {",
"$(this.api().table().container()).css({'font-size': '70%'});",
"}")))
```
custom.scss
/*-- scss:rules --*/
table.dataTable th {
text-transform: unset;
}
I would like to have a download button in the middle of a sentence to a pdf or csv document for example. This means there should be a small button in the sentence suggesting that you can download a document, not in a navigation or side bar. Here is some reproducible code:
---
title: "Download button in text Quarto"
format:
html:
code-fold: true
engine: knitr
---
I would like to have a download button [here]() for pdf or CSV document for example.
I am not sure if it is possible to implement a clean button in a sentence using downloadthis package because it should be in the middle of a sentence with text around.
Update
I have create quarto shortcode extension downloadthis that provides a shortcode to embed a download button more easily (in comparison to my old answer) and doesn't require to use an R package (but of course, this extension is inspired by {downloadthis})
So after installing that shortcode, we can use the shortcode as following,
---
title: "Download button in text Quarto"
format:
html:
css: style.css
engine: knitr
---
The following button is a download button for matcars data {{< downloadthis mtcars.csv
label="Download data" dname=mtcars id=mtcars-btn >}} You can download the mtcars data as csv file by clicking on it.
style.css
#mtcars-btn {
font-size: xx-small;
padding: 0.2rem 0.3rem !important;
}
#down-btn {
margin-right: 2px;
margin-left: 2px;
}
a:has(#mtcars-btn) {
text-decoration: none !important;
}
Explore here for more options and live demos.
Old Answer
Using a bit of CSS and javascript, it is possible to do very easily.
---
title: "Download button in text Quarto"
format:
html:
code-fold: true
include-after-body: add_button.html
engine: knitr
---
```{r}
#| echo: false
library(downloadthis)
mtcars %>%
download_this(
output_name = "mtcars dataset",
output_extension = ".csv",
button_label = "Download data",
button_type = "default",
self_contained = TRUE,
has_icon = TRUE,
icon = "fa fa-save",
id = "mtcars-btn"
)
```
The following button is a download button for matcars data <span id="down-btn"></span> You can download the mtcars data as csv file by clicking on it.
add_button.html
<style>
#mtcars-btn {
font-size: xx-small;
padding: 0.2rem 0.3rem !important;
}
#down-btn {
margin-right: 2px;
margin-left: 2px;
}
a:has(#mtcars-btn) {
text-decoration: none !important;
}
#mtcars-btn:focus,
#mtcars-btn:active {
box-shadow: none !important;
}
#mtcars-btn:hover {
transition: 0.2s;
filter: brightness(0.90);
}
#mtcars-btn:active {
filter: brightness(0.80);
}
</style>
<script>
function add_button() {
/* get the R generated button by its id */
let mtcars_btn = document.querySelector("a:has(#mtcars-btn)");
mtcars_btn.href = '#mtcars-btn';
/* get the placeholder where you want to put this button */
let down_btn = document.querySelector("span#down-btn");
/* append the R generated button to the placeholder*/
down_btn.appendChild(mtcars_btn)
}
window.onload = add_button();
</script>
Explanation
So what I have done here
At first, created a download button using the downloadthis with an id=mtcars-btn so that we can get hold of this generated button with js code using this #mtcars-btn id selector
Then created a placeholder inside the paragraph text using <span></span>, where I want the download button to be and also in this case, assigned an id down-btn to that span, so that we can target this span using #down-btn.
Then using js, simply appended that generated download button to placeholder span tag so that the button is in the place where we wanted it to be.
Lastly, used some css to make this button smaller, reduced button padding, created a bit left and right margin and removed the underline.
Thats it!
I am making a book via bookdown.
I know it is possible to omit headings from the Table of Contents by adding the attributes {.unlisted .unnumbered}, as shown in Section 4.18 of the R Markdown Cookbook.
However, how can I add arbitrary content to the Table of Contents?
If I only needed to add this for the PDF output, I could use (e.g.) the LaTeX command \addcontentsline, but I need this to show in the HTML contents sidebar as well.
For example, if you set up a new default bookdown project from RStudio, it includes the file 01-intro.Rmd.
The first few lines are
# Introduction {#intro}
You can label chapter and section titles using `{#label}` after them, e.g., we can reference Chapter \#ref(intro). If you do not manually label them, there will be automatic labels anyway, e.g., Chapter \#ref(methods).
Figures and tables with captions will be placed in `figure` and `table` environments, respectively.
I need to be able to create arbitrary divs that are added to the table of contents, like so:
# Introduction {#intro}
You can label chapter and section titles using `{#label}` after them, e.g., we can reference Chapter \#ref(intro). If you do not manually label them, there will be automatic labels anyway, e.g., Chapter \#ref(methods).
::: {#arbitrary-header <some other attribute?>}
Figures and tables with captions will be placed in `figure` and `table` environments, respectively.
:::
Which would add the sentence "Figures and tables with captions will be placed in figure and table environments, respectively." in both the LaTeX Table of Contents and the sidebar on the HTML output.
The context of this problem is that I need to place a header inside another custom div that formats the content within a colorbox to make it stand out.
Otherwise, I could of course just add another heading via ## before the sentence above.
We could use an R function that prints a colored box and adds the title to the TOC depending on the output format. For gitbook output, this is easily done using HTML and markdown. For pdf_book we may use a LaTeX environment for colored boxes like tcolorbox.
Here is the function (define in a code block in .Rmd file):
block_toc <- function(title, level, content, output) {
if(output == "html") {
title <- paste(paste(rep("#", level), collapse = ""), title, "{-}")
cat('<div class = "myblock">', title, '<p>', content, '</p>\n</div>', sep = "\n")
} else {
level <- c("part", "chapter", "section")[level]
cat('\\addcontentsline{toc}{', level, '}{', title, '}',
'\n\\begin{mybox}\n\\textbf{\\noindent ', title, '}\n\\medskip\n\n', content,
'\n\n\\end{mybox}', sep = "")
}
}
Depending on the output format, block_toc() concatenates and prints the code for the blocks and, of course, also ensures that the title is added to the TOC. You can set the level of the TOC where the box title is added using level.
Use block_toc() like this in a chunk:
```{r, results='asis', echo=F, eval=T}
block_toc(
title = "Central Limit Theorem",
level = 2
content = "The CLT states that, as $n$ goes to infinity,
the sample average $\\bar{X}$ converges in distribution
to $\\mathcal{N}(\\mu,\\sigma^2/n)$.",
output = knitr::opts_knit$get("rmarkdown.pandoc.to")
)
```
output = knitr::opts_knit$get("rmarkdown.pandoc.to") will get and pass the current output format to the function when building the book.
Some styles for appealing boxes
Add to preamble.tex (for colored box in PDF output -- include file in YAML header). This will define a tcolorbox environment for generating blue boxes.
\usepackage{tcolorbox}
\definecolor{blue}{HTML}{D7DDEF}
\definecolor{darkblue}{HTML}{2B4E70}
\newtcolorbox{mybox}{colback=blue, colframe=darkblue}
Add to style.css (styles for HTML colored box) or include in a ```{css} code chunk:
.myblock {
background-color: #d7ddef;
border: solid #2b4e70;
border-radius: 15px;
}
.myblock p, .myblock h2, .myblock h3 {
padding: 5px 5px 5px 20px;
margin-top: 0px !important;
}
For HTML output (gitbook) this yields
and for LaTeX output (pdf_book) it looks like this
with a corresponding entry at the section level in the TOC.
Maybe this solution?
CSS-file:
k1 {
font-family: 'Times New Roman', Times, serif;
font-size: 12pt;
text-align: justify;
}
#TOC {
color:black;
background-color: white;
position: fixed;
top: 0;
left: 0;
width: 250px;
padding: 10px;
overflow:auto;
margin-left: -5px;
}
body {
max-width: 800px;
margin-left:300px;
line-height: 20px;
}
div#TOC li {
list-style:none;
}
h2#toc-title {
font-size: 24px;
color: Red;
}
Rmd-file:
---
title: "Arbitrary elements"
author: "Me"
date: "`r Sys.Date()`"
output:
bookdown::html_document2:
toc: true
css: "arb.css"
toc-title: "Contents"
---
# My question is it: "..."
# Introduction of our story ...
# It was a strange person ...
## The Flame was in his body ...
# <k1> Figures and tables with captions will be placed in `figure` and `table` environments, respectively. </k1> {-}
## Where is the love, friends?
We'll be using a Lua filter for this, as those are a good way to modify R Markdown behavior. The "Bookdown Cookbook" has an excellent overview and includes a description of how to use Lua filters.
The way we are doing this is to side-step the normal TOC generator and rewrite it in Lua. Then we add our new TOC as a meta value named table-of-contents (and toc, for compatibility), which is enough to be included in the output.
So first let's dump the code to create a normal TOC:
_ENV = pandoc
local not_empty = function (x) return #x > 0 end
local section_to_toc_item
local function to_toc_item (number, text, id, subcontents)
if number then
text = Span({Str(number),Space()} .. text, {class='toc-section-number'})
end
local header_link = id == '' and text or Link(text, '#' .. id)
local subitems = subcontents:map(section_to_toc_item):filter(not_empty)
return List{Plain{header_link}} ..
(#subitems == 0 and {} or {BulletList(subitems)})
end
section_to_toc_item = function (div)
-- bail if this is not a section wrapper
if div.t ~= 'Div' or not div.content[1] or div.content[1].t ~= 'Header' then
return {}
end
local heading = div.content:remove(1)
local number = heading.attributes.number
-- bail if this is not supposed to be included in the toc
if not number and heading.classes:includes 'unlisted' then
return {}
end
return to_toc_item(number, heading.content, div.identifier, div.content)
end
-- return filter
return {
{ Pandoc = function (doc)
local sections = utils.make_sections(true, nil, doc.blocks)
local toc_items = sections:map(section_to_toc_item):filter(not_empty)
doc.meta['table-of-contents'] = {BulletList(toc_items)}
doc.meta.toc = doc.meta['table-of-contents']
return doc
end
},
}
The code makes a few minor simplifications, but should produce an identical TOC for most documents. Now we can go on and modify the code to our liking. For example, to include divs with the class toc-line, the section_to_toc_item could be modified by adding this code at the start of the function:
section_to_toc_item = function (div)
if div.t == 'Div' and div.classes:includes('toc-line') then
return to_toc_item(nil, utils.blocks_to_inlines(div.content), div.identifier)
end
⋮
end
Modify the code as you see fit.
Also, if you want to exclude the extra TOC lines from the normal output, you'll have to filter them out. Let the script return a second filter to do that:
return {
{ Pandoc = function (doc) ... end },
{ Div = function (div) return div.classes:includes 'toc-line' and {} or nil end }
}
I am using rmarkdown to generate an HTML report. I am on a restricted machine, can't install tex. So, I was trying to generate an HTML document and then convert/print it to a pdf. The example markdown document is:
---
title: "trials"
author: "Foo Bar"
date: "15 December 2016"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r cars, echo=FALSE, cache=FALSE, message=FALSE}
library(dplyr, quietly = TRUE)
library(abind, quietly = TRUE)
virginica <- iris %>% filter(Species == "virginica") %>% head() %>% select(-Species)
setosa <- iris %>% filter(Species == "setosa") %>% head() %>% select(-Species)
diff_mat <- virginica - setosa
diff_mat[diff_mat<0] <- '<font color="green">⇓ </font>'
diff_mat[diff_mat>0] <- '<font color="red">⇑ </font>'
diff_mat[diff_mat == 0] <- '<font color="blue">⇔ </font>'
datArray <- abind::abind(virginica, diff_mat, along=3)
fin_dat <- apply(datArray,1:2, function(x)paste(x[1],x[2], sep = " "))
knitr::kable(fin_dat, format = "html",
escape = FALSE, table.attr = "border=1",
caption = "Changes across species")
```
I can't knit to word either as the formatting is lost as discussed in HTML formatted tables in rmarkdown word document. The HTML produced is exactly what I wanted. HTML to word using save as in word works mostly fine with some issues and I can print pdf but it is not as good as directly printed from pdf.
when I try to save it as pdf in chrome the colour is lost.
There is no issues in print options
Other pages such as this question in our beloved site Replace NA's using data from Multiple Columns prints fine
Do you have any pointers where I am missing a point or where the issue is.
Add this right after the YAML header:
<style>
#media print {
font[color="green"] {
color: #00ff00!important;
-webkit-print-color-adjust:exact;
}
font[color="red"] {
color: #ff0000!important;
-webkit-print-color-adjust:exact;
}
}
</style>
The problem is that RStudio's default R markdown templates use Bootstrap and their version of bootstrap.min.css has:
#media print {
*,
*:before,
*:after {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
in it. That's a pretty "destructive" media query as the *'s cause those settings to be applied to all tags and color: #000 !important; means "no color for YOU!" when you print a document. I grok the sentiment behind that (saving the planet + toner/ink costs) but if you're printing to PDF it makes no sense whatsoever.
Unfortunately, there are no hyper-targeted media queries for printing to PDF, so the generic "print" ones get applied when you print web pages to PDFs and these mindless, catch-all media queries take over.
The problem for you is that you'll need to be very specific in targeting any other tags to override these settings. Which means adding your own CSS classes to anything you generate in Rmds or getting cozy with "Inspect Element" until you catch'em all.
However, if you're feeling adventurous you can modify the YAML header to be:
output:
html_document:
self_contained: false
When you render to HTML it'll create a directory with subdirectories for the various components vs base64-encode them into one big document.
I named my document forso.Rmd which means it made a directory called forso_files and put subdirs under it.
Open up the main HTML file and scroll down until you see something like:
<script src="forso_files/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="forso_files/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="forso_files/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="forso_files/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="forso_files/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="forso_files/navigation-1.1/tabsets.js"></script>
Change this:
<link href="forso_files/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
to:
<link href="forso_files/bootstrap-3.3.5/css/bootstrap.css" rel="stylesheet" />
Edit bootstrap.css, remove the color: #000 !important; line and add the -webkit-print-color-adjust:exact; line. SAVE A COPY OF bootstrap.css ELSEWHERE as it'll get squashed on future renders (i.e. you'll need to copy it back on every render).
You can't just link to a separate CSS file with a less brain dead print media query since the color: #000 !important; impacts all tags thanks to the * target and you can't just reset it to initial or inherit` because that will just turn them black as well.
Your final (and probably best) option is to make your own R Markdown template (see https://github.com/hrbrmstr/markdowntemplates for more info) and avoid placing over-arching print media queries in it.
I want to customize the classes in Google Charts.
As far as I'm concerned, there are two options that I've stumbled upon. The first option is:
Just inspect the elements in the browser, to see what the name of the classes is, then just give them new rules in the css file. In some cases I've to set !important; to override the rule. This option seems very "ugly", because forcing the class to have an !important; state is just ugly.
.charts-menu-button,
.charts-menu-button-inner-box {
width: 200px;
line-height: 55px;
border: 0 !important;
padding: 0 !important;
}
This is my second option which I'm pretty confused over. As I read the Google Chart docs, they suggest to call the "cssClass", like this:
options: {
ui: {
cssClass: {}
}
}
What I don't understand is when I'm going with the second option, absolute nothing happens to the class I want to customize.
So my question is: What am I doing wrong here, and is there any other way?
Set the cssclassnames in options for the chart as below. Define the classes in the css file. Below example is for table chart.
chart1.options = {
// title: "User Chart",
displayExactValues: true,
'showRowNumber': false,
'allowHtml': true,
is3D: true,
// 'height' : '350px',
cssClassNames : {
headerRow :'tableChartHeaderRow',
hoverTableRow : 'tableChartHeaderRowHighlightedState'
}
};