How to use an r object inside an html chunk in rmarkdown - html

I would like to insert a png "logo.png" inside my rMarkdown report. The current solution is working only when the png is in the root directory of the html report. However, when I send the report to someone, the missing png is an issue, since the person has only the html without the accompanied logo.
My idea is to read and to save the png beforehand and then to insert this r object in the html code chunk. However, I am having issues with this approach. Any help or other ideas are very much appreciated!
<script>
$(document).ready(function() {
$head = $('#header');
$head.prepend('<img src=\"logo.png\" style=\"float: right; width: 300px; padding-top: 20px; padding-left: 35px\"/>')
});
</script>

You can use an R chunk to import the png
```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("logo.png")
```
Example taken from this closed question

Related

How to make html file import html code from another file (without JS)? [duplicate]

(First ask here so thanks in advance for the help!)
Is there a way to import html from another file to act as templates? Similar to calling a function.
The main reason is to simplify any changes made to the website as a whole; for example changing the header navigation menu would affect the entire website's design.
HTML has no features built-in to do that. The closest it gets are <iframe> elements which load a separate document into an embedded viewport.
This problem is generally best solved by combining your reused components before the HTML gets to the browser.
This could be done using some form of server-side programming (such as SSI, a PHP include, or a template language) or at build-time (typically using a static site generator).
You can start using Custom Elements, but there is lack of support in Opera and Safari. It looks overwhelming at first, and you need javascript experience, but it's pretty smooth once you get hang of it.
You can also use frameworks like Vue, React, Angular and Polymer that takes Custom Elements a step further.
I think the closest thing would be having html code surrounded with <template> tags and later executing Javascript code which generates final HTML document according to that template. Something like :
<!DOCTYPE html>
<html>
<body>
<style>
.myClass {
color: white;
background-color: DodgerBlue;
padding: 5px;
text-align: center;
margin: 10px;
}
</style>
<h2>The template demo</h2>
<button onclick="showContent()">Generate document</button>
<template>
<div class="myClass">I like: </div>
</template>
<script>
var myArr = ["Audi", "BMW", "Ford", "Honda", "Jaguar", "Nissan"];
function showContent() {
var temp, item, a, i;
temp = document.getElementsByTagName("template")[0];
item = temp.content.querySelector("div");
for (i = 0; i < myArr.length; i++) {
a = document.importNode(item, true);
a.textContent += myArr[i];
document.body.appendChild(a);
}
}
</script>
</body>
</html>

pdfHTML with in-memory CSS

I'm trying out iText7 and trying to piece together how to do things. It seems that I can put in a base URI to grab external resources which I'm assuming if it finds a .css it will apply that? I have a particular situation where it's easier for me to hold the CSS in memory as a string. It seems odd that I can use HtmlConverter.convertToPdf() and pass in HTML as a string but not CSS.
As a secondary question, what happens if it finds multiple CSS files at that base URI?
Finally (sorry for the dump), if the HTML contains FQDN URLs to images, I'm assuming/hoping it will pull the images directly? In other words, I'm hoping I don't also have to store/write those images to the specified base URI?
Thanks.
UPDATE: I put together a quick demo. I found out it will download images that have a full URL which is great.
However, it does not seem to be loading the CSS file that is in a folder I specified. The code:
StringBuilder sb = new StringBuilder(File.ReadAllText("demoHtml.html"));
// this folder, which is relative to the test .exe, contains a file called pdf.css
ConverterProperties props = new ConverterProperties().SetBaseUri("Content/Pdf");
FileStream fs = new FileStream("itext.pdf", FileMode.Create);
HtmlConverter.ConvertToPdf(sb.ToString(), fs, props);
And the CSS:
img {
max-width: 100%;
}
table {
vertical-align: top;
}
td ol {
-webkit-padding-start: 15px;
padding-left: 15px;
}
thead tr {
background: #aaa;
}
tr:nth-child(even) {
background: #eee;
}
Solution to question 1:
I'm trying out iText7 and trying to piece together how to do things. It seems that I can put in a base URI to grab external resources which I'm assuming if it finds a .css it will apply that? I have a particular situation where it's easier for me to hold the CSS in memory as a string. It seems odd that I can use HtmlConverter.convertToPdf() and pass in HTML as a string but not CSS.
Many hours i have spent finding the slution for this problem. Everything seemed right and i even asked a support question about the using of CSS files. In contrary to itext5 (itextsharp), itext7 can't manage an url with a space in it.
So locally testing in a path like this: c:/Path to project/project/name/wwwroot/ won't work (note the spaces)
I didn't notice this at first because i generated my path programmatically to my css folder:
var basepath = env.ContentRootPath + "\\wwwroot\\pdfcss\\";
Changed it to:
var basepath = #"G:\some-other\directory\pdfcss\";
Solution to question 2:
Now knowing this i could solve your second question:
As a secondary question, what happens if it finds multiple CSS files at that base URI?
Nothing, you will still have to insert the links into your html in the head element. If this isn't added you will not have any css!
Solution to question 3:
And indeed:
Finally (sorry for the dump), if the HTML contains FQDN URLs to images, I'm assuming/hoping it will pull the images directly? In other words, I'm hoping I don't also have to store/write those images to the specified base URI?
You can do the following:
<img id="logo"
src="https://xxxxx.blob.core.windows.net/path/to-image-
logo.png" />

