63 lines
1.9 KiB
Python
63 lines
1.9 KiB
Python
import sys
|
|
import os
|
|
|
|
sys.path.append(os.path.join(os.path.dirname(__file__), 'gateway'))
|
|
|
|
try:
|
|
import pdfengine
|
|
except ImportError as e:
|
|
print(f"Failed to import pdfengine: {e}")
|
|
sys.exit(1)
|
|
|
|
def main():
|
|
corpus_dir = os.path.join(os.path.dirname(__file__), 'corpus', 'basic')
|
|
source_pdf = os.path.join(corpus_dir, 'hello_world.pdf')
|
|
dest_pdf = os.path.join(corpus_dir, 'hello_world_python.pdf')
|
|
|
|
print(f"Testing StreamEditor on {source_pdf}")
|
|
editor = pdfengine.StreamEditor(source_pdf)
|
|
|
|
objects = editor.extract_text_objects(0)
|
|
print(f"Extracted {len(objects)} text objects.")
|
|
|
|
hello_idx = -1
|
|
for i, obj in enumerate(objects):
|
|
print(f"[{i}]: {obj['text']} (Font: {obj['fontName']} {obj['fontSize']}, Tm: {obj['tm']})")
|
|
if obj['text'] == "Hello, world!":
|
|
hello_idx = i
|
|
|
|
if hello_idx == -1:
|
|
print("Failed to find 'Hello, world!'")
|
|
sys.exit(1)
|
|
|
|
new_text = "Hello from Python pybind11!"
|
|
print(f"\nReplacing object {hello_idx} with '{new_text}'...")
|
|
|
|
success = editor.replace_text_object(0, hello_idx, new_text, dest_pdf)
|
|
if not success:
|
|
print("Failed to replace text object")
|
|
sys.exit(1)
|
|
|
|
print(f"Successfully saved modified PDF to {dest_pdf}")
|
|
|
|
print("\nVerifying modification...")
|
|
verify_editor = pdfengine.StreamEditor(dest_pdf)
|
|
verify_objects = verify_editor.extract_text_objects(0)
|
|
|
|
found = False
|
|
for obj in verify_objects:
|
|
if obj['text'] == new_text:
|
|
found = True
|
|
break
|
|
|
|
if found:
|
|
print("SUCCESS! Modified text was perfectly preserved.")
|
|
if os.path.exists(dest_pdf):
|
|
os.remove(dest_pdf)
|
|
else:
|
|
print("FAILURE! Modified text was not found in the output PDF.")
|
|
sys.exit(1)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|