Creating PDF in PHP is a very useful skill that can help website developers generate various types of dynamic PDF files such as invoices, reports, certificates, etc. By using libraries and extensions in PHP, developers can easily convert data into PDF format and make it available on the website for users to download or print. This article will explain how to create PDF files in PHP using common libraries and extensions, as well as some practical tips and considerations.
Create PDF using mpdf library in
php
We can create PDF in PHP using external library mpdf
. We can retrieve data from the database, store them in a PDF, and then download the PDF. Using this library we can create PDF from html documents. HTML documents should be encoded in UTF-8. We can retrieve the data to be added to the PDF from the database in HTML format. We can use the library by downloading it from the project
directory via the command composer require mpdf/mpd. This command will install the mpdf
library in the project directory. A vendor
file will be created and we need to use the require()
function to include the file autoload.php
located inside the vendor
folder. We have to make sure that the directory where the library is installed should have write permission.
We will create an object from the Mpdf()
constructor and use methods like WriteHTML()
and output()
to create the PDF. We can output PDF in different modes. We can specify the mode in the second parameter of the output()
method. The different modes are represented by the D
, I
, F
, and S
options. Option D
will force a download of the PDF after the script is run. After the script runs, option I
will display the PDF in the browser. Also, option F
will save the downloaded PDF in a folder relative to the PHP file. Finally, option F
will output a pdf in the browser only if the output()
method is assigned to a variable.
For example, we have a database named phprow
which contains a table named Persons
. Table Persons
contains the following data.
<code> <code class="language-sql hljs" data-lang="sql"><span style="display:flex;"><span><span style="color:#666">+</span><span style="color:#408080;font-style:italic">----------+----------+-----------+ </span></span></span><span style="display:flex;"><span><span style="color:#666">|</span><span style="color:#bbb"> </span>PersonID<span style="color:#bbb"> </span><span style="color:#666">|</span><span style="color:#bbb"> </span>Name<span style="color:#bbb"> </span><span style="color:#666">|</span><span style="color:#bbb"> </span>Address<span style="color:#bbb"> </span><span style="color:#666">|</span><span style="color:#bbb"> </span></span></span><span style="display:flex;"><span><span style="color:#666">+</span><span style="color:#408080;font-style:italic">----------+----------+-----------+ </span></span></span><span style="display:flex;"><span><span style="color:#666">|</span><span style="color:#bbb"> </span><span style="color:#666">22</span><span style="color:#bbb"> </span><span style="color:#666">|</span><span style="color:#bbb"> </span>Harry<span style="color:#bbb"> </span>M<span style="color:#bbb"></span><span style="color:#666">|</span><span style="color:#bbb"> </span>England<span style="color:#bbb"> </span><span style="color:#666">|</span><span style="color:#bbb"> </span></span></span><span style="display:flex;"><span><span style="color:#666">|</span><span style="color:#bbb"> </span><span style="color:#666">32</span><span style="color:#bbb"> </span><span style="color:#666">|</span><span style="color:#bbb"> </span>Paul<span style="color:#bbb"> </span>P<span style="color:#bbb"> </span><span style="color:#666">|</span><span style="color:#bbb"> </span>France<span style="color:#bbb"></span><span style="color:#666">|</span><span style="color:#bbb"> </span></span></span><span style="display:flex;"><span><span style="color:#666">+</span><span style="color:#408080;font-style:italic">----------+----------+-----------+ </span></span></span></code></code>
First, include the vender/autoload.php
file using the require()
function. Then, create and establish a database connection, run a sql query to select data from the database, and create a table in the $html
variable. Use the .
operator to join the $html
variable with the body of the table. Create a table with headers ID
, Name
, and Address
. The table is then populated by retrieving the above data from the Persons
table.
Sample code:
<code> <code class="language-php hljs" data-lang="php"><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">require</span>(<span style="color:#ba2121">'vendor/autoload.php'</span>); </span></span><span style="display:flex;"><span><span style="color:#19177c">$con</span><span style="color:#666">=</span><strong class="keylink">Mysql</strong>i_connect(<span style="color:#ba2121">'localhost'</span>,<span style="color:#ba2121">'root'</span>,<span style="color:#ba2121">''</span>,<span style="color:#ba2121">'phprow'</span>); </span></span><span style="display:flex;"><span><span style="color:#19177c">$res</span><span style="color:#666">=</span><strong class="keylink">mysql</strong>i_query(<span style="color:#19177c">$con</span>,<span style="color:#ba2121">"select * from Persons"</span>); </span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">if</span>(mysqli_num_rows(<span style="color:#19177c">$res</span>)<span style="color:#666">></span><span style="color:#666">0</span>){ </span></span><span style="display:flex;"><span><span style="color:#19177c">$html</span><span style="color:#666">=</span><span style="color:#ba2121">'<table>'; <span style="display:flex;"><span><span style="color:#19177c">$html</span><span style="color:#666">.=</span><span style="color:#ba2121">'<tr> <td>ID</td> <td>Name</td> <td>Address</td>'; <span style="display:flex;"><span><span style="color:#008000;font-weight:bold">while</span>(<span style="color:#19177c">$row</span><span style="color:#666">=</span>mysqli_fetch_assoc(<span style="color:#19177c">$res</span>)){ </span></span><span style="display:flex;"><span><span style="color:#19177c">$html</span><span style="color:#666">.=</span><span style="color:#ba2121">'<tr> <td>'<span style="color:#666">.</span><span style="color:#19177c">$row</span>[<span style="color:#ba2121">'PersonID'</span>]<span style="color:#666">.</span><span style="color:#ba2121">'</span> </td> <td>'<span style="color:#666">.</span><span style="color:#19177c">$row</span>[<span style="color:#ba2121">'Name'</span>]<span style="color:#666">.</span><span style="color:#ba2121">'</span> </td> <td>'<span style="color:#666">.</span><span style="color:#19177c">$row</span>[<span style="color:#ba2121">'Address'</span>]<span style="color:#666">.</span><span style="color:#ba2121">'</span> </td> </tr>'</span>; </span></span><span style="display:flex;"><span>} </span></span><span style="display:flex;"><span><span style="color:#19177c">$html</span><span style="color:#666">.=</span><span style="color:#ba2121">'</span></span></span> </tr></span></span></span> </table>'</span>; </span></span><span style="display:flex;"><span>} </span></span></code></code>
In the above example, we are storing data from the database in the variable $html
. We used the .
operator to join all table elements. So, we are ready to write HTML document to PDF.
Next, create a variable named $mpdf
. Assign the object of the Mpdf()
constructor to a variable using the new
keyword. Call the WriteHTML()
function using the $html
variable as the parameter of the object. Then create another variable $file
to store the PDF. Concatenate files/
with the time()
function and concatenate it again with .pdf
to create the filename. Store it in the $file
variable. Finally, call the output()
function with $file
as the first argument and option I
as the second argument.
Therefore, we retrieved the data from the database and created a PDF using the data. The following example creates a file named with the current time and with the extension .pdf
in the files
folder. After the script runs, the PDF will be displayed in the browser. We can download the PDF from the browser.
Sample code:
<code> <code class="language-php hljs" data-lang="php"><span style="display:flex;"><span><span style="color:#19177c">$mpdf</span><span style="color:#666">=</span><span style="color:#008000;font-weight:bold">new</span> \Mpdf\Mpdf(); </span></span><span style="display:flex;"><span><span style="color:#19177c">$mpdf</span><span style="color:#666">-></span><span style="color:#7d9029">WriteHTML</span>(<span style="color:#19177c">$html</span>); </span></span><span style="display:flex;"><span><span style="color:#19177c">$file</span><span style="color:#666">=</span><span style="color:#ba2121">'files/'</span><span style="color:#666">.</span>time()<span style="color:#666">.</span><span style="color:#ba2121">'.pdf'</span>; </span></span><span style="display:flex;"><span><span style="color:#19177c">$mpdf</span><span style="color:#666">-></span><span style="color:#7d9029">output</span>(<span style="color:#19177c">$file</span>,<span style="color:#ba2121">'I'</span>); </span></span></code></code>
Create PDF in PHP using the
dompdf
library
dompdf
library is also an option for creating and downloading PDFs in PHP. It lets us load HTML into PDF. This library is very similar to the mpdf
library; just the approach is different. We will use methods like loadHtml()
, render()
and stream()
. We need to download the library to our working directory using the command composer require dompdf/dompdf
. It will create the vendor
folder and the composer.<strong class="keylink">JSON</strong>
and composer.lock
files just like the first method.
例如,要求 vendor/autoload.php
作为程序中代码的第一行。然后编写 use
关键字以将 Dompdf
类导入为 use Dompdf/Dompdf
。我们可以使用与上述方法相同的 HTML 表来加载 PDF。
<code> <code class="language-php hljs" data-lang="php"><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">require</span> <span style="color:#ba2121">'vendor/autoload.php'</span>; </span></span><span style="display:flex;"><span><span style="color:#008000;font-weight:bold">use</span> Dompdf\Dompdf; </span></span></code></code>
将 HTML 存储在变量 $html
中后,创建另一个变量 $dompdf
以创建类 Dompdf
的对象。然后使用 $html
作为参数调用 loadHtml()
方法。接下来,调用 render()
函数,然后使用 $dompdf
对象调用 stream()
函数。
下面的示例将使用第一种方法中的表格创建 PDF。render()
方法将 HTML 呈现为 PDF 文件,而 stream()
方法将呈现的 HTML 输出到浏览器。因此,我们可以使用 PHP 中的 dompdf
库创建 PDF。
示例代码:
<code> <code class="language-php hljs" data-lang="php"><span style="display:flex;"><span><span style="color:#19177c">$dompdf</span> <span style="color:#666">=</span> <span style="color:#008000;font-weight:bold">new</span> Dompdf(); </span></span><span style="display:flex;"><span><span style="color:#19177c">$dompdf</span><span style="color:#666">-></span><span style="color:#7d9029">loadHtml</span>(<span style="color:#19177c">$html</span>); </span></span><span style="display:flex;"><span><span style="color:#19177c">$dompdf</span><span style="color:#666">-></span><span style="color:#7d9029">render</span>(); </span></span><span style="display:flex;"><span><span style="color:#19177c">$dompdf</span><span style="color:#666">-></span><span style="color:#7d9029">stream</span>(); </span></span></code></code>
The above is the detailed content of Create PDF in PHP. For more information, please follow other related articles on the PHP Chinese website!

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)
