PythonとLibreOfficeを組み合わせて、Office文書をPDFに変換する方法を紹介します。この記事では、Pythonのsubprocessモジュールを用いて、LibreOfficeのsofficeコマンドを実行します。
前提知識: LibreOfficeのユーザプロファイル
LibreOfficeのユーザプロファイルは、ユーザーに関連するすべてのデータを格納するフォルダです。拡張機能やカスタム辞書、テンプレートなどが含まれます。LibreOfficeをアンインストールやアップデートしても削除されません。カスタマイズした内容は保存されます。
デフォルトの格納場所は以下の通りです:
– Windows: %APPDATA%\\libreoffice\\4\\user
– Linux: /home/<ユーザー名>/.config/libreoffice/4/user
– macOS: ~/Library/Application Support/LibreOffice/4/user
PythonでのPDF変換
以下に、Pythonを用いてOffice文書をPDFに変換するサンプルコードを示します。
import os
import subprocess
import shutil
import glob
default_user_profile = os.environ['HOME'] + "/.config/libreoffice/4/user"
class PdfConverter:
def __init__(self, file_in:str, file_out:str, timeout_sec:int=30, user_profile:str=None):
self.file_in = file_in
self.file_out = file_out
self.timeout_sec = timeout_sec
self.user_profile = user_profile
if self.user_profile:
if not os.path.exists(self.user_profile):
shutil.copytree(default_user_profile, self.user_profile)
def __enter__(self):
return self
def __exit__(self):
self.stop()
def start(self):
args = [
'soffice',
'--headless',
'--convert-to',
'pdf',
self.file_in,
'--outdir',
self.file_out,
]
if self.user_profile:
args.append('-env:UserInstallation=file://%s' % self.user_profile)
stdout_str = ""
stderr_str = ""
rc = 0
try:
ret = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=self.timeout_sec, check=True, text=True)
rc = ret.returncode
stdout_str = ret.stdout
stderr_str = ret.stderr
except subprocess.CalledProcessError as cpe:
rc = -1
stdout_str = cpe.stdout
stderr_str = cpe.stderr
except subprocess.TimeoutExpired as te:
rc = -2
stdout_str = te.stdout
stderr_str = te.stderr
finally:
if stdout_str:
print(stdout_str)
if stderr_str:
print(stderr_str)
self.stop()
return rc
def stop(self):
tmp_files = self.file_out + '/*.tmp'
for f in glob.glob(tmp_files):
os.remove(f)
print('soffice finished')
if __name__ == "__main__":
pc = PdfConverter('test1.xlsx', './output')
pc.start()
このコードは、Pythonのsubprocessモジュールを用いて、LibreOfficeのsofficeコマンドを実行し、Office文書をPDFに変換します。
まとめ
PythonとLibreOfficeを組み合わせることで、Office文書をPDFに変換することが可能です。この記事で紹介した方法を試してみてください。