'Creating two pdf pages with Imagick

Currently i can create PDF files from images in Imagick with this function

$im->setImageFormat("pdf");
$im->writeImage("file.pdf");

And it's possible to fetch multiple pages with imagick like this

$im = new imagick("file.pdf[0]");
$im2 = new imagick("file.pdf[1]");

But is it possible to save two image objects to two pages? (example of what i am thinking, its not possible like this)

$im->setImageFormat("pdf");
$im->writeImage("file.pdf[0]");

$im2->setImageFormat("pdf");
$im2->writeImage("file.pdf[1]");


Solution 1:[1]

I know this is long past due, but this result came up when I was trying to do the same thing. Here is how you create a multi-page PDF file in PHP and Imagick.

    $images = array(
    'page_1.png',
    'page_2.png'
);
$pdf = new Imagick($images);
$pdf->setImageFormat('pdf');
if (!$pdf->writeImages('combined.pdf', true)) {
    die('Could not write!');
}

Solution 2:[2]

Accepted answer wasn't working for me, as a result, it always generated one page pdf (last image from constructor), to make this work I had to get file descriptor first, like this:

$images = array(
  'img1.png', 'img2.png'
); 
$fp = fopen('combined.pdf', 'w');
$pdf = new Imagick($images);
$pdf->resetiterator();
$pdf->setimageformat('pdf');
$pdf->writeimagesfile($fp);
fclose($fp);

Solution 3:[3]

Is this working?

$im->setImageFormat("pdf");
$im->writeImage("file1.pdf");

$im2->setImageFormat("pdf");
$im2->writeImage("file2.pdf");

exec("convert file*.pdf all.pdf");

Solution 4:[4]

CAM::PDF is a pure-Perl solution for low-level PDF manipulation like this. You can either use the appendpdf.pl command-line tool, or do it programmatically like this:

use CAM::PDF;
my $doc1 = CAM::PDF->new('file1.pdf');
my $doc2 = CAM::PDF->new('file2.pdf');
$doc1->appendPDF($doc2);
$doc1->cleanoutput('out.pdf');

If you can figure out how to make ImageMagick write to a string instead of to a file (I'm not an ImageMagick expert...) then you save some performance overhead by keeping it all in Perl.

(I'm the author of CAM::PDF. It's free software: GPL+Artistic dual-licensed).

Solution 5:[5]

I do not know php or this Imagick library, but if calling an external program is acceptable I can recommend the program pdfjoin to merge pdf files.

It does have an dependency to pdflatex, so if this is something you intend to run on a server you might have to install extra latex stuff, but the end result from pdfjoin is very good, so I think it will be worth it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mitch C
Solution 2 wojtek
Solution 3 schnaader
Solution 4 Ωmega
Solution 5