DocZhivago
DocZhivago

Reputation: 83

Opening PDF within R studio using file.show

I am making making an R tutorial that runs in R within Swirl. I am trying open specific PDF files within R. I am using:

file.show(paste(getwd(),"/cv.pdf",sep=""), title="some title")

But the display is like this:

Output in R-studio

It does not show PDF file. Works well for TXT file.

I am running OSX 10.11.1. Default PDF viewer is "Preview" and I do not have Adobe Reader installed. Is there a way I can have PDF file opened up through an R script?

Upvotes: 6

Views: 10346

Answers (3)

rahul-ahuja
rahul-ahuja

Reputation: 1424

R command to open pdf file on specified page with specified zoom with Foxit Reader in Windows 10 :

prog = "C:\\Program Files\\...\\FoxitReader.exe"
# or
prog = r"(C:\Program Files\...\FoxitReader.exe)"

fpath = r"(E:\...\myfile.pdf)"

loc = paste0('/A zoom=106% page=', as.character(13))

system(paste(shQuote(prog, type='cmd'), shQuote(fpath, type='cmd'), noquote(loc)))

Upvotes: 1

izmirlig
izmirlig

Reputation: 9

If you want something system independent that just works out of the box, use the default pdf viewer in R in a 'system' call:

 "%,%" <- paste0
 n <- grep("pdf", names(options()))
 system(options()[[n]] %,% " <path to file>  2> /dev/null &")

for example,

 system(options()[[n]] %,% " $R_HOME/site-library/pwrFDR/doc/2021-01-25-NWU-Biostat-Talk.pdf 2> /dev/null &")

Upvotes: 0

jimjamslam
jimjamslam

Reputation: 2067

file.show() is only designed to open text files. If you'd like to open PDFs and you know which platform you'll be deploying the script on—not a problem if it's just your OS X machine, but will you be sharing this tutorial?—you can use system2() to run any command the shell can, including Preview.app.

To open a PDF in your OS X system's default PDF viewer:

system2('open', args = 'myfile.pdf', wait = FALSE)

To open a PDF specifically in Preview:

system2('open', args = c('-a Preview.app', 'myfile.pdf'), wait = FALSE)

Note that you'll need to give a full path, rather than just a file name, if you're executing the script from a different directory to your PDF.

Upvotes: 8

Related Questions