Jump to content
xisto Community
Sign in to follow this  
dungsport

Create And Email PDF File 'On The Fly' With PHP

Recommended Posts

Create a pdf on the fly, I am sure that many people know how to do it but not attaching those into email. You can have a lot tutorials about generating a pdf on the fly without storing anything on webserver. This technique allow you to customise the pdf as client's requirements.

 

Let's say you have a huge database of various types of books. On your website, visitors have the option to download sample booklet (in pdf format) of a book for which they are looking. In the old days, you have to create all of those pdf files manually or whatever way you can then upload them onto web server. Links to those pdf files have to be set up in advance properly. If you add new books to your database, the same process of making sample booklet will be repeated.

 

Today, that process can be done just in one php file which uses some libraries to generate pdf booklet on the fly as soon as a visitor asks for downloading it. I will show you this simple step in a moment.

 

However, what could you do if you do want to send those booklet to your visitors through provided email address instead of downloading them. Should you give them a link to the file or attach them with that email? A link in an email is nothing easier but attachment. After showing you how to create a pdf file on the fly using FPDF class, I will demonstrate how to attach that pdf file into emails.

 

 

PART I: Create PDF file on the fly

 

To generate a PDF file using PHP, you need a tool that supports you to do so. In this tutorial, I use FPDF which is completely free and can be downloaded from http://www.fpdf.org/. Following are some highlight features:

 

° Choice of measure unit, page format and margins

° Page header and footer management

° Automatic page break

° Automatic line break and text justification

° Image support (JPEG and PNG)

° Colors

° Links

° TrueType, Type1 and encoding support

° Page compression

 

You do not need to have any extra tool to get FPDF to work. However, if you choose to use compression feature, zlib is required. FPDF works just fine with PHP version 4 and 5.

 

In this tutorial, the main purpose is how to send a pdf that you create on the fly as an email attachment. So, the following simple example on how to create a pdf file using PHP is borrowed from FPDF website. Visit FPDF website for full documentation and tutorials.

 

<?php

require('fpdf.php');

 

$pdf=new FPDF();

$pdf->AddPage();

$pdf->SetFont('Arial','B',16);

$pdf->Cell(40,10,'Hello World!');

$pdf->Output();

?>

 

The sample code above just returns a pdf file with the message "Hello World!" as usual. I will use the same code in the next part of this tutorial.

 

Make sure you download the fpdf.php from FPDF website and place it in the same folder with the example file or using absolute/relative path to fpdf.php if it is in another folder.

 

 

 

PART II: Sending pdf as email attachment

 

You can send email using just native PHP code. However, to make this task simple, I prefer to use PEAR's Mail class which can be obtained from http://pear.php.net/. Do not forget to get a copy of PEAR's Mime class because PEAR's Mail need it to attach files into emails.

 

Make sure you set up all those PEAR classes properly in order to get this to work.

 

<?php

require('fpdf/fpdf.php');

 

$pdf=new FPDF();

$pdf->AddPage();

$pdf->SetFont('Arial','B',16);

$pdf->Cell(40,10,'Hello World!');

$pdfcontent = $pdf->Output("helloworld.pdf", "S");

 

require_once('Mail.php');

require_once('Mail/mime.php');

 

// email address of the recipient

$to = "youremail@yahoo.com";

 

// email address of the sender

$from = "senderemail@yahoo.com";

 

// subject of the email

$subject = "Hello world from coolersport";

 

// email header format complies the PEAR's Mail class

// this header includes sender's email and subject

$headers = array('From' => $from,

'Subject' => $subject);

 

// We will send this email as HTML format

// which is well presented and nicer than plain text

// using the heredoc syntax

// REMEMBER: there should not be any space after PDFMAIL keyword

$htmlMessage = <<<PDFMAIL

<html>

<body bgcolor="#ffffff">

<p align="center">

Please find the pdf attached in the email.<br>

This is generated by <b style="font-size:18pt;">FPDF</b>

</p>

</body>

</html>

PDFMAIL;

 

// create a new instance of the Mail_Mime class

$mime = new Mail_Mime();

 

// set HTML content

$mime->setHtmlBody($htmlMessage);

 

// IMPORTANT: add pdf content as attachment

$mime->addAttachment($pdfcontent, 'application/pdf', 'helloworld.pdf', false, 'base64');

 

// build email message and save it in $body

