Skip to content

Instantly share code, notes, and snippets.

@jeroen
Last active October 23, 2022 02:25
Show Gist options
  • Save jeroen/852f2b6f8aab5861ebdf33efd3c8f566 to your computer and use it in GitHub Desktop.
Save jeroen/852f2b6f8aab5861ebdf33efd3c8f566 to your computer and use it in GitHub Desktop.
Reoder pdf with drag and drop in shiny
# https://twitter.com/henrikbengtsson/status/1583520708470067201
library(shiny)
library(sortable)
library(pdftools)
library(magick)
# The file to manipulate
pdffile <- tempfile(fileext = '.pdf')
download.file('https://www.uscis.gov/sites/default/files/document/forms/i-9-paper-version.pdf', pdffile)
# convert the pdf into thumbnails
thumbs <- magick::image_read_pdf(pdffile, density = 200, pages = 1:3) |>
image_resize("x100") |>
lapply(function(img){
tmp <- magick::image_write(img, tempfile(fileext = '.png'), format = 'png')
thumbnail <- tags$img(src = file.path('thumbs', basename(tmp)), height = 100)
tags$figure(align = "center", thumbnail, alt = tmp)
})
names(thumbs) = seq_along(thumbs)
addResourcePath(prefix = "thumbs", directoryPath = tempdir())
rank_list_basic <- rank_list(
text = "Drag the items in any desired order",
labels = thumbs,
input_id = "rank_list_basic"
)
ui <- fluidPage(
fluidRow(
column(
width = 12,
tags$h2("PDF page reorder"),
tags$b("Exercise"),
rank_list_basic,
tags$b("Order"),
verbatimTextOutput("results_basic"),
tags$a(href = 'thumbs/output.pdf', 'Download PDF', target = '_blank')
)
)
)
server <- function(input, output, session) {
output$results_basic <- renderPrint({
pages <- as.numeric(input$rank_list_basic)
if(!length(pages)){
pages <- seq_along(thumbs)
}
qpdf::pdf_subset(pdffile, pages = pages, output = file.path(tempdir(), 'output.pdf'))
pages
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment