using PHP to fill in a PDF - php

I need to fill in a PDF, in the fly, using PHP - have no idea where to start.
I'm currently doing quizzes on line using PHP - once a series of quizzes are passed the client wants to let the user download a 'certificate of completion'
The PDF of the certificate has blank lines for the users name and the area of study.
My thought is - add 2 form elements to the PDF, and have PHP pill them in when I pull of the certificate.
BUT HOW?
Is there a different, better way?
Things I need to be 'cautious' of - installing third party stuff is not reliable, UNLESS I can just drop a lib in the the site root. I can't guarantee the hosting provider will let me change a PHP config.
Any help is appreciated - the more specific, the better.
Sorry I have no code at the moment - other than how I'm currently displaying the PDF -
// show cert
echo '<iframe src="1_cert.pdf" width="1000" height="700">';
Thanks.
OK - using TCPDF - as suggested - I've installed, and example pages work...
I've placed a file in the example folder.... I've included a call to import...
require_once('../tcpdf_import.php');
// create new PDF document
$pdf = new TCPDF_IMPORT('1_cert.pdf');
...other boiler plate copied form other examples...
$pdf->SetDisplayMode('fullpage', 'SinglePage', 'UseNone');
// set font
$pdf->SetFont('times', 'B', 20);
$pdf->setPage(1, true);
$pdf->SetY(50);
$pdf->Cell(0, 0, 'test text', 1, 1, 'C');
$pdf->lastPage();
The error I'm getting "TCPDF ERROR: Wrong page number on setPage() function: 1"

Ok, if you're not showing code, then neither will I. ;)
I would recommend doing it with TCPDF.
Import the PDF with TCPDF_Import
In a PDF document, you can navigate to any x/y position, (NB: 0/0 is bottom left). Therefore, simply set your “cursor” to the position to each field, and insert a text with either the Cell or the writeHTMLCell method.
Save the PDF document.
Display it to the user.
Voilà.
By the way, both FPDI and TCPDF are common PHP libraries, so you can just put them somewhere in your base folder, no additional tools should be required on a common web server.

Related

Creating an FPDF to then send via PHPMailer or Print

So I'm trying to create a PDF invoice for a garage and I have the below currently (I know the variables are missing but they had personnel info in for the testing on localhost as well as some of the blank text in cells). So anyway a few things!
I want the Work and the corresponding amount on the same line which I have done some research on and it still wont work as I don't fully understand it, is someone able to help on how it works so I can implement it?
The idea is to create the invoice saving it to a SQL database, which I have done, with the added option to either print the document straight out or send via e-mail to the customer is it possible to Save the PDF to send as an attach through PHPMailer(Which I will be getting to grips with soon!). Or print straight from this?
Ideally wouldn't want to PDF to clog up after creating.
Any help would be greatly appreciated, need anything give me a shout!
<?php
require ('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','',24);
//Cell (Width, height, text, border, end line, 'align')
$pdf->Cell(189,25,'Cheshire West Vehicle Ltd Invoice', 0,1, 'C');
$pdf->SetFont('Arial','',14);
//CWV & Customer Address
$pdf->Cell(65,5,'',0,0);
$pdf->Cell(124, 5, $firstname.' '.$lastname, 0, 1, 'R');
$pdf->Cell(40,5,'',0,0);
$pdf->Cell(149 ,5, $housenumber.', '.$postcode, 0 ,1, 'R');
$pdf->Cell(30,5,'',0,0);
$pdf->Cell(159,5,$contactnumber,0,1,'R');
$pdf->Cell(30,5,'',0,0);
$pdf->Cell(159,5,$email,0,1,'R');
//Date
$pdf->SetFont('Arial','',12);
$pdf->Cell(189,15,$date,0,1,'R');
$pdf->SetFont('Arial','',13);
//Vehicle Stuff
$pdf->Cell(12,15,'VRM: ',0,0);
$pdf->Cell(29,15,$vrm,0,0,'C');
$pdf->Cell(13,15,'Make: ',0,0);
$pdf->Cell(35,15,$make,0,0,'C');
$pdf->Cell(14,15,'Model: ',0,0);
$pdf->Cell(44,15,$model,0,0,'C');
$pdf->Cell(18,15,'Mileage: ',0,0);
$pdf->Cell(24,15,$mileage,0,1,'C');
//Work
$pdf->Cell(149,5,'Work Carried Out',1,0,'C');
$pdf->Cell(40,5,'Amount',1,0,'C');
$pdf->Cell(0,5,'',0,1);
$pdf->MultiCell(189,25,$work1,1,'C',false);
$pdf->MultiCell(40,25,$amount1,1,1);
$pdf->MultiCell(189,25,$work2,1,'C',false);
$pdf->MultiCell(40,25,$amount2,1,1);
$pdf->MultiCell(189,25,$work3,1,'C',false);
$pdf->Cell(40,25,$amount3,1,1);
//Other
$pdf->Cell(189,5,'Other Details',1,'C');
$pdf->MultiCell(189,25,$other,1,'C',false);
$pdf->Output();
?>
Yes. If you look at the docs for tcpdf, you'll see there are options for output, including one (S) that returns the PDF data directly as a string, rather than writing it to a file. You can pass this raw data directly into PHPMailer's addStringAttachment() method, like this:
$pdfdata = $pdf->Output('name.pdf', 'S');
$mail->addStringAttachment($pdfdata, 'name.pdf');
It will get its encoding and MIME type set automatically.
In other news, the tcpdf docs are hopeless to navigate.

PDF manipulation - images are distorted after few consecutive operations on PDF file

I've run into this weird issue with PDF file handling. Not sure if SO is the right place to ask this, but I couldn't find any specific sites for this. I hope that someone can shed some light on the issue.
This happens with the following specific process, if some of steps are omitted - the issue is not observed.
I have a PHP application that serves PDF files to users. These files are created by authors in MS Word 2007, then printed to protected PDF (using pdf995, most likely, I can confirm if needed).
I'll call this initial PDF file as 'source' hereinafter.
Upon request, the source file is processed in PHP the following way:
we decrypt it using qpdf:
qpdf --decrypt "source.pdf" "tmp_output.pdf"
Then we add security label / wartermark to it, encrypt and output to browser using mPDF 6.0:
$mpdf = new mPDF();
$mpdf->SetImportUse();
$pagecount = $mpdf->SetSourceFile($fpath);
if ($pagecount) {
for ($i=1;$i<=$pagecount;$i++){
$tplId = $mpdf->ImportPage($i);
$mpdf->UseTemplate($tplId);
$html = '[security label / watermark contents...]';
$mpdf->WriteHTML($html);
}
}
$mpdf->SetProtection(array('copy','print'), '', 'password',128);
$mpdf->Output('final_output.pdf','I');
With the exact steps described above, images in the output that were pasted in the Word doc appear as follows:
In the source PDF, tmp_output (qpdf decrypted file) the pasted images look correct:
The distortion doesn't take place if any of the following occurs:
Word doc printed to PDF without protection
mPDF output is not protected.
As you can see there too many factors, so I don't know where to look for a bug.
Each component works correctly on it's own and I cannot find any info on the issue. Any insights are greatly appreciated.
EDIT 1
After some more testing, it appears that this only happens to screenshots taken from web browser, Windows explorer, MS Word. Cannot reproduce this with screenshots from Gimp.
It appears that something along the way attempts to convert white to alpha and fails.
The current version (6.1) of Mpdf has a bug which does not handle escaped PDF strings (imported via FPDI) correct if they should be encrypted.
A pull request, which fixes this issue is available here.

mPDF only getting "Finished" when progressBar enabled

I'm generating a very large pdf file on my PHP application. The document can reach over 300 pages. The build process may take more than 40 seconds, that's why I want to show the user a message to understand that the file is being generated.
The problem is that when i set $this->progressBar = 1; on config.php file, the progress shows perfect, but when the proces finish, I'm only getting a Finished message, and i'm not redirected to the file.
Heres' my code:
<?php
ob_start();
include('include/mpdf/mpdf.php');
define('_MPDF_URI','../');
$mpdf = new mPDF('','A4', 9, 'freesans', 10, 10, 20, 15, 5, 5, 'L');
$mpdf->SetHTMLHeader($cabecera);
$mpdf->setFooter("Pagina {PAGENO} de {nb}");
$html=utf8_encode($html);
$mpdf->WriteHTML($html);
$mpdf->Output();
ob_end_flush();
I believe someone already has gone through this problem. Please guide me on how I can solve this problem.
Thank you,
The documentation has a note:
Note: You may need to define the constant _MPDF_URI if you use progress bars. The constant _MPDF_URI is needed to redirect the user
to the PDF file (and prior to mPDF 5.0 to locate a javascript file
within the progress bar script). It must be either a relative path
(e.g. '../') or a full URI (e.g. 'http://www.example.com/mpdf/'). If
you do not define it before calling mPDF() mPDF will assign it the
same value as _MPDF_PATH. This is fine if you have used a relative
path. _MPDF_PATH requires either a relative path or a filesystem real
path (e.g. '/homepages/27/d84233457/htdocs/')
Then make sure the ->Output() function has the correct parameters, such as:
$mpdf->Output('yourFileName.pdf', 'I');
For more info see this stack answer.

Convert HTML form data into a PDF file using PHP

I have been looking and testing this for a couple days now and was wondering if anyone could point me in a different direction. I have a very long job application HTML form (jobapp.html) and a matching PDF (jobpdf.pdf) that have the same field names for all entries in both the HTML form and the PDF. I need to take the user data that is entered in the form and convert it to a PDF. This is what I have gathered so far but don't know if I am on track:
Is pdftk the only viable 3rd party app to accomplish this?
Using pdftk would i take the $_POST data collected for the user and generate a .fdf(user.fdf) then flatten the .fdf on the .pdf(job.pdf). So irreguarless of where the fields are located on each document the information on the fdf would populate the pdf by field names?
I have been trying
http://koivi.com/fill-pdf-form-fields/tutorial.php
I have also looked at "Submit HTML form to PDF"
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!

Writing PDF using PHP (PDFLib)

I'm currently writing a code to output a pdf file in PHP using PDFlib from http://www.pdflib.com/. The problem is all html tag is also written in the output file. How can be able to cancel out all those tags?
Here is my sample code.
$postVariable = $_POST;
$contentData = "";
foreach($postVariable as $key => $value){
if(is_array($key)){
foreach($key as $key1 => $value1){
$contentData.= $key1 .": ". $value1."<nextline>";
}
}else{
$contentData.= $key .": ". $value."<nextline>";
}
}
$testdata = nl2br($contentData);
$pdf = pdf_new();
// open a file
pdf_open_file($pdf, $_SERVER['DOCUMENT_ROOT']."cas".DIRECTORY_SEPARATOR."$filename.pdf");
// start a new page (A4)
pdf_begin_page($pdf, 595, 842);
// Locate Font Directory
$fontdir = "C:\WINDOWS\Fonts";
// Font Name Parameters
pdf_set_parameter($pdf, "FontOutline", "arialMyName=$fontdir\arial.ttf");
// Find Font
$arial = PDF_findfont($pdf,"arialMyName","host",0 );
// Set font size and font name
pdf_setfont($pdf, $arial, 10);
//$arial = pdf_findfont($pdf, "Arial", "host", 1);
//pdf_setfont($pdf, $arial, 10);
// print text
pdf_show_xy($pdf, "TO THE UNIT OWNER",50, 750);
pdf_show_xy($pdf, "Test ext", 50,730);
pdf_show_xy($pdf, "test test", 50,715);
pdf_show_xy($pdf, $contentData, 50,700);
// end page
pdf_end_page($pdf);
// close and save file
pdf_close($pdf);
and the sample output is:
TO THE UNIT OWNER
Test text
test test
type: Apartment****var_name: ****var_company: ****var_date: ****submit: Save and Download<
It disregards the html tags and it include it on the content.
Is there any other methods on how to print out HTML to PDF using the library that I'm currently using (PDFlib).
Thanks.
regards,
Resty
I would recommend the TCPDF library. It can convert your HTML to a PDF file, including CSS code. It has support for quite a lot of HTML tags, and does a decent job. HOWEVER, from personal experience, while it is very possible to generate high quality PDF files with it, the results are not always 100% as expected. It might need a bit of tweaking and fiddling to get the result you want.
If you only want to remove the HTML tags, I think you might want to take a look at strip_tags. But I guess that's not really what you're after.
Finally, there's a really really cool new kid on the block - a PHP extension that uses the WebKit HTML and rendering engine to generate PDFs. It is called the libwkhtmltox extension and can be found here. It produces amazing results. For example, look at this PDF it made from the homepage of the New York Times - see (http://www.2shared.com/document/kYuS_G7p/nytimes.html - click "save to my pc" down below). That output was generated without specifying any additional options. Exceptional. HOWEVER, you need to get it running as PHP extension, and that might be a non-trivial task. So I would say: stick with the TCPDF library for now.
You cannot generate PDF content from HTML by using PDFLib. Ok, you can write convertor, but that's a huge work to do.
I recommend using TCPDF which supports HTML input.
Man... I was trying to do same thing once. It is very hard to work with pdflib directly.
I found this project, hosted on Google code site. The project deserved 10 stars out of 5.
It is called DOM PDF, you can download it here. You can generate PDFs from HTML pages, with CSS support. You can generate PDF with less than 10 lines of code!
Look at samples to see it in action.

Categories