How to reduce shiny interactive rmarkdown margins?

Is there any way to reduce the right and left margins when shiny-server sees an .Rmd file instead of ui.R and server.R? As you can see below, nearly half of the window is right and left margins. Is there a way to modify an internal css script to make the change or is there a more simple solution by adding an geometry option in the markdown header?
Here is the sample code generated when I create a new Shiny Rmarkdown file in Rstudio:
---
title: "Untitled"
author: "Me"
date: "10/13/2015"
output: html_document
runtime: shiny
---
This R Markdown document is made interactive using Shiny. Unlike the more traditional workflow of creating static reports, you can now create documents that allow your readers to change the assumptions underlying your analysis and see the results immediately.
To learn more, see [Interative Documents](http://rmarkdown.rstudio.com/authoring_shiny.html).
## Inputs and Outputs
You can embed Shiny inputs and outputs in your document. Outputs are automatically updated whenever inputs change. This demonstrates how a standard R plot can be made interactive by wrapping it in the Shiny `renderPlot` function. The `selectInput` and `sliderInput` functions create the input widgets used to drive the plot.
```{r, echo=FALSE}
inputPanel(
selectInput("n_breaks", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust)
lines(dens, col = "blue")
})
```
## Embedded Application
It's also possible to embed an entire Shiny application within an R Markdown document using the `shinyAppDir` function. This example embeds a Shiny application located in another directory:
```{r, echo=FALSE}
shinyAppDir(
system.file("examples/06_tabsets", package="shiny"),
options=list(
width="100%", height=550
)
)
```
Note the use of the `height` parameter to determine how much vertical space the embedded application should occupy.
You can also use the `shinyApp` function to define an application inline rather then in an external directory.
In all of R code chunks above the `echo = FALSE` attribute is used. This is to prevent the R code within the chunk from rendering in the document alongside the Shiny components.
After looking at the HTML produced by an Rmd file, it looks like the main content is under a div with class main-content and it has a max-width property. Looking at the rmarkdown source code, I believe that perhaps this happens here. Try adding a css rule like div.main-container { max-width: inherit; }
The above CSS change did not work for me, as I am having the same issue rendering HTML from Rmd in RStudio, but this did work. Added after YAML in Rmd:
<style>
.main-container {
max-width: 940px;
margin-left: 0;
margin-right: auto;
}
</style>

How to change dimensions of rChart Iframe in html using RMarkdown?

I am trying to incorporate rchart based on nvd3 library in my html documentation generated by RMarkdown. But I am unable to adjust the height of the resulting iframe in my html document.
As a result of that only half of my plot is visible. is there any solution for this problem using R?. I don't know any html or css. Here is my code chunk producing the plot.
```{r, echo=FALSE,results='asis',comment=NA}
library(rCharts)
hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = "Eye", data = hair_eye_male, type = "multiBarChart")
n1$show("iframesrc",cdn=TRUE)
```
I even tried opening the html file in text editor and editing the width and height options of Iframe in vain.

Custom html with download data button in Shiny

I'm wondering how to make the Shiny downloadHandler work with a custom html UI.
In my index.html I have the following:
<a id="downloadproject" class="shiny-download-link shiny-bound-output">export</a>
And in the server.R I have:
output$downloadproject <- downloadHandler(
filename = "test.csv",
content = function(file) {
test_data <- c(1,2,3,4,5,6,7)
write.csv(test_data, file)
}
)
However, I can't get it working. I've noticed inspecting the source on the demo page: http://shiny.rstudio.com/gallery/file-download.html that the link there points to a resource:
<a id="downloadData" class="btn shiny-download-link shiny-bound-output" href="session/58c63083742fd00d75ac37732eb224bc/download/downloadData?w=299e8cd2e7b56a2507a31ddbe72446fd2ce5d51f5940ea0a" target="_blank">
<i class="fa fa-download"></i>
Download
</a>
However, I guess that this it to be set by the downloadHandler from the server side. My a-tag in however does not get any href at all. Is what I'm looking to do even possible? Am I'm making some mistake here? Any ideas on how to fix this would be much appreciated.
I think the A tag is being modified by some javascript. If you just download the HTML source for that (which is in an iframe wrapper) then you don't see the long href.
So I further think your custom HTML UI doesn't include the right javascript that adjusts the tag.
I think its done by downloadLinkOutputBinding in shiny.js, line 1402 or thereabouts.
Those demos load a lot of js and css, some of it is clearly crucial!
I've just pasted your html and server.R into a test environment and it works - are you still having this problem?
In particular, it turns out that you can leave out the anchor's href tag (according to this post on the shiny forum).
Also, you only need class="shiny-download-link on the button (ie. no need for shiny-bound-output).
In most cases you will want to pass the downloadable data from the client to the server, so I'll mention how to do that too (thanks to this post). On the server:
output$downloadproject <- downloadHandler(
filename = function() { 'test.csv' },
content = function(file) {
write.csv(input$mydata, file)
}
)
And add some javascript into the html:
Shiny.onInputChange("mydata", [1,2,3,4,5,6,7]);
Hope that helps.