2
2

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 3 years have passed since last update.

img2pdfについて

Last updated at Posted at 2021-03-23

#png画像をPDFにまとめたい!

画像をpdfファイルをにしたい時ってありますよね
調べてみると、img2pdfが便利そうで

を参考にさせてもらい作ってみました。
けど、ちょっと自分の環境では、問題があったのでそれをメモしておきます。

#問題が...

先程のサイトを参考に

pdf.py
import os
import img2pdf
from PIL import Image

if __name__ == '__main__':
    pdf_FileName = "/tmp/png/output.pdf"
    png_Folder = "/tmp/png/"
    extension  = ".png"

    with open(pdf_FileName,"wb") as f:
        
        f.write(img2pdf.convert([Image.open(png_Folder+j).filename for j in os.listdir(png_Folder)if j.endswith(extension)]))

を作ってみたのですが、
画像の名前が○○1.pngなどの連番にしてたのですが、
なぜかpdfにしようとすると順番がバラバラに....

そこでsortedを使用して並び替えて見ました。

pdf.py
import os
import img2pdf
from PIL import Image

if __name__ == '__main__':
    pdf_FileName = "/tmp/png/output.pdf"
    png_Folder = "/tmp/png/"
    extension  = ".png"
    listfolder = os.listdir(png_Folder)
    sortfolder = sorted(listfolder, key=lambda s: int(re.search(r'\d+', s).group()))

    with open(pdf_FileName,"wb") as f:
        
        f.write(img2pdf.convert([Image.open(png_Folder+j).filename for j in sortfolder if j.endswith(extension)]))

に変えたら順番通りになりました。
以上

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?