imagick将文本覆盖在pdf信件上


imagick overlaying text on pdf letter

我有一封pdf设计的信。现在使用php,我想获取地址并将其放在pdf信件上,然后动态生成另一个具有该地址的pdf文件。

我该怎么做。

使用imagick/imagickdraw(ext:php-imagick(在windows下安装很痛苦,但如果你运行的是linux,它非常快速简单。

$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);

实际上,我使用ghostscript将pdf(写入临时目录的单个页面(合并为一个pdf。我看到的唯一问题是,我使用$Imagick->annotateImage((或$Imagick->drawImage((的页面似乎褪色了。我现在正在弄清楚这就是为什么我发现了这个问题。

我想这只是半个答案,但我希望它能帮助到别人。

---通过编辑添加2012年4月6日---找到了一种绕过PDF图像褪色的方法。

$Imagick->setImageFormat("jpg");
$Imagick->writeImage('whatever.jpg');
$Imagick = new Imagick();
$Imagick->setResolution(300,300);
$Imagick->readImage('whatever.jpg');

---2012年5月1日通过编辑添加---找到了一种从pdf到tif的灰度看起来很糟糕的方法。只有一个命令。Ghostscript PDF->TIFF转换对我来说很糟糕,人们对此赞不绝口,只有我一个人看起来闷闷不乐

$Imagick->blackThresholdImage('grey');

---编辑结束2012年5月1日---

$Imagick->setImageFormat("pdf");
$Imagick->writeImage($filename);

许可证的成本很高,但PDFlib是为这样的事情而设计的——打开一个template.pdf文件并动态添加新项目以生成输出pdf。还有其他免费的PDF操作库,比如TCPDF,可能也可以做同样的事情。

我将fpdf与fpdi一起使用。它对我来说很好。我几乎毫无问题地覆盖了数千个文件。