[R] pdf font example

ivo welch ivo.welch at gmail.com
Wed Sep 14 18:42:34 CEST 2011


Dear R Users---

[Because I struggled with this for a while, I decided to post it into
r-help for the benefit of others, where google search will pick it up.
 thanks to everyone who made these facilities available.]

The task is to use your own opentype otf fonts in an R-created pdf
file using the pdf device (not with the [excellent] CairoPDF device,
if only because it does not have colorspace [yet] and because it is
not available elsewhere).  Importantly, the fonts should be embedded.

The example that follows embeds the bera fonts, which are freely
available in the TeXLive 2011 distribution.  It tries to check
everything, so it should just work.  you need only the otf and afm
files, which you can create online with a number of font converters.

file.exists <- function( fname ) length(Sys.glob(fname))>0

absolute.path.to.font.files <-  GIVE THE DIRECTORY HERE # ./
(relative) will not work with ghostscript

bera.names <- c("fvsr8a","fvsb8a","fvsro8a","fvsbo8a") # roman, bold,
italic, bold-italic

## use 'http://www.freefontconverter.com/' or
http://www.files-conversion.com/font-converter.php
## if you do not have the correct font types
for (i in 1:length(bera.names)) {
  stopifnot( file.exists(paste(absolute.path.to.font.files,
bera.names[i], ".afm", sep="")) )
  stopifnot( file.exists(paste(absolute.path.to.font.files,
bera.names[i], ".otf", sep="")) )
}

pdf.start <- function(pdfbasename, ...) {
  options( pdf.current=pdfbasename )  ## we need to store the file name
  ## the first argument, the name, does not seem to be used
  berasans <- Type1Font("BeraSans", paste(absolute.path.to.font.files,
bera.names, ".afm", sep=""))
  pdf(file = paste(pdfbasename,".PDF", sep=""), family=berasans, ...)
}

pdf.end <- function(verbose =1) {
  dev.off()
  embedfonts( options("pdf.current") )
}

embedfonts <- function( fname ) {
  commandline <- paste( "ps2pdf14 -DPDFSETTINGS=/prepress
-sFONTPATH=", absolute.path.to.font.files, sep="")
  stopifnot(system( paste(commandline, paste(fname, ".PDF", sep=""),
paste(fname, ".pdf", sep="") ) ) ==0 )
  options( pdf.current= NULL )
}


# and a test
pdf.start("test-berasans")
plot( 1:10, 1:10, xlab="This is bera sans text")
pdf.end()


----
Ivo Welch (ivo.welch at gmail.com)



More information about the R-help mailing list