Convert HTML form data into a PDF file using PHP

不羁的心 提交于 2019-12-02 21:10:40

I have used fpdf several times to create php-based pdf documents. An example following:

require('fpdf.php');

$pdf = new FPDF();

$pdf->AddFont('georgia', '', 'georgia.php');
$pdf->AddFont('georgia', 'B', 'georgiab.php');
$pdf->AddFont('georgia', 'I', 'georgiai.php');

# Add UTF-8 support (only add a Unicode font)
$pdf->AddFont('freesans', '', 'freesans.php', true);
$pdf->SetFont('freesans', '', 12);

$pdf->SetTitle('My title');
$pdf->SetAuthor('My author');
$pdf->SetDisplayMode('fullpage', 'single');

$pdf->SetLeftMargin(20);
$pdf->SetRightMargin(20);

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

You can learn very fast with these tutorials from the website itself.


EDIT: Example to save form data: (yes, is very easy...)

require('fpdf.php');
$pdf = new FPDF();

$pdf->AddPage();
foreach ($_POST as $key =>$data)
{
    $pdf->Write(5, "$key: $data"); //write
    $pdf->Ln(10); // new line
}
$pdf->Output($path_to_file . 'file.txt','F'); // save to file

Look at these pages created with fpdf, really!

http://www.fpdf.org/

That would be the library to do it. I used it here to add images to a form and submit it to create a PDF with those images: http://productionlocations.com/locations

The actual code to do it is pretty complex.

I have found PrinceXML very easy to use. It takes your HTML/XML, applies CSS, and converts it into a PDF. The PHP extensions work very well. Unfortunately, it's not free.

One way you can consider is using an online API that converts any HTML to PDF. You can send them a generated HTML (easier to produce) that will contains your user's submitted data, and receive back a high fidelity PDF.

There are quite a few services available on the market. I like to mention PDFShift because it offers a package in PHP that simplifies the work for you.

Once you've installed it (using Composer, or downloaded it directly, depending on your choices) you can quickly convert an HTML document like this:

require_once('vendor/autoload.php');
use \PDFShift\PDFShift;

PDFShift::setApiKey('{your api key}');
PDFShift::convertTo('https://link/to/your/html', null, 'invoice.pdf');

And that's it. There are quite a few features you can implement (accessing secured documents, adding a watermark, and more).

Hope that helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!