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

PHP ImagickでPDFを透過なしpng画像として出力する

Last updated at Posted at 2020-02-01

概要

ImageMagickのPHPモジュールImagickでPDFを読み込んでpng画像化します。
何もしないと背景が透明になるため、白背景で透過無しのpng画像とします。

2020.02.02修正
背景色を白にする処理によって、1ページしか書き出されない状態が発生しており、修正しました。

コード


<?php

//入力ファイル名
$pdf_filename = 'test.pdf';
//出力ファイル名 ※書き込み権限のあるディレクトリであること!
$out_filename = 'output/test.png';

//ImageMagick宣言
$imagick = new Imagick();
//ファイル読み込み前に、解像度の設定
$imagick->setResolution(96,96);
//PDFファイル読み込み
$imagick->readImage($pdf_filename);
//ページ数をカウントする
$page_count = $imagick->getimagescene();
for($i = 0; $i <= $page_count; $i++) {
	//背景色を白に設定
	$imagick->setimageindex($i);
	$imagick->setImageBackgroundColor('#ffffff');
	$imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
	$imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
}
//書き出し形式をpngに設定
$imagick->setImageFormat('png');
//ファイル書き出し。サーバーの絶対パスを指定する
$imagick->writeImages(dirname(__FILE__).'/'.$out_filename, false);
//最後にオブジェクト破棄
$imagick->destroy();

これで、PDFが1ページのみの場合は、test.pngが、複数ページある場合はtest-1.png、test-2.png、test-3.pngという連番ファイルが保存されます。

参考

https://www.php.net/manual/ja/class.imagick
https://stackoverflow.com/questions/17970421/imagick-make-black-background-white
http://319ring.net/blog/archives/2218/

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?