Search code examples
apacherrapache

How RApache force a pdf download by using R


i'm trying to using R and RApache to download pdf file with no success.

Here's my code

#R-Downwload pdf
#---------------------------------------------
pdf("/public_html/upload/rpdf.pdf")
attach(mtcars)
plot(wt, mpg)
abline(lm(mpg~wt))
title("PDF Report")
dev.off()

setContentType(type='application/pdf')
setHeader(header='Content-Disposition', 'attachment; filename=rpdf.pdf')
setHeader(header='Content-Transfer-Encoding', 'binary')
setHeader(header='Accept-Ranges', 'bytes')

cat("/public_html/upload/rpdf.pdf")

When I run this code on the browser, it show me the download popup box but when I click to download it display

... either not a supported file type or it has been damaged"

Solution

  • If you ever come accross this question, here's the answer.

    setHeader(header='Content-Disposition', 'attachment; filename=rpdf.pdf')
    setContentType("application/pdf")
    t <- tempfile()
    pdf(t)
    attach(mtcars)
    plot(wt, mpg)
    abline(lm(mpg~wt))
    title("PDF Report")
    dev.off()
    setHeader('Content-Length',file.info(t)$size)
    sendBin(readBin(t,'raw',n=file.info(t)$size))
    

    Enjoy!