ImageMagickでpdfファイルの1ページ目だけをjpegにする

ImagemMgickのconvertコマンドでpdfをjpegにしようとするとエラーになってしまいました.でもこれは見覚えのあるエラー……どこかにメモした気がするのですが見当たらないのでblogにしてみました.

ImageMagickのセキュリティポリシーを変更してpdfファイルを変換できるようにする

$ convert -geometry 640 /var/tmp/Nextcloud2pdf_cache/HQeSTL5TgcgAPtS.pdf[0] /tmp/HQeSTL5TgcgAPtS.jpg
convert-im6.q16: attempt to perform an operation not allowed by the security policy `PDF' @ error/constitute.c/IsCoderAuthorized/408.
convert-im6.q16: no images defined `/tmp/HQeSTL5TgcgAPtS.jpg' @ error/convert.c/ConvertImageCommand/3258.

セキュリティの問題でImageMagickの設定で無効にしてあるのでこれを有効にします.

$ sudo git -C /etc diff /etc/ImageMagick-6/policy.xml
diff --git a/ImageMagick-6/policy.xml b/ImageMagick-6/policy.xml
index 82a3d0b..0953557 100644
--- a/ImageMagick-6/policy.xml
+++ b/ImageMagick-6/policy.xml
@@ -91,6 +91,6 @@
   <policy domain="coder" rights="none" pattern="PS2" />
   <policy domain="coder" rights="none" pattern="PS3" />
   <policy domain="coder" rights="none" pattern="EPS" />
-  <policy domain="coder" rights="none" pattern="PDF" />
+  <policy domain="coder" rights="read|write" pattern="PDF" />
   <policy domain="coder" rights="none" pattern="XPS" />
 </policymap>

設定を編集後実行するとうまく動きました :)

$ convert -geometry 640 /var/tmp/Nextcloud2pdf_cache/HQeSTL5TgcgAPtS.pdf[0] /tmp/HQeSTL5TgcgAPtS.jpg

pdfファイルの指定ページだけを変換する

ソースファイル名を普通に指定すると, ファイル名-%d.jpg のようなファイルが連番で作成されます.
今回は1ページめだけが欲しいので不必要なファイルがたくさん出来てしまいます.

1ページだけが欲しい場合, ソースファイル名.pdf[0] というようにページ指定して実現できます.この添字は1ページ目が0,2ページめが1のように指定します.

存在しないページ番号を指定するとエラーになります.

$ convert -geometry 640 /var/tmp/Nextcloud2pdf_cache/HQeSTL5TgcgAPtS.pdf[99] /tmp/HQeSTL5TgcgAPtS-99.jpg

Requested FirstPage is greater than the number of pages in the file: 33
   No pages will be processed (FirstPage > LastPage).
convert-im6.q16: no images defined `./HQeSTL5TgcgAPtS-1.jpg' @ error/convert.c/ConvertImageCommand/3258.
環境
$ dpkg-query -W imagemagick
imagemagick     8:6.9.10.23+dfsg-2.1+deb10u1
$ lsb_release -dr
Description:    Debian GNU/Linux 10 (buster)
Release:        10
$ uname -m
x86_64

コメントを残す

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です

Your post must include a link to this post.

How does this work?
Write a response on your own website and include a link to this post. Then submit your response’s URL here. Your response may appear here after moderation. To update or remove it, edit or delete your original post and submit the same URL again. Learn more about Webmentions.