How to add CSS to html2pdf?

by eleanore_wisozk , in category: Other , a year ago

How to add CSS to html2pdf?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by ava.bogan , a year ago

@eleanore_wisozk 

HTML2PDF is a PHP library that converts HTML documents to PDF format. To add CSS styles to your HTML document while using HTML2PDF, you can use either inline styles or an external CSS file.


Inline styles:


You can add inline styles directly to the HTML tags in your document. Here's an example:

1
2
3
4
5
6
7
8
9
<html>
<head>
    <title>My Document</title>
</head>
<body>
    <h1 style="color: red;">Heading 1</h1>
    <p style="font-size: 12px;">This is a paragraph.</p>
</body>
</html>


External CSS file:


You can also link to an external CSS file in your HTML document. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<html>
<head>
    <title>My Document</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <h1>Heading 1</h1>
    <p>This is a paragraph.</p>
</body>
</html>


In this example, the styles.css file contains your CSS styles:

1
2
3
4
5
6
7
h1 {
    color: red;
}

p {
    font-size: 12px;
}


When using HTML2PDF, make sure to include any external CSS files or inline styles in your PHP code before generating the PDF document. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php
require_once('html2pdf/vendor/autoload.php');

// Create new HTML2PDF object
$html2pdf = new SpipuHtml2PdfHtml2Pdf('P', 'A4', 'en');

// Include CSS styles
$html2pdf->writeHTML('<link rel="stylesheet" href="styles.css">');

// Generate PDF document
$html2pdf->writeHTML($html);

// Output PDF document to browser
$html2pdf->output();
?>


In this example, the writeHTML method is used to include the CSS file and the HTML content. The output method is then used to generate and display the PDF document in the browser.

Member

by marina , 3 months ago

@eleanore_wisozk 

And just to clarify, please ensure that the path to the CSS file is correct in your PHP code. Make sure the CSS file is located in the correct directory relative to your PHP file, or use an absolute path if needed. This way, HTML2PDF can properly access and apply the CSS styles to your HTML document when generating the PDF.