开发者

Validating a PDF before sending as e-mail attachment

I'm using FDPF to generate invoices for customers, which are then attached to an e-mail and sent along to the customer. The invoices / emails are generated in a batch (several hundred at a time). In the first real world run of 开发者_运维问答the batch, a handful (about 5 out of 200) of customers received corrupt PDFs. The common link between them was that they had larger invoices than average, which leads me to believe that the time it takes to generate the invoice is causing a race condition and perhaps the e-mail is being sent before the PDF has time to finish generating completely. Is there a way to validate that the PDF is not corrupt before sending the e-mail? Or is there another way to approach the problem that I'm overlooking?


You can test if the pdf is fully generated by creating an md5 hash for the pdf at the time the file is first sent, and then again while the email is sending, and finally after it has been sent. If the md5 changes each time, then the file is still being created by the pdf generator while the email is sending.

Here's an example on how to use md5 hash:

<?php

$file_name = 'md5_demonstration_file';


    $file_changer = 0;

    while($file_changer < 10)
    {
     file_put_contents($file_name, $file_changer);
     echo md5_file ($file_name) . '</br>';
     $file_changer++;
    }

    ?>

You will notice that the md5 hash changes on each iteration of the function because the file is still being written. If you try this sample code, you may have to set the permissions on 'md5_demonstration_file' manually so that anyone can write to it.

If race condition isn't the problem have you read this SO suggested thread: Corrupt PDF email attachment when generated by FPDF and PHP


Be aware that the latest version of the Acrobat reader is fussier about reading files that don't conform exactly to the correct pdf format.

The start of a pdf document is indicated by the string %PDF. Older versions of Acrobat would ignore file content occurring before the %PDF marker. For example, you might have left some debug output in the file, as follows:

debug line 1
debug line 2
%PDF-1.4
3 0 obj
<</Type /Page
etc.

and Acrobat would open that ok, (as will Preview on OSX).

Acrobat won't accept that anymore.

I got bitten by that, so hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