Generate PDF from PHP/HTML file including CSS - php

I know: opinion-based stuff shouldn't be asked etc., but this isn't about opinion, but for now simply about what still exists or rather what will still work today.
My concern: I am looking for a solution to generate one-page pdf files from PHP/HTML pages that get their content from a database and are rather heavily styled with CSS (also including tabular data and images). A function that lets you open or download the PDF when clicking on a link. The PDF should just basically look the same as the corresponding webpage at size A4 (I'll style it that way). As if you choose "preview/save as PDF" in MacOS' printing dialog, but without the user needing any particular software, working on any OS and browser.
I searched SO and the web, and I found a lot of old posts and pages (3 years and much older), like Convert HTML + CSS to PDF with PHP? , Generate PDF report from php and Generate PDF from HTML PHP I can't see in these posts if any of this is still up-to-date / working.
So I'd have to download all that stuff and build it into my pages, maybe only find out that it doesn't work anymore or isn't really applicable for my situation.
Could people who have experience with that kind of stuff please point me to places where I can find scripts/libraries which are able to do this and work with PHP 5.6 and 7? It doesn't have to support CSS3, I can restrict these pages to CSS2, and although I am using webfonts on that website, I can get along without them for the PDFs. Possibly for free, but also a not-too-expensive commercial solution would be okay. I'd be very grateful for any help.

You can use the mpdf library. It's very easy to learn. Here is the sample code.
It works perfectly.
You can get value from another page, using post method also. Your choice.
<?php $student_id = $_GET['student_id']; ?>
<?php
include("mpdf/mpdf.php");
$html .= "
<html>
<head>
<style>
body {font-family: sans-serif;
font-size: 10pt;
background-image: url(\"images/ok.jpg\");
background-repeat: no-repeat;
padding-top:10pt;
margin-top: 100px;
padding-top: 50px;
}
td { vertical-align: top;
border-left: 0.6mm solid #000000;
border-right: 0.6mm solid #000000;
align: center;
}
p.student_id{
padding-left : 140px;
padding-top : -27px;
}
</style>
</head>
<body>
<!--mpdf
<p class=\"student_id\">$student_id</p>
<sethtmlpageheader name='myheader' value='on' show-this-page='1' />
<sethtmlpagefooter name='myfooter' value='on' />
mpdf-->
</body>
</html>
";
$mpdf=new mPDF();
$mpdf->WriteHTML($html);
$mpdf->SetDisplayMode('fullpage');
$mpdf->Output();
?>

Related

Laravel CSS background-image for hero

I've been attempting to create a hero header in my Laravel 5.4 project. However, one certain thing doesn't seem to be working the way it's supposed to.
(If you're not familiar with what a hero header is; it's basically an image stretching over the entire screen used as a background upon first loading the website, usually with some text and a call to action on top of it.)
This is the way I've structured my code, based on research I've been doing:
home.blade.php:
#extends('layouts.app')
#section('content')
<div class="container">
#include('partials.hero')
</div>
#endsection
hero.blade.php:
<div class="hero-image">
<div class="hero-text">
<h1>Hero header</h1>
<p>Hero text</p>
<button id="hero-prim" class="button-primary">Action!</button>
<button id="hero-sec" class="button-secondary">Info</button>
</div>
and finally the css:
.hero-image{
background-image: url(/images/hero-image.png);
width: 100%;
height: 50%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
position: relative;
}
.hero-text{
text-align: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
}
The strange thing about this is that the text and the buttons are loaded with the page, but there's no sign of the image. Even if I exclude any other elements and try to only show the image, it gives me nothing.
This makes me think the issue must be in how I'm setting the background-image in my CSS, but I've no idea how I'd have to do it differently.
Any help or advice is greatly appreciated!
EDIT:
The image now displays properly, but doesn't stretch across the entire width of the screen, instead I think it only stretches across the section.
In any case, I'm not sure exactly which change in code made this happen, but after trying out some Bootstrap classes on it and defining the height of html and body as 100% (courtesy of VegaPunk), things have been better.
I'm sorry I can't define a more clear answer, but it's still a mystery to me, since yesterday none of these solutions seemed to work on their own.
I face the same problem and solved it just now. My css code was background: url(images/banner.jpg); and the error was Failed to load resource: the server responded with a status of 404 (Not Found). The solution is adding two dot '.' and a single slash '/' before images background: url(../images/banner.jpg);, Now the image has been appeared. My images and css folder in my project public folder and banner.jpg is in the images folder.
Your image should be located in your public folder. So create a folder in public called 'Images' with a capital I and place the hero-image.png inside the created folder.
Heights are really tricky in CSS. I suggest you use a framework like Bootstrap or Foundation.
It doesnt know 50% of what, you need to declare
html, body { height: 100%;}

Styling PDF's with multiple text columns

This is a PDF or HTML styling question: I want multiple text columns in my PDF.
I have a custom modification to PDFMaker's PDF Export tool for Vtiger. For the moment it looks as if I can only style inline in the elemnt style tag, generated from the php export module.
When using the text/code editor in the browser, my styles work fine. I am able to create text columns and everything looks great! (Thank to this genius! : http://jsfiddle.net/jalbertbowdenii/7Chkz/ ) ...I'm using this exact code, only inline.
.cols {
-moz-column-count:3;
-moz-column-gap: 3%;
-moz-column-width: 30%;
-webkit-column-count:3;
-webkit-column-gap: 3%;
-webkit-column-width: 30%;
column-count: 3;
column-gap: 3%;
column-width: 30%;
}
But when I export to PDF, it will not render columns..it stacks my child divs.
*Note: I did change all percentages to fixed widths (pdf seems to not like percentages...not sure on this, but seems like it)
So, is there something special about styling for PDF's to make it recognize columns? Or is there a proven work around in CSS to achieve multiple text columns?
Thanks in advance, Stackoverflow rocks!
After a few days and no replies, here is what I found out. There are different PDF "classes" ( not sure how to define class in this context)... but it's the library of code that interprets different forms of code for rendering a PDF, I've seen PHP, JQuery and HTML.
For the answer to my question, I needed to know what HTML styles the PDF 'class' I was using would work. It turns out that the library/class I was using was called mPDF
This class had nice documentation of styles and attributes it supports:
Supported CSS
HTML attributes
After reading through the docs, it appears that the 'column-count' style is not supported as well as floats are limited. It appears I can not achieve the 'masonry' style layout I'm looking for (at this time).
QUICK UDDATE ON LINK 2021: https://mpdf.github.io/
Add to add multi column function in the mpdf use the following code
<columns column-count="3" vAlign="J" column-gap="2"/>
<!-- add the dive with text etc here-->
<columns/>
For more details you check this website https://mpdf.github.io/reference/html-control-tags/columns.html
I found this in php
.row {
display:table;
width: 100%;
clear: both;
}
.col-lg-4 {
float: left;
width: 32.83%;
border:1px solid blue;
}
and php code here
<?php
$d = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$cols = 3;
$dRowLen = ceil(count($d) / $cols);
?>
<?php for($i=0;$i<$dRowLen;$i++){ ?>
<div class="row">
<?php
$z = $i*$cols;
for($v=0;$v<$cols;$v++){
if(isset($d[$z+$v])){
?>
<div class="col-lg-4">
<?php echo $d[$z+$v];?>
</div>
<?php
}
}
?>
</div>
<?php } ?>

DOMPDF Background Displaying Incorrect Size

I am trying to put together a little contact form for my 3 year old son who has leukemia. I want to use it so people can send him notes of encouragement, and we can print them out and hang them in his room. I've got the form working and posting the data using DOMpdf. My issue is, the background image I am trying to use as the "stationary", refuses to scale out to 100% and regardless of what size I make it in my graphic software, it is not working. Any help is appreciated on what I am missing. Code below. For example, see: http://bebrave.me/#contact
<head>
<style>
body { background-image: url(http://www.bebrave.me/test.jpg); background-position: top left; background-repeat: no-repeat;
background-size: 100%;
margin-top:300px;
width:612px;
height:792px;
}
</style>
</head>
<body>
<table width="500px" border="0" align="center" cellpadding="0" cellspacing="0" id="Table">
<tr>
<td align="left">Dear Joshua,<br />
<?php echo $post->Message; ?></td>
</tr>
<tr>
<td align="right">Be Brave!<br />
-<?php echo $post->Name; ?></td></tr>
</table>
</body>
A few notes, these apply if you're using dompdf 0.6.0 beta 3 or the latest from github:
the background-size property is not yet supported in dompdf
you're adding a margin to the body, so the content of the body (including any background image) will be start after the margin is applied
dompdf applies a default page margin of 1.2cm
the default DPI in later versions of dompdf is 96. It's probably a bit easier to get a handle on the dimensions and placement if you drop that back to 72 so that it matches the PDF standard. If you use any other DPI dompdf will perform translation during the render.
dompdf does appear to diverge from modern browsers in regards to the application of the background image. This is probably something the dev team will want to look at in the future. However, since you're targeting dompdf you'll have to take into account its quirks.
Here's a re-written document that appears to do what you want. It's targeting the latest code available on github which I recommend you use considering the many improvements it includes. If you need to target a different release let me know and I can tweak the HTML.
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Denk+One' rel='stylesheet' type='text/css'>
<style>
#page { margin: 0in; }
body {
font-family: Denk One, sans-serif;
background-image: url(http://www.bebrave.me/test.jpg);
background-position: top left;
background-repeat: no-repeat;
background-size: 100%;
padding: 300px 100px 10px 100px;
width:100%;
height:100%;
}
p {
width: 400px;
margin: auto;
}
.signature {
margin-top: 4em;
text-align: right;
}
</style>
</head>
<body>
<p>
Dear Joshua,<br />
You may not understand all that's happening. Sometimes, you may not even care.
Maybe you just want to do what you have to do to get better so you can
go back to being a three-year-old ... growing, learning, playing, loving.
It may be hard to understand, but you are a hero to your family and friends. You
are a hero to them because you show strength in the face of something so
scary. Stay strong, be happy, and and get better.
</p>
<p class="signature">
Be Brave!<br />
-BrianS
</p>
</body>
</html>
The resolution of your image should be 96 pixels per inch (PPI).
For example:
Format A4: Resolution 96ppi and 210mm x 297mm or 297mm x 210mm (horizontal or vertical, respectively)

Error converting HTML/CSS to PDF using PHP

I build bar codes using jquery in a div in my web app.
The black bars are contructed as a set of div tags with their background as black or white as follows,
<div style='padding: 0px; overflow: auto; width: 194px;' id='bar1'>
<div style='float: left; font-size: 0px; background-color: #FFFFFF; height: 40px; width: 60px'>
<div style='float: left; font-size: 0px; width:0; border-left: 2px solid #000000; height: 40px;'>
I have tried multiple PHP packages (htmp2pdf, dompdf, tcpdf) to convert this to PDF but come up with either a blank PDF or an error as it sees nested div in the content.
Can anyone tell me how can I convert these generated barcodes to PDF suing PHP?
Try wkhtmltopdf which is a simple shell utility to convert html to pdf using the webkit rendering engine.
To use it, unpack it and run it like this:
> wkhtmltopdf www.mydomain.com/barcode3 barcode3.pdf
Basically, it will run over n HTML pages and generate PDF's without the overhead of purely dynamic PDF generation!
This might offer you a solution, but you'll need to check the requirements and see if it fits with your server constraints. It worked really well when we used it for producing accurate reports directly from HTML.
EDIT: EG, running it as a potential user function from within PHP:
For Linux:
exec("wkhtmltopdf http://mydomain.com /home/user/$user.barcode3.pdf 2>&1");
For Windows:
<?php
exec('C://path/to/package//wkhtmltopdf http://mydomain.html barcode3.pdf');
echo "PDF Created Successfully";
?>
Would it help if you used <img> data instead of drawing the bars with <div> rectangles? Not sure if you need Code 128 or another symbology, but there is a complete set of inline (base64) Code 128 images at http://notionovus.com/blog/code-128-barcode/.
I initially tried to generate barcodes by drawing rectangles, but found that letting the browser do the scaling saved me a lot of work. Sounds like the <div> tags have their down side as well.

Best practice: delivery of a wallpaper banner with OpenX

I am looking for a solution to deliver a "wallpaper" banner with the adserver "openx". A wallpaper consists of a leaderboard banner (728x90 px) and a vertical skyscraper. I cant find any option in OpenX itself, so I guess there must be some kind of dirty methods to get it done.
Anyone here having experiences with it? I'm thinking of delivering just an leaderboard banner and then attaching a html snipped to the banner - which contains the markup to my skyscraper-banner... :-/
greg0ire > You can see an example of a "wallpaper" banner on this site (you might experience an overlay banner before, make sure you disable ad blocking extensions): http://www.allocine.fr/ Some days it is in flash, other days it is just a background-image css property set on the body element. I'd like to achieve the second option.
Thanks!
I got wallpapers ads to work through openx using this method.
First I created a div below the content wrapper of my site (using wordpress, header.php file).
<div id="adbg" style=" margin: 0pt auto; height: 1000px; width: 100%; position: fixed; cursor:pointer; ">
Then I created a div block with the wallpaper image in the CSS and added it to OpenX as a TEXT BANNER
<div OnClick="location.href='#';" style="background: url('image.jpg') no-repeat scroll center top #026eb4; height: 100%; width: 100%; margin: 0pt auto; cursor:pointer; "></div>
Finally, I took the openx embed code and place it within the ADBG div I pasted above.
This technique worked well for me on all browsers.
You can of course take the CSS in the adbg div and store it in your CSS file.
For the moment, I ended up doing this, but I'd like to see better solutions:
<div class="openx_<?php echo $_block->getBlockParameter('css_class');?> openx_background hidden">
<?php echo str_replace('INSERT_RANDOM_NUMBER_HERE', rand(0, 9000), $_block->getBlockParameter('html', ESC_RAW));?>
<?php echo javascript_tag()?>
var checkImg = window.setInterval(function(){
if (jQuery('.openx_background img').length)
{
jQuery("body").css('background', 'url("' + jQuery('.openx_background img').attr('src') + '") no-repeat');
window.clearInterval(checkImg);
}
}, 1000);
//give up 3 s later
setTimeout(function(){
if (jQuery('.openx_background img').length == 0)
{
clearInterval(checkImg);
}
}, 3001);
<?php echo end_javascript_tag()?>
</div>
$_block->getBlockParameter('html', ESC_RAW) contains the openx javascript invocation code.
Not sure if this is still of interest, but there's a setting in openX for that called "Companion positioning". Have a look at the OpenX reference guide under point 4.6:
http://opensourceusers.com/sites/default/files/openx_reference_guide.pdf
It's a method to make sure that a skyscraper is delivered every time a certain leaderboard is delivered. You can then use the prepend/append functionality to color the background to turn this "hockey stick" into a full blown wallpaper.

Categories