Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text to Pdf in R

Tags:

text

r

csv

pdf

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.

like image 567
Pragyaditya Das Avatar asked Dec 03 '25 17:12

Pragyaditya Das


2 Answers

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

like image 101
Rentrop Avatar answered Dec 06 '25 08:12

Rentrop


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()
}
like image 32
Xizam Avatar answered Dec 06 '25 09:12

Xizam