0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

「Python」 PDF ページの回転

Posted at

はじめに

PDFファイルを操作する際に、ページが逆さまになったり正しく読み取れなかったり印刷できなかったりすることがあります。そのような場合、PDFページを回転させて文書の向きを調整することができます。このチュートリアルでは、Pythonを使用してPDFページを回転させる方法について説明します。回転する際には、必要に応じて時計回りまたは反時計回りに異なる角度で回転することができます。詳細については以下をご覧ください。

ライブラリ

  • Spire.PDF for Python
    これは独立したプロフェッショナルな Python ライブラリです。 PDF の作成、編集、変換をサポートします。

事前準備

  • まず、Python をダウンロードしてインストールします。
  • Visual Studio Codeで「Extensions」をクリックし、「Python」を検索してインストールします。
  • 「Explorer」-「NO FOLRDER OPENED」-「Open Folder」
  • フォルダーを作成します。
  • そのフォルダーに「.py」 ファイルを追加し、任意の名前を付けます。
  • 「Terminal」-「New Terminal」
  • 次のコマンドを入力して、Spire.PDF for Python と plum-dispatch v1.7.4 をインストールします。
pip install Spire.PDF

サンプルコード

from spire.pdf.common import *
from spire.pdf import *

#PdfDocument オブジェクトの作成
pdf = PdfDocument()

#PDFを読む 
pdf.LoadFromFile("C:/Users/Administrator/Desktop/Sample.pdf")

#各ページをループする
for i in range(pdf.Pages.Count):
    page = pdf.Pages.get_Item(i)

    #ページの元の回転角度を取得する
    rotation = int(page.Rotation.value)

    #ページを元の状態から時計回りに180度回転させる。
    rotation += int(PdfPageRotateAngle.RotateAngle180.value)
    page.Rotation = PdfPageRotateAngle(rotation)

#結果文書の保存
pdf.SaveToFile("C:/Users/Administrator/Desktop/Result.pdf")
pdf.Close()

上記のコードでは、まずPdfDocumentオブジェクトを作成し、PDFをロードします。次に、すべてのページをループします。PdfPageBase.Rotation.valueプロパティを使用して、ページの元の回転角度を取得します。回転角度を変更し、PdfPageBase.Rotationプロパティで新しい回転角度をページに適用します。最後に、結果のファイルを保存します。


このコードを実行すると、すべてのページが回転します。
ただし、特定のページのみを回転させたい場合は、すべてのページをループするのではなく、指定のページを取得することができます。

# 最初のページを取得する
page = pdf.Pages[0]

これのパラメータは「0」から計算されます。


image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?