ファイルの変換#

ファイルからPDFへ#

PyMuPDFでサポートされているドキュメントタイプ は、Document.convert_to_pdf() メソッドを使用することで簡単に PDF に変換できます。このメソッドはデータバッファを返し、それを PyMuPDF が利用して新しい PDF を作成できます。

import pymupdf

xps = pymupdf.open("input.xps")
pdfbytes = xps.convert_to_pdf()
pdf = pymupdf.open("pdf", pdfbytes)
pdf.save("output.pdf")

PDFからSVGへ#

技術的には、SVGファイルは複数ページを持つことができないため、各ページをSVGとしてエクスポートする必要があります。

ページのSVG表現を取得するには、Page.get_svg_image() メソッドを使用します。

import pymupdf

doc = pymupdf.open("input.pdf")
page = doc[0]

# Convert page to SVG
svg_content = page.get_svg_image()

# Save to file
with open("output.svg", "w", encoding="utf-8") as f:
    f.write(svg_content)

doc.close()

PDFからMarkdownへ#

PyMuPDF4LLM API を利用することで、PDFをMarkdown表現に変換できます。

import pymupdf4llm
import pathlib

md_text = pymupdf4llm.to_markdown("test.pdf")
print(md_text)

pathlib.Path("4llm-output.md").write_bytes(md_text.encode())

PDFからDOCXへ#

PyMuPDF を使用してドキュメントを PDF から DOCX 形式に変換する pdf2docx ライブラリを使用します。

from pdf2docx import Converter

pdf_file = 'input.pdf'
docx_file = 'output.docx'

# convert pdf to docx
cv = Converter(pdf_file)
cv.convert(docx_file) # all pages by default
cv.close()

This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of that license. Refer to licensing information at artifex.com or contact Artifex Software Inc., 39 Mesa Street, Suite 108A, San Francisco CA 94129, United States for further information.