Created
February 8, 2025 07:47
-
-
Save HViktorTsoi/3f71062cbcb4583d5eef1cb5e7a26889 to your computer and use it in GitHub Desktop.
An Ubuntu utility for converting PDF file to PNG file.
This file contains hidden or 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
# location: /home/xxx/.local/share/applications/ | |
[Desktop Entry] | |
Name=PDF2PNG | |
Comment=converting pdf to png | |
Exec=/path/to/pdf_to_png/pdf_to_png.py %U | |
Icon=/path/to/pdf_to_png.png | |
Terminal=false | |
Type=Application |
This file contains hidden or 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 python3 | |
import os | |
import sys | |
import subprocess | |
from pathlib import Path | |
def convert_pdf_to_png(pdf_path): | |
""" | |
使用ghostscript将PDF转换为高质量PNG | |
参数: | |
pdf_path: PDF文件的路径 | |
""" | |
try: | |
# 确保输入文件存在 | |
if not os.path.exists(pdf_path): | |
raise FileNotFoundError(f"找不到文件: {pdf_path}") | |
# 获取PDF文件的路径信息 | |
pdf_file = Path(pdf_path) | |
output_dir = pdf_file.parent | |
filename = pdf_file.stem | |
# 构建ghostscript命令 | |
gs_cmd = [ | |
'gs', | |
'-dNOPAUSE', | |
'-dBATCH', | |
'-sDEVICE=png16m', | |
'-r500', # 设置分辨率为300dpi | |
'-dGraphicsAlphaBits=4', | |
'-dTextAlphaBits=4', | |
'-dQUIET', | |
f'-sOutputFile=\"{output_dir}/0xGS-{filename}-%03d.png\"', | |
"\"{}\"".format(pdf_path) | |
] | |
open('/tmp/pdf2png.log', 'w').write(' '.join(gs_cmd) + '\n') | |
# 执行转换 | |
result = subprocess.run(gs_cmd) | |
if result.returncode == 0: | |
print(f"转换成功: {pdf_path}") | |
open('/tmp/pdf2png.log', 'a').write('success' + '\n') | |
return True | |
else: | |
print(f"转换失败: {result.stderr}") | |
open('/tmp/pdf2png.log', 'a').write('failed' + '\n') | |
return False | |
except Exception as e: | |
print(f"转换过程中出错: {str(e)}") | |
open('/tmp/pdf2png.log', 'a').write('error:{}'.format(str(e)) + '\n') | |
return False | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print("使用方法: pdf2png.py <PDF文件路径>") | |
sys.exit(1) | |
pdf_path = sys.argv[1] | |
convert_pdf_to_png(pdf_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment