3

I have a text file (say Dimension.txt) with certain data in it,

I want to write a function in R that would convert this text file into a pdf file.

I googled a lot before I ended up here. There are a lot of places where people have asked as to how to convert a pdf file to text not the vice-versa.

Here is my code:

FunctionFun <- function(.csv)
{
  sink('Dimension.txt')
  csv <- read.csv(.csv)
  dimValue <- dim(csv)
  print("The dimension of the dataset is:")
  print(dimValue)
  return(dimValue)
  sink('Dimension.txt', append=TRUE)
}

When I run FunctionFun("tips.csv"), I get a text file as an output, which looks like: enter image description here

Now, my task is to write a separate function that would convert Dimension.txt to Dimension.pdf.

Your help is appreciated.

Thanks.

Pragyaditya Das
  • 1,648
  • 6
  • 25
  • 44

2 Answers2

5

You can do the following using rmarkdown

require(rmarkdown)
my_text <- readLines("YOUR PATH") 
cat(my_text, sep="  \n", file = "my_text.Rmd")
render("my_text.Rmd", pdf_document())
file.remove("my_text.Rmd") #cleanup

Which gives you a PDF document named my_text.pdf that looks as follows: enter image description here

Rentrop
  • 20,979
  • 10
  • 72
  • 100
  • I already have a text file, I need to convert that into pdf. I don't understand what you tried to do with the answer. – Pragyaditya Das Sep 27 '16 at 16:01
  • 1
    You read in your text file what i simulated via `my_text <- c("Hello World", "Here we go")` you would do that via `readLines` then you apply formatting to it so each line goes into a new line via `cat(..., sep=" \n", ...)` and then you transform it. Did you at least try it? – Rentrop Sep 27 '16 at 20:24
  • Well, I tried with the method you said, then after I failed repeatedly, I tried using an alternative. I used the text2pdf.exe file, which worked well. And now, the solution you provided seems simpler and more elegant. Many thanks :) – Pragyaditya Das Sep 28 '16 at 13:40
1

You could try using the textGrob function? Of course, this will lose all formatting. If you want to keep the orignal text formatting, you probably should not use R but one of the many pdf printers available online and a batch script.

Edit:

library(gridExtra)

toPdf=function(textfile="pathToFile", pdfpath="pathToPdf"){
 text=read.table(textfile, stringsAsFactors=FALSE)
 grb=textGrob(apply(text, 2, paste, collapse="\n"))
 pdf(pdfpath)
 grid.arrange(grb)
 dev.off()
}
Xizam
  • 699
  • 7
  • 21