$body = $mime->get();

 

// build header

$hdrs = $mime->headers($headers);

 

// create Mail instance that will be used to send email later

$mail = &Mail::factory('mail');

 

// Sending the email, according to the address in $to,

// the email headers in $hdrs,

// and the message body in $body.

$mail->send($to, $hdrs, $body);

 

?>

 

You can notice that this will send email using built-in PHP mail() function, so make sure your web server can send email. I reckon the localhost will not work in this case. Look at the line:

 

// create Mail instance that will be used to send email later

$mail = &Mail::factory('mail');

 

If you want to send email using SMTP or other method, please read instruction in PEAR documentation.

 

As you can see, in the sample in part 1, the function output() is used without any parameter. As default, FPDF will return PDF code to http stream and will be display at client browser. In the example of part 2, output() function has two parameters. The first one is file name of that pdf file, which will be ignored because the second parameter "S" is used. Passing string "S" in the second parameter of the output() function will tell FPDF to return PDF file as a string instead of output it to client browser. As you can see, the result is stored in $pdfcontent and attached into the email later. The addAttachment() function will cast the $pdfcontent string into "base64" format which will produce correct format for the pdf file in email attachment.

 

 

Conclusion

 

I do not want to cover too much information in this tutorial except what has been discussed above. If you'd like to understand more about FPDF and PEAR's functions, please visit their website.

 

I hope that this will give you a idea of what the tutorial title says and you can put this into work.

Edited by dungsport (see edit history)

Share this post


Link to post
Share on other sites

howpdf converter works?

Create And Email PDF File 'On The Fly' With PHP

 

This is test comment from pdf converter!

 

FPDF 1.53 Reference Manual

AcceptPageBreak - accept or not automatic page break

AddFont - add a new font

AddLink - create an internal link

AddPage - add a new page

AliasNbPages - define an alias for number of pages

Cell - print a cell

Close - terminate the document

Error - fatal error

Footer - page footer

FPDF - constructor

GetStringWidth - compute string length

GetX - get current x position

GetY - get current y position

Header - page header

Image - output an image

Line - draw a line

Link - put a link

Ln - line break

MultiCell - print text with line breaks

Output - save or send the document

PageNo - page number

Rect - draw a rectangle

SetAuthor - set the document author

SetAutoPageBreak - set the automatic page breaking mode

SetCompression - turn compression on or off

SetCreator - set document creator

SetDisplayMode - set display mode

SetDrawColor - set drawing color

SetFillColor - set filling color

SetFont - set font

SetFontSize - set font size

SetKeywords - associate keywords with document

SetLeftMargin - set left margin

SetLineWidth - set line width

SetLink - set internal link destination

SetMargins - set margins

SetRightMargin - set right margin

SetSubject - set document subject

SetTextColor - set text color

SetTitle - set document title

SetTopMargin - set top margin

SetX - set current x position

SetXY - set current x and y positions

SetY - set current y position

Text - print a string

Write - print flowing text

 

FPDF 1.53 Reference Manual

AcceptPageBreak - accept or not automatic page break

AddFont - add a new font

AddLink - create an internal link

AddPage - add a new page

AliasNbPages - define an alias for number of pages

Cell - print a cell

Close - terminate the document

Error - fatal error

Footer - page footer

FPDF - constructor

GetStringWidth - compute string length

GetX - get current x position

GetY - get current y position

Header - page header

Image - output an image

Line - draw a line

Link - put a link

Ln - line break

MultiCell - print text with line breaks

Output - save or send the document

PageNo - page number

Rect - draw a rectangle

SetAuthor - set the document author

SetAutoPageBreak - set the automatic page breaking mode

SetCompression - turn compression on or off

SetCreator - set document creator

SetDisplayMode - set display mode

SetDrawColor - set drawing color

SetFillColor - set filling color

SetFont - set font

SetFontSize - set font size

SetKeywords - associate keywords with document

SetLeftMargin - set left margin

SetLineWidth - set line width

SetLink - set internal link destination

SetMargins - set margins

SetRightMargin - set right margin

SetSubject - set document subject

SetTextColor - set text color

SetTitle - set document title

SetTopMargin - set top margin

SetX - set current x position

SetXY - set current x and y positions

SetY - set current y position

Text - print a string

Write - print flowing text

FPDF 1.53 Reference Manual

AcceptPageBreak - accept or not automatic page break

AddFont - add a new font

AddLink - create an internal link

AddPage - add a new page

AliasNbPages - define an alias for number of pages

Cell - print a cell

Close - terminate the document

Error - fatal error

Footer - page footer

FPDF - constructor

GetStringWidth - compute string length

GetX - get current x position

GetY - get current y position

Header - page header

Image - output an image

Line - draw a line

Link - put a link

Ln - line break

MultiCell - print text with line breaks

Output - save or send the document

PageNo - page number

Rect - draw a rectangle

SetAuthor - set the document author

SetAutoPageBreak - set the automatic page breaking mode

SetCompression - turn compression on or off

SetCreator - set document creator

SetDisplayMode - set display mode

SetDrawColor - set drawing color

SetFillColor - set filling color

SetFont - set font

SetFontSize - set font size

SetKeywords - associate keywords with document

SetLeftMargin - set left margin

SetLineWidth - set line width

SetLink - set internal link destination

SetMargins - set margins

SetRightMargin - set right margin

SetSubject - set document subject

SetTextColor - set text color

SetTitle - set document title

SetTopMargin - set top margin

SetX - set current x position

SetXY - set current x and y positions

SetY - set current y position

Text - print a string

Write - print flowing text

 

 

FPDF 1.53 Reference Manual

AcceptPageBreak - accept or not automatic page break

AddFont - add a new font

AddLink - create an internal link

AddPage - add a new page

AliasNbPages - define an alias for number of pages

Cell - print a cell

Close - terminate the document

Error - fatal error

Footer - page footer

FPDF - constructor

GetStringWidth - compute string length

GetX - get current x position

GetY - get current y position

Header - page header

Image - output an image

Line - draw a line

Link - put a link

Ln - line break

MultiCell - print text with line breaks

Output - save or send the document

PageNo - page number

Rect - draw a rectangle

SetAuthor - set the document author

SetAutoPageBreak - set the automatic page breaking mode

SetCompression - turn compression on or off

SetCreator - set document creator

SetDisplayMode - set display mode

SetDrawColor - set drawing color

SetFillColor - set filling color

SetFont - set font

SetFontSize - set font size

SetKeywords - associate keywords with document

SetLeftMargin - set left margin

SetLineWidth - set line width

SetLink - set internal link destination

SetMargins - set margins

SetRightMargin - set right margin

SetSubject - set document subject

SetTextColor - set text color

SetTitle - set document title

SetTopMargin - set top margin

SetX - set current x position

SetXY - set current x and y positions

SetY - set current y position

Text - print a string

Write - print flowing text

 

 

FPDF 1.53 Reference Manual

AcceptPageBreak - accept or not automatic page break

AddFont - add a new font

AddLink - create an internal link

AddPage - add a new page

AliasNbPages - define an alias for number of pages

Cell - print a cell

Close - terminate the document

Error - fatal error

Footer - page footer

FPDF - constructor

GetStringWidth - compute string length

GetX - get current x position

GetY - get current y position

Header - page header

Image - output an image

Line - draw a line

Link - put a link

Ln - line break

MultiCell - print text with line breaks

Output - save or send the document

PageNo - page number

Rect - draw a rectangle

SetAuthor - set the document author

SetAutoPageBreak - set the automatic page breaking mode

SetCompression - turn compression on or off

SetCreator - set document creator

SetDisplayMode - set display mode

SetDrawColor - set drawing color

SetFillColor - set filling color

SetFont - set font

SetFontSize - set font size

SetKeywords - associate keywords with document

SetLeftMargin - set left margin

SetLineWidth - set line width

SetLink - set internal link destination

SetMargins - set margins

SetRightMargin - set right margin

SetSubject - set document subject

SetTextColor - set text color

SetTitle - set document title

SetTopMargin - set top margin

SetX - set current x position

SetXY - set current x and y positions

SetY - set current y position

Text - print a string

Write - print flowing text

 

FPDF 1.53 Reference Manual

AcceptPageBreak - accept or not automatic page break

AddFont - add a new font

AddLink - create an internal link

AddPage - add a new page

AliasNbPages - define an alias for number of pages

Cell - print a cell

Close - terminate the document

Error - fatal error

Footer - page footer

FPDF - constructor

GetStringWidth - compute string length

GetX - get current x position

GetY - get current y position

Header - page header

Image - output an image

Line - draw a line

