Haley
Haley

Reputation: 43

Create new pdf with decreasing font text ( by line) repeating every 9 lines in R

I've been running this code without success, but I don't know why it's not working. My goal is to change the font of a pdf line-by-line, decreasing from biggest to smallest, every 9 lines (e.g., 12-point font for line 1, 10-point font for line 2, 8-point font for line 3, 7-point font for line 4, 6-point font for line 5, 5-point font for line 6, 4-point font for line 7, 3-point font for line 8, 2-point font for line 9, 12-point font for line 10, 10-point font for line 11, 8-point font for line 12, etc.). I ideally want this to work for long documents (e.g., over 1000 lines). I'm trying to see if I can write a program for it so I can enter any single page PDF to convert it to this format. In the end, it will look like a series of repeating eyecharts. I am expecting a new pdf be saved somewhere on my computer. I'm not getting any errors using this code, but I'm also not seeing where the new pdf would be downloaded. Can anyone see what is wrong here?

#install.packages(c("pdftools", "textclean", "qpdf", "ggplot2", "rmarkdown"))
library(pdftools)

# Path to your PDF file
pdf_path <- file.choose()

# Extract text from the PDF
pdf_text <- pdf_text(pdf_path)
# Assuming single page
text_lines <- unlist(strsplit(pdf_text[1], "\n"))
# Define font sizes in a repeating pattern
font_sizes <- c(12, 10, 8, 7, 6, 5, 4, 3, 2)
num_lines <- length(text_lines)
font_size_index <- (seq_len(num_lines) - 1) %% length(font_sizes) + 1
font_sizes_selected <- font_sizes[font_size_index]
library(ggplot2)
library(grid)

# Create a new PDF to save the modified text
pdf("output.pdf", width = 8.5, height = 11) # A4 size

# Create plots with varying font sizes
for (i in seq_along(text_lines)) {
# Create a ggplot object with the text
  p <- ggplot() +
    theme_void() +
    annotate("text", x = 0, y = 1, label = text_lines[i], size = font_sizes_selected[i] / 3, hjust = 0, vjust = 1) +
    theme(plot.margin = unit(c(1, 1, 1, 1), "inches"))

  # Print the plot to the PDF
  print(p)

  # Check for page breaks if necessary
  if (i %% 50 == 0) {  # Adjust the number of lines per page as needed
    grid.newpage()
  }
}

dev.off()

Upvotes: 0

Views: 47

Answers (0)

Related Questions