Advertisement
Python253

pdf2json

Mar 14th, 2024
706
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: pdf2json.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts a PDF file (.pdf) to a JSON file (.json).
  10. It extracts text from each page of the PDF and saves the data as a JSON file with page-wise content.
  11.  
  12. Requirements:
  13. - Python 3.x
  14. - PyMuPDF library (install using: pip install PyMuPDF)
  15.  
  16. Usage:
  17. 1. Save this script as 'pdf2json.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 'json_filename' variables in the script as needed.
  23. """
  24.  
  25. import fitz  # PyMuPDF
  26. import json
  27.  
  28. def pdf_to_json(pdf_filename, json_filename):
  29.     pdf_document = fitz.open(pdf_filename)
  30.     json_data = {"pdf_content": []}
  31.  
  32.     for page_num in range(pdf_document.page_count):
  33.         page = pdf_document[page_num]
  34.         json_data["pdf_content"].append({"page": page_num + 1, "text": page.get_text()})
  35.  
  36.     with open(json_filename, 'w', encoding='utf-8') as json_file:
  37.         json.dump(json_data, json_file, indent=2)
  38.  
  39. if __name__ == "__main__":
  40.     # Set the filenames for the PDF and JSON files
  41.     pdf_filename = 'example.pdf'
  42.     json_filename = 'pdf2json.json'
  43.  
  44.     # Convert the PDF to a JSON file
  45.     pdf_to_json(pdf_filename, json_filename)
  46.  
  47.     print(f"Converted '{pdf_filename}' to '{json_filename}'.")
  48.  
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement