Advertisement
Python253

pdf2txt

Mar 14th, 2024
680
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: pdf2txt.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts a PDF file (.pdf) to a text file (.txt).
  10. It extracts text from each page of the PDF and saves the combined text as a text file.
  11.  
  12. Requirements:
  13. - Python 3.x
  14. - PyMuPDF library (install using: pip install PyMuPDF)
  15.  
  16. Usage:
  17. 1. Save this script as 'pdf2txt.py'.
  18. 2. Ensure your PDF file ('example.pdf') is in the same directory as the script.
  19. 3. Install the PyMuPDF library using the command: 'pip install PyMuPDF'
  20. 4. Run the script.
  21.  
  22. Note: Adjust the 'pdf_filename' and 'txt_filename' variables in the script as needed.
  23. """
  24.  
  25. import fitz  # PyMuPDF
  26.  
  27. def pdf_to_txt(pdf_filename, txt_filename):
  28.     pdf_document = fitz.open(pdf_filename)
  29.     text_content = ""
  30.  
  31.     for page_num in range(pdf_document.page_count):
  32.         page = pdf_document[page_num]
  33.         text_content += page.get_text()
  34.  
  35.     with open(txt_filename, 'w', encoding='utf-8') as txt_file:
  36.         txt_file.write(text_content)
  37.  
  38. if __name__ == "__main__":
  39.     # Set the filenames for the PDF and text files
  40.     pdf_filename = 'example.pdf'
  41.     txt_filename = 'pdf2txt.txt'
  42.  
  43.     # Convert the PDF to a text file
  44.     pdf_to_txt(pdf_filename, txt_filename)
  45.  
  46.     print(f"Converted '{pdf_filename}' to '{txt_filename}'.")
  47.  
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement