簡體   English   中英

如何在 Python 中將 RTF 轉換為 Docx

[英]How to convert RTF to Docx in Python

我正在使用 doxygen 生成 rtf output,但我需要使用 python 以自動方式將 rtf 轉換為 docx 以在構建系統上運行。

  • 輸入:example.rtf

  • Output:example.docx

我不想更改任何樣式、格式或內容。 直接轉換就行了。 與手動打開 word 中的 .rtf 然后執行 SaveAs.docx 的方式相同

我花了很多時間和精力試圖解決這個問題,所以我想我會為社區發布問題和解決方案。 最后其實很簡單,但是花了很長時間才找到正確的信息來完成這個。

此解決方案需要以下內容:

  • Python 3.x
  • PyWin32 模塊
  • Windows 10 環境(沒試過其他口味的Windows)
#convert rtf to docx and embed all pictures in the final document
def ConvertRtfToDocx(rootDir, file):
    word = win32com.client.Dispatch("Word.Application")
    wdFormatDocumentDefault = 16
    wdHeaderFooterPrimary = 1
    doc = word.Documents.Open(rootDir + "\\" + file)
    for pic in doc.InlineShapes:
        pic.LinkFormat.SavePictureWithDocument = True
    for hPic in doc.sections(1).headers(wdHeaderFooterPrimary).Range.InlineShapes:
        hPic.LinkFormat.SavePictureWithDocument = True
    doc.SaveAs(str(rootDir + "\\refman.docx"), FileFormat=wdFormatDocumentDefault)
    doc.Close()
    word.Quit()

由於 rtf 不能嵌入圖像,這也會從 RTF 中獲取任何圖像並將它們嵌入到生成的單詞 docx 中,因此沒有外部圖像引用依賴項。

convert.rtf ->.doc ->.docx 對我有用(可選地,我附上了第 3 步以轉換為.pdf)

您需要 pip 安裝:

pip install pywin32
pip install docx2pdf (optional if you need to have pdf)

第 1 步:轉換.rtf -> .doc

from glob import glob
import re
import os
import win32com.client as win32
from win32com.client import constants


def rtf_to_doc(file_path):
    word = win32.gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(file_path)
    doc.Activate()

    # Rename path with .doc
    new_file_abs = os.path.abspath(file_path)
    new_file_abs = re.sub(r'\.\w+$', '.doc', new_file_abs)

    # Save and Close
    word.ActiveDocument.SaveAs(
        new_file_abs, FileFormat=constants.wdFormatDocument
    )
    doc.Close(False)

第 2 步:轉換.doc -> .docx

import re
import os
from win32com.client import constants
import win32com.client as win32

def doc_to_docx(file_path):
    word = win32.gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(file_path)
    doc.Activate()

    # Rename path with .docx
    new_file_abs = os.path.abspath(file_path)
    new_file_abs = re.sub(r'\.\w+$', '.docx', new_file_abs)

    # Save and Close
    word.ActiveDocument.SaveAs(
        new_file_abs, FileFormat=constants.wdFormatXMLDocument
    )
    doc.Close(False)

第 3 步(如果需要 PDF,則可選).docx ->.pdf

from docx2pdf import convert

def docx_to_pdf(ori_file, new_file):
     convert(ori_file, new_file)
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM