使用pdftools提取PDF表格至Excel:如何实现列分隔?
Hey there! The issue you're hitting is super common—pdf_text() extracts raw text from your PDF, but since PDF tables rely on fixed character positions (not explicit separators like commas or tabs) to align columns, all that text ends up mashed into one row when you paste it into Excel. Let's adjust your code to parse those fixed-width columns properly and get a table that matches your PDF's format.
Step 1: Load Required Packages
We'll need pdftools for text extraction, plus tidyverse for string manipulation and writexl to export the final table to Excel.
library(pdftools) library(tidyverse) library(writexl)
Step 2: Extract and Clean Raw Text
First, pull the text from your PDF and split it into individual lines, trimming whitespace and removing empty rows:
# Replace "your_file.pdf" with your actual file path tx <- pdf_text("your_file.pdf") # Split text into lines, clean up extra spaces and empty rows clean_lines <- tx %>% str_split("\n") %>% unlist() %>% str_trim() %>% keep(~ . != "") # Remove completely empty lines
Step 3: Parse Fixed-Width Columns
PDF tables use fixed character positions to align columns, so we need to define where each column starts and ends. First, check a sample of your raw lines to identify these positions:
# Print the first 5 lines to inspect column positions head(clean_lines, 5)
Look at the output—you'll see columns aligned by consistent character counts. For example, maybe Column 1 spans characters 1-12, Column 2 13-28, Column 3 29-45, etc.
Use these positions to split each line into columns. You can either use str_sub() for manual splitting, or read_fwf() (fixed-width file reader) for a cleaner approach:
Option A: Manual Splitting with str_sub()
# Adjust the start/end positions and column names to match your PDF formatted_table <- tibble(raw_line = clean_lines) %>% mutate( `Column Name 1` = str_sub(raw_line, 1, 12) %>% str_trim(), `Column Name 2` = str_sub(raw_line, 13, 28) %>% str_trim(), `Column Name 3` = str_sub(raw_line, 29, 45) %>% str_trim(), # Add more columns as needed for your table ) %>% # Remove duplicate header rows if your PDF has them on every page filter(!str_detect(`Column Name 1`, "Header Keyword")) # Replace with your actual header text, e.g., "ID"
Option B: Using read_fwf() (Simpler for Fixed-Width Tables)
# Define column start/end positions and names column_positions <- fwf_positions( start = c(1, 13, 29), # Match your column start positions end = c(12, 28, 45), # Match your column end positions col_names = c("Column Name 1", "Column Name 2", "Column Name 3") ) # Parse the clean lines into a data frame formatted_table <- read_fwf(I(clean_lines), col_positions = column_positions)
Step 4: Export to Excel
Finally, save your properly formatted table to an Excel file:
writexl::write_xlsx(formatted_table, "formatted_output.xlsx")
Key Notes
- Double-check the column start/end positions—they need to match exactly how your PDF's table is aligned. If columns look off, adjust these numbers and re-run.
- If your PDF has merged cells or complex formatting, you might need to do a bit more cleanup (like removing extra header rows or adjusting for wrapped text), but this approach works for most standard fixed-width PDF tables.
内容的提问来源于stack exchange,提问作者Bunty

