I have pdf designed letter. Now using php I would like to fetch the address and put it on pdf letter and generate another pdf file with that address dynamically.
How can I do this.
using imagick / imagickdraw (ext: php-imagick) It's a pain to setup under windows but if you're running linux it's pretty quick and easy.
$Imagick = new Imagick();
$Imagick->setResolution(300,300);
$Imagick->readImage('my.pdf[' . $page_number . ']');
$width = $Imagick->getImageWidth();
$height = $Imagick->getImageHeight();
$height *= (float) (2550 / $width);
$Imagick->scaleImage(2550, $height);
if (0 != $rotation)
$Imagick->rotateImage(new ImagickPixel(), $rotation);
$scaled_ratio = (float)$Imagick->getImageWidth() / 850;
// put white boxes on image
$ImagickDraw = new ImagickDraw();
$ImagickDraw->setFillColor('#FFFFFF');
$ImagickDraw->rectangle($x1, $y1, $x2, $y2);
$Imagick->drawImage($ImagickDraw);
// put text in white box (really on canvas that has already been modified)
$ImagickDraw = new ImagickDraw();
/* Font properties for text */
$ImagickDraw->setFont('times');
$ImagickDraw->setFontSize(42); // 10 * 300/72 = 42
$ImagickDraw->setFillColor(new ImagickPixel('#000000'));
$ImagickDraw->setStrokeAntialias(true);
$ImagickDraw->setTextAntialias(true);
// add text to canvas (pdf page)
$Imagick->annotateImage(
$ImagickDraw,
$x1 + 4, // 1 * 300/72 = 4
$y1 + 42, // 10 * 300/72 = 42
0,
$the_text // do not use html.. strip tags and replace <br> with \n if you got the text rom an editable div. (which is what I'm doing)
);
$Imagick->writeImage($filename);
I actually use ghostscript to merge the pdfs (individual pages written to a temp directory) into a single pdf. The only problem I've seen is pages seem faded where I've used $Imagick->annotateImage() or $Imagick->drawImage(). I'm figuring that out right now which is why I found this question.
I guess It's a half answer but I hope it helps someone.
--- addition via edit 4/6/2012 --- Found a way around the PDF image fading.
$Imagick->setImageFormat("jpg");
$Imagick->writeImage('whatever.jpg');
$Imagick = new Imagick();
$Imagick->setResolution(300,300);
$Imagick->readImage('whatever.jpg');
--- another addition via edit 5/1/2012 --- Found a way around greyscale from pdf to tif looking awful. Just one command. Ghostscript PDF -> TIFF conversion is awful for me, people rave about it, I alone look sullen
$Imagick->blackThresholdImage('grey');
--- end of edit 5/1/2012 ---
$Imagick->setImageFormat("pdf");
$Imagick->writeImage($filename);
It's expensive for a license, but PDFlib is designed for such things - opening a template .pdf file and adding new items dynamically to produce an output pdf. There's other free PDF manipulation libraries such as TCPDF which can probably do the same thing.