banner
andrewji8

Being towards death

Heed not to the tree-rustling and leaf-lashing rain, Why not stroll along, whistle and sing under its rein. Lighter and better suited than horses are straw sandals and a bamboo staff, Who's afraid? A palm-leaf plaited cape provides enough to misty weather in life sustain. A thorny spring breeze sobers up the spirit, I feel a slight chill, The setting sun over the mountain offers greetings still. Looking back over the bleak passage survived, The return in time Shall not be affected by windswept rain or shine.
telegram
twitter
github

【Python自動化オフィス】バッチでworld文書をPDFに変換し、ページ番号を集計する

こんにちは、皆さん。今日は Python を使って、world 文書を PDF 形式に一括変換する方法を紹介します。

それでは、早速始めましょう!

pypdf2 は、PDF ファイルを読み書きおよび操作するための Python モジュールです。pypdf2 モジュールをインストールするには、以下の手順に従ってください。

Python がインストールされていることを確認してください。ターミナルまたはコマンドプロンプトで python --version と入力して、Python がインストールされているか確認できます。

pypdf2 モジュールのインストール:
ModuleNotFoundError: No module named ‘PyPDF2’

image

インストールが完了したら、Python で pypdf2 モジュールを使用して PDF ファイルを読み書きおよび操作できます。

例えば、PDF ファイル内のテキスト内容を読み取るには、Python スクリプトに pypdf2 モジュールをインポートし、PdfFileReader クラスを使用してファイルを読み込み、各ページを遍歴します。以下は簡単なサンプルコードです:

import pypdf2  
  
pdf_file = pypdf2.PdfFileReader('example.pdf')  
for page_num in range(pdf_file.getNumPages()):  
    page = pdf_file.getPage(page_num)  
    print(page.extractText())

これにより、PDF ファイル内の各ページのテキスト内容が印刷されます。

注意:
PyPDF2 のバージョン更新により、一部のクラスや関数が廃止されました。代替関数を使用することをお勧めします。例えば、pdf ページ数の取得には getNumPages を使用する代わりに len (reader.pages) を直接使用してください。

以下は 2 つのエラーメッセージのヒントです。関数を置き換えるだけで大丈夫です。

PyPDF2.errors.DeprecationError: PdfFileReader is deprecated and was removed in PyPDF2 3.0.0. Use PdfReader instead.

PyPDF2.errors.DeprecationError: reader.getNumPages is deprecated and was removed in PyPDF2 3.0.0. Use len(reader.pages) instead.

image
Python コードを利用して、word 文書を PDF 形式に一括変換し、変換された文書のページ数を統計します。以下はコードの例です:

# -*- coding:utf-8 -*-
import os  # システム機能モジュールをインポート
from win32com.client import Dispatch, DispatchEx  # pywin32モジュールのclientパッケージから関数をインポート
from win32com.client import constants  # pywin32モジュールのclientパッケージからCOM定数を保存するクラスをインポート
from win32com.client import gencache    # pywin32モジュールのclientパッケージからgencache関数をインポート
from PyPDF2 import  PdfReader  # ページ数を取得するため
import re  # 正規表現モジュールをインポート

import pythoncom  # OLE自動化APIをラップしたモジュールで、pywin32のサブモジュール


'''指定されたディレクトリ内のファイルを取得
   filepath:遍歴するディレクトリ
   filelist_out:出力ファイルリスト
   file_ext:ファイルの拡張子、デフォルトは任意のタイプのファイル
'''
def getfilenames(filepath='',filelist_out=[],file_ext='all'):
    # filepath内のすべてのファイルを遍歴、サブディレクトリ内のファイルも含む
    for fpath, dirs, fs in os.walk(filepath):
        for f in fs:
            fi_d = os.path.join(fpath, f)
            if file_ext == '.doc':  # Word文書ファイルを遍歴
                if os.path.splitext(fi_d)[1] in ['.doc','.docx']:   # Wordファイルかどうかを判断
                    filelist_out.append(re.sub(r'\\','/',fi_d))  # パスリストに追加
            else:
                if  file_ext == 'all':  # すべてのファイルを取得する場合
                    filelist_out.append(fi_d)  # ファイルパスをリストに追加
                elif os.path.splitext(fi_d)[1] == file_ext:  # Wordファイル以外のファイルを取得する場合
                    filelist_out.append(fi_d)  # ファイルパスをリストに追加
                else:
                    pass
        filelist_out.sort()  # パスをソート
    return filelist_out  # 完全なファイルパスリストを返す

# WordをPDFに変換(複数ファイル)
def wordtopdf(filelist,targetpath):
    totalPages = 0   # 総ページ数を記録
    valueList = []
    try:
        pythoncom.CoInitialize()   # COMライブラリを初期化し、Word 2007を呼び出す際の「CoInitializeが呼び出されていない」エラーを解決
        gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
        # 変換を開始
        w = Dispatch("Word.Application")
        for fullfilename in filelist:
            (filepath,filename) = os.path.split(fullfilename)  # ファイルパスとファイル名を分割
            softfilename = os.path.splitext(filename)  # ファイル名と拡張子を分割
            os.chdir(filepath)  
            doc = os.path.abspath(filename)
            os.chdir(targetpath)
            pdfname = softfilename[0] + ".pdf"
            output = os.path.abspath(pdfname)
            pdf_name = output

            # ドキュメントパスは絶対パスである必要があります。Wordを起動すると、現在のパスはスクリプトを呼び出したときのパスではありません。
            try: # 例外をキャッチ
                doc = w.Documents.Open(doc, ReadOnly=1)
                doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF, \
                                        Item=constants.wdExportDocumentWithMarkup,
                                        CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
            except Exception as e: # 例外を処理
                print(e)
            if os.path.isfile(pdf_name): # ファイルが存在するか判断
                # ページ数を取得
                pages = getPdfPageNum(pdf_name)   # ページ数を取得
                valueList.append([fullfilename,str(pages)])
                totalPages += pages  # ページ数を累計
                # os.remove(pdf_name)  # 生成されたPDFファイルを削除
            else:
                print('変換に失敗しました!')
                return False
        w.Quit(constants.wdDoNotSaveChanges) # Wordアプリケーションを終了
        return totalPages,valueList  # 総ページ数と各ドキュメントのページ数を返す
    except TypeError as e:
        print('エラーが発生しました!')
        print(e)
        return False
'''
機能:ドキュメントのページ数を統計
path:ファイルの絶対パス
'''
def getPdfPageNum(path):
    with open(path, "rb") as file:
        doc = PdfReader(file)
        pagecount = len(doc.pages)
    return pagecount

if __name__ == '__main__':
    sourcepath = r"C:/Users/Lenovo/Desktop/pythonコード示例/word/"  # ソースパスを指定(Word文書のパス)
    targetpath = r"C:/Users/Lenovo/Desktop/pythonコード示例/pdf/"  # ターゲットパスを指定(PDF保存パス)
    filelist = getfilenames(sourcepath,[],'.doc')  # Word文書のパスを取得
    valueList = wordtopdf(filelist,targetpath)  # Word文書を一括でPDFに変換
    resultList = valueList[1]  # 統計結果を取得
    if valueList:
        for i in resultList:
            print(i[0],i[1])
        totalPages = str(valueList[0]) # 総ページ数
        print("合計ページ数:",totalPages)
    else:
        print("統計するファイルがないか、統計に失敗しました!")

image

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。