Link - put a link

Ln - line break

MultiCell - print text with line breaks

Output - save or send the document

PageNo - page number

Rect - draw a rectangle

SetAuthor - set the document author

SetAutoPageBreak - set the automatic page breaking mode

SetCompression - turn compression on or off

SetCreator - set document creator

SetDisplayMode - set display mode

SetDrawColor - set drawing color

SetFillColor - set filling color

SetFont - set font

SetFontSize - set font size

SetKeywords - associate keywords with document

SetLeftMargin - set left margin

SetLineWidth - set line width

SetLink - set internal link destination

SetMargins - set margins

SetRightMargin - set right margin

SetSubject - set document subject

SetTextColor - set text color

SetTitle - set document title

SetTopMargin - set top margin

SetX - set current x position

SetXY - set current x and y positions

SetY - set current y position

Text - print a string

Write - print flowing text

 

FPDF 1.53 Reference Manual

AcceptPageBreak - accept or not automatic page break

AddFont - add a new font

AddLink - create an internal link

AddPage - add a new page

AliasNbPages - define an alias for number of pages

Cell - print a cell

Close - terminate the document

Error - fatal error

Footer - page footer

FPDF - constructor

GetStringWidth - compute string length

GetX - get current x position

GetY - get current y position

Header - page header

Image - output an image

Line - draw a line

Link - put a link

Ln - line break

MultiCell - print text with line breaks

Output - save or send the document

PageNo - page number

Rect - draw a rectangle

SetAuthor - set the document author

SetAutoPageBreak - set the automatic page breaking mode

SetCompression - turn compression on or off

SetCreator - set document creator

SetDisplayMode - set display mode

SetDrawColor - set drawing color

SetFillColor - set filling color

SetFont - set font

SetFontSize - set font size

SetKeywords - associate keywords w

 

-reply by prakash

Share this post


Link to post
Share on other sites
which PEAR packages use for example II. ?Create And Email PDF File 'On The Fly' With PHP

Warning: require_once(PEAR.Php): failed to open stream: No such file orDirectory in /httpd/html/xxx/www/Mail.Php on line 21

Share this post


Link to post
Share on other sites
How can I send a copy of the email.Create And Email PDF File 'On The Fly' With PHP

So I set the $to = to my email.That works good.Can someone suggest me how I can also send an automatic copy of the same email with the same attachment to the user's input email.So whoever filled out the form and whatever email they input they get a copy of the same thing.Sort of like CC.

I tried everything.

 Thank you.

 Vadim.

-reply by Vadim

Share this post


Link to post
Share on other sites

Nice article about creating PDF's with FPDF using PHP, I remeber I had some issues with it and found a much better class for creating PDF using PHP, it's called TCPDFI did a lot of projects using it and it's really comfortable and has full utf-8 support and an easy tool to create fonts for usage with it and al ot of examples and tutorials how to use it.Get it at: http://forums.xisto.com/no_longer_exists/ usage is similar to FPDF, because it's also a class :D At first it may be hard to understand it and use it, but with time it gets fun to create dynamic PDF's :P

Share this post


Link to post
Share on other sites
Very Nice...Create And Email PDF File 'On The Fly' With PHP

Was very fortunate to stumble onto this page. It was exactly what I was looking for. I've saved it as a favorite.

Thank you very much..

Share this post


Link to post
Share on other sites
Problem in Attachement name?Create And Email PDF File 'On The Fly' With PHP

Nice Article.

 It is working fine... When I saw the attached pdf  by going to the mail account, it is showing the pdf content in pdf format only, but name of that document is showing as 'noname'.

Why so?

Can any one correct it..

-question by venkat

 

Share this post


Link to post
Share on other sites
Where the attached fil saved?Create And Email PDF File 'On The Fly' With PHP

Replying to (G)MDPHi dear,,,I have just a question,, when you create the pdf file,, where it was saved???And in the attachment to mail you didn't give the file path!I can't understand that!!How the script will know where is the file and attached "un-pathed" file!!I have an approach but I don't if its true!!The file saved @ temp folder,, and the default file path for the attachment is the temp folder...Could you explain that please?Because when I looking for something like that generating file and send it on the fly,,, the file should be firstly saved on some where then attached..And also on your case did the file deleted after the sending or not???Finally big thanks for your effort and code, this solve a big problem for meBest regards

-question by Samer Hannoun

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.