使用pdftools将pdf批量转换为文本

时间:2017-09-30 21:59:36

标签: r pdf batch-processing

我想将1000 pdf转换成文本进行数据分析。我正在使用pdftools包。

我已经能够使用以下代码转换2 pdf:

library(pdftools)
file_list <- list.files('pdf', full.names = TRUE, pattern = 'pdf')

for(i in 1:length(file_list)){
  temp <- pdf_text(file_list[i])
  temp <- tolower(temp)

  file_name = paste(file_list[i], '.txt')
  sink(file_name)
  cat(temp)
  sink()

}

但是当我添加超过2时,我收到以下错误:

" Error in poppler_pdf_text(loadfile(pdf), opw, upw) : PDF parsing failure." 

另外,我希望最终的文本文件只是&#34; file_name.txt&#34;现在我得到&#34; file_name.pdf .txt&#34;

谢谢,

1 个答案:

答案 0 :(得分:1)

library(pdftools)
library(purrr)

setwd("/tmp/test")

file_list <- list.files(".", full.names = TRUE, pattern = '.pdf$')

s_pdf_text <- safely(pdf_text) # helps catch errors

walk(file_list, ~{                                     # iterate over the files

  res <- s_pdf_text(.x)                                # try to read it in
  if (!is.null(res$result)) {                          # if successful

    message(sprintf("Processing [%s]", .x))

    txt_file <- sprintf("%stxt", sub("pdf$", "", .x))  # make a new filename

    unlist(res$result) %>%                             # cld be > 1 pg (which makes a list)
      tolower() %>%                                    
      paste0(collapse="\n") %>%                        # make one big text block with line breaks
      cat(file=txt_file)                               # write it out

  } else {                                             # if not successful
    message(sprintf("Failure converting [%s]", .x))    # show a message
  }

})