finding a way to convert a nodebuffer docx to pdf - docx

I am trying to convert my generated docx document to pdf using docx to pdf package https://www.npmjs.com/package/docx-pdf and I keep getting a Process exited with code 2 error. My docx document was generated using docxtemplater
const contentBuffer = doc.getZip().generate({ type: "nodebuffer" });
How do I convert my document: contentBuffer to pdf, this is what I am trying rn
let output;
const PDF = docxConverter(contentBuffer, output, function(err,result){
if(err){
console.log(err);
}
console.log('result'+result);
});
Is there any other way to achieve this without using this package or method?

Related

ggplot images not appearing in .md github_documents

I recently parameterized hundreds of reports. The html_documents look great, but in the .md reports, which are github_documents, the images are not appearing.
.md file viewed in GitHub:
Same .md file in raw format:
The images have successfully pushed to GitHub:
Why aren't my image files mapping to my reports?
The problem lay in how I specified the location of my output files in the render() function within my for loop.
This loop specified absolute file paths and in turn the image file locations were also being specified with absolute file paths.
dir_datasets <- here::here('data', 'cooked', 'gamma_a4_b0-04')
mdes <- c(.980, .990, .995, 1.010, 1.020, 1.030)
mdes_str <- broman::myround(mdes, 3)
my_files <- list.files(dir_datasets)
for (mde in mdes) {
for (file in my_files){
TRUE_EFFECT <- extract_string_from_filename(file, 3)
MDE_TITLE <- dash4dot(mde, 3)
rmarkdown::render(
fs::path(dir_sprt_ttest, 'template.Rmd'),
output_file = fs::path(
dir_output, paste0('tte', TRUE_EFFECT, '_mde', MDE_TITLE, '.md')
),
params = list(file_name = file, mde = mde)
)
}
}
When I remove the absolute filepath from the output_file argument in render() the images were thereafter saved with relative filepaths, too, and the .md files displayed their images after being pushed to GitHub.
output_file = paste0('tte', TRUE_EFFECT, '_mde', MDE_TITLE, '.md') # note that I dropped fs::path(dir_output,

Setting local chunk options for a specific chunk in knitr?

I'm using knitr to knit RMarkdown, and there have been multiple times where I have wanted to add code chunks programmatically, but failed to find a way to do so satisfactorily. Say I want to have knitr play a sound when a file has finished knitting. My way around this problem has been like so:
beep_on_knit <- function(beep_sound=3, sleep=3) {
library(beepr)
last_label <- tail(knitr::all_labels(),n=1)[[1]]
knitr::knit_hooks$set(
.beep_on_last_chunk =
function(before, options) {
if (options$label == last_label & !before) {
beepr::beep(beep_sound)
Sys.sleep(sleep)
invisible(NULL)
}
})
# Sets the options for every chunk so the hook will be run on them
knitr::opts_chunk$set(.beep_on_last_chunk = TRUE)
}
However, having to edit the chunk properties of every single chunk (i.e., knitr::opts_chunk$set(.beep_on_last_chunk = TRUE) means that if I add this function to a document, it invalidates the cache of every previously cached chunk.
Is there a way to set the options of a specific chunk beforehand?
I don't know why you need to set knitr::opts_chunk$set(.beep_on_last_chunk = TRUE) globally for the document. Is it possible for you to set .beep_on_last_chunk = TRUE only on the last chunk as a local chunk option? If this is possible, you won't need to test if (options$label == last_label) in the hook.
Alternatively, you may consider using the document hook, which is executed after the whole document has been knitted, e.g.,
knitr::knit_hooks$set(document = function(x) {
beepr::beep(3)
x
})

saving an svg object onto disk

I am working with a function that outputs an svg object. As I see the SVG object is essentially a string of characters.
I was wondering how to
1) plot the svg output from the function
2) save this svg object to disk under an svg extension? I tried ggsave but just resulted in an error.
I am fairly new to svg handling, so would appreciate any inputs.
Thanks!
1) I tried that for a package I was developing and it was not straightforward. In the end, I needed two libraries: rsvg and grImport2. Here is the code I used:
tfile <- tempfile(fileext = ".svg")
tfile2 <- tempfile(fileext = ".png")
cat(svg_code, file=tfile)
if (requireNamespace("rsvg", quietly = TRUE) && requireNamespace("grImport2", quietly = TRUE)) {
rsvg::rsvg_svg(svg = tfile, tfile2)
p <- grImport2::readPicture(tfile2)
grImport2::grid.picture(p)
} else {
if (systemShow == FALSE && outFile == ''){
warning("The figure cannot be rendered in the plot window. Please, use the arguments outFile and/or systemShow.")
}
}
if (systemShow){
utils::browseURL(tfile)
}
The first conditional is in case the system does not allow the installation of either package. As you can see, you first need to write the svg code (svg_code) to a file, in this case temporary (tfile). Then, rsvg_svg writes a temporary png file (tfile2). Finally, grImport2::readPicture and grImport2::grid.picture show the converted file in the plot window. I also left the part where the user can set a boolean variable (systemShow) and the package will attempt to open the file on the default system svg viewer.
2) That one is much easier. You just need to write the code to a file as text, like cat(svg_code, file='path_to_file.svg').

