Created
February 13, 2024 09:25
-
-
Save 136s/d1edb2ea844bad3ad7ffd2574e90c1ce to your computer and use it in GitHub Desktop.
Convert file links in pdf from absolute paths to relative paths.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from pathlib import Path | |
import sys | |
import fitz # pip install pymupdf==1.23.21 | |
def convert_to_relative_path(pdf_path: str): | |
"""Convert file links in pdf from absolute paths to relative paths. | |
Args: | |
pdf_path (str): Path to the PDF file. | |
""" | |
pdf_dir = Path(pdf_path).parent.absolute() | |
doc = fitz.open(pdf_path) | |
for page in doc.pages(): | |
for link in page.get_links(): | |
if filelink := link.get("file"): | |
page.delete_link(link) | |
del link["file"] | |
link["kind"] = 2 | |
link["uri"] = Path(filelink[1:]).relative_to(pdf_dir).as_posix() | |
page.insert_link(link) | |
doc.saveIncr() | |
if __name__ == "__main__": | |
for pdf_path in sys.argv[1:]: | |
convert_to_relative_path(pdf_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment