Simple Example of PDF file using PHP and MySQL

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Exporting MySQL Data to PDF and TXT

scedar/mysql_php_export_pdf_txt

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

readme.md

MYSQL DATA EXPORT TO PDF AND TXT

A boilerplate for PHP project that includes connection to a MYSQL Database, FPDF which is used for generation of PDFs and simple way to generate text files. The code is also commendably structured.

git clone https://github.com/scedar/mysql_php_export_pdf_txt.git
  • Create a database called pdfexport
  • Import sql/pdfexport.sql
  • Edit your Server Details on the config/constants.php

From there i think you are set.

Источник

Generate PDF File from MySQL Database Using PHP

This is another PHP pdf export feature tutorial, I will create a simple PHP script to fetch data from MySQL and create a pdf file using PHP. We will use third-party PHP FPDF library.

The FPDF is a very awesome PHP class to generate PDF using PHP from MySQL database. This is open source PHP library to generate pdf file using PHP.

PDF is a very common and popular file format to read, view, and write documents.PDF format is independent of application software, hardware, and operating systems.

Читайте также:  Javascript add class to element by class

FPDF has the following main features

  • Choice of measure unit, page format and margins.
  • Page header and footer management.
  • Automatic page and line break with text justification
  • Image support (JPEG, PNG and GIF).
  • Colors
  • Links
  • TrueType, Type1 and encoding support
  • Page compression

Video Tutorial:

If you are more comfortable in watching a video that explains about using pdf generation, then you should watch this video tutorial.

Checkout other php export tutorials,

We will follow following steps to Generate PDF

  • Download the FPDF library from fpdf.org
  • We will fetch data from MySQL database into the page.
  • We will use FPDF libs function to generate pdf file with header and footer.

Step 1: We will create employee table into MySQL database.

-- -- Table structure for table `employee` -- CREATE TABLE IF NOT EXISTS `employee` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key', `employee_name` varchar(255) NOT NULL COMMENT 'employee name', `employee_salary` double NOT NULL COMMENT 'employee salary', `employee_age` int(11) NOT NULL COMMENT 'employee age', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=64 ;

We will generate some sample data and insert it into the employee table.

-- -- Dumping data for table `employee` -- INSERT INTO `employee` (`id`, `employee_name`, `employee_salary`, `employee_age`) VALUES (1, 'Tiger Nixon', 320800, 61), (2, 'Garrett Winters', 170750, 63), (3, 'Ashton Cox', 86000, 66), (4, 'Cedric Kelly', 433060, 22), (5, 'Airi Satou', 162700, 33), (6, 'Brielle Williamson', 372000, 61), (7, 'Herrod Chandler', 137500, 59), (8, 'Rhona Davidson', 327900, 55), (9, 'Colleen Hurst', 205500, 39), (10, 'Sonya Frost', 103600, 23), (11, 'Jena Gaines', 90560, 30), (12, 'Quinn Flynn', 342000, 22), (13, 'Charde Marshall', 470600, 36), (14, 'Haley Kennedy', 313500, 43), (15, 'Tatyana Fitzpatrick', 385750, 19), (16, 'Michael Silva', 198500, 66);

Step 2: Let’s connect MySQL database with PHP. We will create connection.php file and add below code.

Class dbObj< /* Database connection start */ var $dbhost = "localhost"; var $username = "root"; var $password = ""; var $dbname = "test"; var $conn; function getConnstring() < $con = mysqli_connect($this->dbhost, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error()); /* check connection */ if (mysqli_connect_errno()) < printf("Connect failed: %s\n", mysqli_connect_error()); exit(); >else < $this->conn = $con; > return $this->conn; > >

The above file is used to connect and select MySQL database using PHP. You need to change $dbhost, $username, $password, and $dbname variable’s value with your database credentials.

Step 3: We will create generate_pdf.php file and add below code.

Image('logo.png',10,-1,70); $this->SetFont('Arial','B',13); // Move to the right $this->Cell(80); // Title $this->Cell(80,10,'Employee List',1,0,'C'); // Line break $this->Ln(20); > // Page footer function Footer() < // Position at 1.5 cm from bottom $this->SetY(-15); // Arial italic 8 $this->SetFont('Arial','I',8); // Page number $this->Cell(0,10,'Page '.$this->PageNo().'/',0,0,'C'); > > $db = new dbObj(); $connString = $db->getConnstring(); $display_heading = array('id'=>'ID', 'employee_name'=> 'Name', 'employee_age'=> 'Age','employee_salary'=> 'Salary',); $result = mysqli_query($connString, "SELECT id, employee_name, employee_age, employee_salary FROM employee") or die("database error:". mysqli_error($connString)); $header = mysqli_query($connString, "SHOW columns FROM employee"); $pdf = new PDF(); //header $pdf->AddPage(); //foter page $pdf->AliasNbPages(); $pdf->SetFont('Arial','B',12); foreach($header as $heading) < $pdf->Cell(40,12,$display_heading[$heading['Field']],1); > foreach($result as $row) < $pdf->Ln(); foreach($row as $column) $pdf->Cell(40,12,$column,1); > $pdf->Output(); ?>

We will include connection and pdf libs file, for customization of the header and footer of pdf files, we will override header and footer methods and define our CSS design.

Читайте также:  Что реализовать на питоне

Step 4: We will create index.php file and add the below code.

     

Generate PDF file from MySQL Using PHP

We have added an HTML form tag and defined the action value generate_pdf.php file.

Conclusion:

We have generated pdf file using PHP and MySQL database, You can generate pdf using another database as well. You just need to create connections with other types of databases.

You can download the source code and see Demo from the below link.

Источник

PDF Export in PHP

If your intention is to create a PDF from PHP, pdflib will help you.

Otherwise, if you want to convert an HTML page to PDF via PHP, you’ll find a little trouble outta here.

So, the options I know are:

DOMPDF : PHP class that wraps the HTML and builds the PDF. Works good, customizable (if you know PHP), based on pdflib, and, if I remember correctly, it takes even some CSS. Bad news: slow when the HTML is big or very complex.

HTML2PS: same as DOMPDF, but this one converts first in .ps (GhostScript), then, in whatever format you need (PDF, JPEG, PNG). For me it is a little better then DOMPDF, but have the same speed problem. Oh, better compatibility with CSS.

Those two are PHP classes, but if you can install some software on the server, and access it through passthru() or system() , give a look to these too:

wkhtmltopdf: based on WebKit (Safari’s wrapper), it’s really fast and powerful. Seems like it is the best one (at the moment) for HTML to PDF conversion on the fly, taking only 2 seconds for a 3 page XHTML document with CSS2. It’s a recent project anyway, so the google.code page is often updated.

htmldoc : this one is a tank, it really never stops/crashes. The project seems dead, as of 2007, but if you don’t need CSS compatibility this can be nice for you.

tcpdf — this is an enhanced and maintained version of fpdf. It has all the main Features of tpdf and it also has faster execution time with great output. For detailed tutorial on using the two most popular PDF generation classes: TCPDF and FPDF, please follow this link. I think you should continue using TCPDF.

  1. Convert HTML + CSS to PDF with PHP?
  2. Which one is the best PDF-API for PHP?
  3. Export a html into PDF in PHP?
  4. Writing HTML with PHP variables to PDF file?
  5. How to convert html into pdf with php?
  6. Tool for exporting html as pdf
  7. Converting HTML in PHP File to PDF File
Читайте также:  Css class in ul and li link

Laravel PDF Exports: How to export data based by id

This code is for exportpdf() function

// This will convert url string to array with '/' declimiter
$url = explode('/', url()->current()); // something like [. '127.0.0.1:8000', 'pengajuan', '3']
$id = end($url); // result is 3

// Get Specific Submission detail with "where" function
$submissionDetail = SubmissionDetail::where('submission_id', $id)->first();

// Rest is just same
$pdf = PDF::loadview('pengajuan_detail', ['submissionDetail' => $submissionDetail]);
return $pdf->stream();

If error occurs, it can be from your PDF template (you can post error if it happens) since you directly using PDF file as a template, not the blade file

Export a php page to pdf

for using FPDF you can download from the link and for more information , Here’s http://fpdf.org

after that you can integrate as follows..


require_once('fpdf.php');

class PDF extends FPDF
function Header()
$query='your query';
$row=mysql_fetch_assoc($query); // data from database

$this->SetXY(50,60);
$this->Cell(45,6,'Name :',1,1,'R');
$this->SetXY(95,60);
$this->Cell(80,6,$row['pdf_name'],1,1);

$this->SetXY(50,66);
$this->Cell(45,6,'Email Address :',1,1,'R');
$this->SetXY(95,66);
$this->Cell(80,6,$row['pdf_email'],1,1);

$this->SetXY(50,72);
$this->Cell(45,6,'Question Paper Selected :',1,1,'R');
$this->SetXY(95,72);
$this->Cell(80,6,$row['subject_sel'],1,1);

$this->SetXY(50,78);
$this->Cell(45,6,'Total Correct Answers :',1,1,'R');
$this->SetXY(95,78);
$this->Cell(80,6,$row['right_answered'],1,1);

$this->SetXY(50,84);
$this->Cell(45,6,'Percentage :',1,1,'R');
$this->SetXY(95,84);
$this->Cell(80,6,$row['percentage']."%",1,1);

$this->Ln(20);
>
function Footer()
$this->SetY(-15);
$this->SetFont('Arial','I',8);
$this->Cell(0,10,'abc according to you',0,0,'C');
>
>
$pdf=new PDF('P','mm',array(297,210));
$pdf->Output($name.'.pdf','D');
?>

you can edit according to your need, it will display record in the form of table and generate it to pdf. hope it will helpful to you.

$this->Image('image path',80,30,50);

How can I export my php page to PDF using php?

Just download mpdf class and use the following script to print your php page. Save the below code as mypdfgenerator.php.:

include("mpdf.php");
$mpdf=new mPDF('win-1252','A4','','',15,10,16,10,10,10);//A4 page in portrait for landscape add -L.
$mpdf->SetHeader('|Your Header here|');
$mpdf->setFooter('');// Giving page number to your footer.
$mpdf->useOnlyCoreFonts = true; // false is default
$mpdf->SetDisplayMode('fullpage');
// Buffer the following html with PHP so we can store it to a variable later
ob_start();
?>
//This is your php page ?>
$html = ob_get_contents();
ob_end_clean();
// send the captured HTML from the output buffer to the mPDF class for processing
$mpdf->WriteHTML($html);
//$mpdf->SetProtection(array(), 'user', 'password'); uncomment to protect your pdf page with password.
$mpdf->Output();
exit;
?>

How to create a PDF file with PHP?

You can try free libraries like fPdf

FPDF is a PHP class which allows to
generate PDF files with pure PHP, that
is to say without using the PDFlib
library. F from FPDF stands for Free:
you may use it for any kind of usage
and modify it to suit your needs.

Источник

Оцените статью