Change color of error messages in RMarkdown code output (HTML, PDF)

Is there a way to automatically make text color of errors red in R Markdown without manually editing the HTML later.
---
title: ""
---
#### Example 1
```{r e1, error = TRUE}
2 + "A"
```
#### Example 2
```{r e2, error = TRUE}
2 + 2
```
In the above code, output of Example 1 would have to be red. Currently, I edit the generated HTML (add style="color:red;" to the appropriate tag) but I am wondering if there is an automatic way. Assume that it is not known before knitting whether the code will generate error.
1. Use a knitr hook
The preferred solution is to use the output hook for errors:
```{r}
knitr::knit_hooks$set(error = function(x, options) {
paste0("<pre style=\"color: red;\"><code>", x, "</code></pre>")
})
```
Output hooks in general allow us to control the output of different parts of our R code (the whole chunk, the source code, errors, warnings, ...). For details check https://yihui.name/knitr/hooks/#output-hooks.
2. Quick and dirty solution using JS/jQuery
And this is my "quick and dirty" solution using jQuery/Javascript. Just add it beneath the YAML header.
Might not be bulletproof, since it checks for error messages using the string "Error" which might occur in other applications as well.
<script type="text/javascript">
$(document).ready(function() {
var $chks = $("pre:not(.r) > code");
$chks.each(function(key, val) {
cntnt = $(this).html();
if (cntnt.indexOf("Error") != -1) {
$(this).css('color', 'red');
}
})
})
</script>
I stumbled here because I had the same question but for PDF output rather than HTML.
It turns out combining #Martin Schmelzer's Solution with some hints from #Yihui Xie found here helps to achieve the same behavior in a PDF output.
Add \usepackage{xcolor} to your YAML header and the following chunk to your .Rmd file.
```{r}
color_block = function(color) {
function(x, options) sprintf('\\color{%s}\\begin{verbatim}%s\\end{verbatim}',
color, x)
}
knitr::knit_hooks$set(error = color_block('red'))
```
The result is red error messages like

Importing pdf in R through package "tm"

I know the practical example to get pdf in "R" workspace through package "tm" but not able to understand how the code is working and thus not able to import the desired pdf. The pdf imported in the following code is "tm" vignette.
The code is
if(file.exists(Sys.which("pdftotext"))) {
pdf <- readPDF(PdftotextOptions = "-layout")(elem = list(uri = vignette("tm")$pdf),
language = "en",
id = "id1")
pdf[1:13]
}
The "tm" is vignette. While the pdf which I am trying to bring is "different". So how to change the above code to bring my pdf in the workspace. minn is the pdf document which I am trying to import.
like
if(file.exists(Sys.which("pdftotext"))) {
pdf <- readPDF(PdftotextOptions = "-layout")(elem = list(uri = vignette("minn")$pdf),
language = "en",
id = "id1")
pdf[1:13]
}
So it seems that problem is with the PDF which I was trying to read. However the code goes like the below. Thanks Thomas for the lead. The link for pdf is "http://www.wine-economics.org/workingpapers/AAWE_WP16.pdf"
tt <- readPDF(PdftotextOptions="-layout")
rr <- tt(elem=list(uri="AAWE_WP16.pdf"),language="en",id="id1")
rr[1:15]

Resources