I want to create a pdf on my wordpress homepage with dompdf. Local an my computer with xampp there is no problem, all works fine.
On wordpress I am using the plugin "PHP Code For Posts". The dompdf folder I copied to the folder of the plugin.
The pdf get created but it is defective.
<?php
if(isset($_POST['button']))
{
require_once("dompdf/dompdf_config.inc.php");
spl_autoload_register('DOMPDF_autoload');
function pdf_create($filename, $paper, $orientation, $stream=TRUE)
{
$dompdf = new DOMPDF();
$dompdf->set_paper($paper, $orientation);
$dompdf->load_html('TEST');
$dompdf->render();
$dompdf->stream($filename.".pdf");
}
$filename = 'file_name';
$dompdf = new DOMPDF();
pdf_create($filename, 'A4', 'portait');
}
?>
<form method="post" >
<p>Test: <input type="text" name="price" /></p>
<p><input type="submit" name="button" value="PDF" /></p>
</form>
I hope anybody can help me. I have no idea why it works local and on wordpress it creates a defective file.
UPDATE:
Here is the code when I open the defective file with notepad.
<!DOCTYPE html>
<html lang="de-DE">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="http://test-homepage.de/xmlrpc.php">
<!--[if lt IE 9]>
<script src="http://test-homepage.de/wp-content/themes/zerif-pro/js/html5.js"></script>
<link rel="stylesheet" href="http://test-homepage.de/wp-content/themes/zerif-pro/css/ie.css" type="text/css">
<![endif]-->
<title>Test – test-homepage</title>
<link rel="alternate" type="application/rss+xml" title="test-homepage » Feed" href="http://test-homepage.de/feed/" />
<script type="text/javascript">
window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/72x72\/","ext":".png","source":{"concatemoji":"http:\/\/test-homepage.de\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.5.3"}};
This may be a solution if you want to stick to the currently used Wordpress plugin and output buffering is enabled (both webserver and php.ini may control output buffering; see the output buffering section on the PHP.net page for more details.
<?php
if(isset($_POST['button']))
{
// make sure that output buffering has been enabled
if (ob_start()) {
// clear previous contents from the server output cache
ob_clean();
try {
require_once("dompdf/dompdf_config.inc.php");
spl_autoload_register('DOMPDF_autoload');
$filename = 'file_name';
$paper= 'A4';
$orientation= 'portrait';
$dompdf = new DOMPDF();
$dompdf->set_paper($paper, $orientation);
$dompdf->load_html('TEST');
$dompdf->render();
$dompdf->stream($filename.".pdf");
// make sure the content of the buffer is sent to the client.
ob_flush();
// terminate the script to make sure no additional content is sent.
exit(0);
} catch (Exception $ex) {
error_log(sprintf("PDF generation failed with %s in line %d", $ex->getMessage(), $ex->getLine()));
}
} else {
// log a message in default error log
error_log("Output buffering could not be enabled (PDF routine)");
}
}
?>
Debugging your setup
As you said you are pretty new to PHP, please create a file with the content:
<?php
phpinfo();
Upload the file to your server and open the file with your browser, scroll down until you find "Configuration" > "PHP Core". In the list below, search for the entry "output_buffering". If it is set to "0", output buffering has been disabled via php.ini. If it has been disabled, all output of your page is directly send to the client and there is no programmatic way to do what you achieve without changing the server setup.
There may be several ways to enable buffering, i.e. your provider may allow changing certain settings via web configuration software or you may add an .htaccess file to your web directory to enable it as described here.
Another update
As you already found out, output buffering has been enabled properly, so we should be able to modify the output buffer to create the PDF even if output had been served before. I copied your code, ran the PHP part after some output had already been sent to the browser and the same happened as on your web page, the static HTML content was also included in my PDF document. The main problem will be that Wordpress does not use output buffering internally and sends the output directly to the browser.
Here's what I did that resolved the problem -> start the output buffering as soon as possible, inside your index.php:
<?php ob_start(); ?>
After buffering had been enabled, I was able to control the buffer and generate the PDF file as required.
Further diagnosis
I just want to make sure we are not missing something, could you add this to your PDF generation code:
if(isset($_POST['button']))
{
$sent = headers_sent($file, $line);
die("The output started in {$file} and at line {$line}");
}
Related
My PDF only displays after I refresh the page, otherwise it turns into weird symbols. When it does display, its fullscreen (header disappears) and when I press go back, the URL changes, but the page still displays the DPF, and when I refresh, this fixes itself again.
Im also using JQuery Mobile, maybe this has something to do with it.
Here is some code:
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hondensectie</title>
<link rel="stylesheet" href="themes/themerollertest.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link type="text/css" rel="stylesheet" href="css/style.css"/>
This is the head ^^
<div data-role="page" data-theme="a">
<div data-role="header" style="overflow:hidden;" data-position="fixed">
<h1>PDF Maker</h1>
Back
Home
</div>
<div data-role="content" data-theme="a">
<div data-role="collapsible" data-content-theme="a">
<h4>Gebruikers</h4>
<p>
<section id="hondppp" data-ajax='false'>
<?php
ob_start();
//call the FPDF library
require('fpdfmap/fpdf.php');
//A4 width : 219mm
//default margin : 10mm each side
//writable horizontal : 219-(10*2)=189mm
//create pdf object
$pdf = new FPDF('P','mm','A4');
//add new page
$pdf->AddPage();
$pdf->Output();
ob_end_flush();
?>
</section>
</p>
</div>
</div>
Right before you call the output function use the ob_end_clean function to remove and discard any other output that may have already been sent to the browser.
$pdf = new FPDF('P','mm','A4');
$pdf->AddPage();
ob_end_clean(); // clear out anything that may have already been output
$pdf->Output();
When you want to display a PDF file, the server has to return a response that contains Content-Type: application/pdf header in it. As far as I know, FPDF sets this header when Output function is called. However, no headers can be set after the response is sent, and this usually happens with the first line of HTML being displayed with your PHP script. Actually I'm surprised that you can ever see the PDF, and that you don't get the infamous "headers already sent" error (although that one probably shows somewhere in the logs, if you know where to look).
The point is, don't write any HTML before or after the PDF content. Your entire PHP script should just contain these lines:
//call the FPDF library
require('fpdfmap/fpdf.php');
//A4 width : 219mm
//default margin : 10mm each side
//writable horizontal : 219-(10*2)=189mm
//create pdf object
$pdf = new FPDF('P','mm','A4');
//add new page
$pdf->AddPage();
$pdf->Output();
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
Warning: Cannot modify header information - headers already sent by
(output started at
C:\wamp\www\ecommerce\base\classes\baseconfig.php:23) in
C:\wamp\www\ecommerce\base\classes\adminHelper.php on line 6
I know the root cause for the above warning. But iam not able to reslove it. My problem is different from other questions and many down-voted and closed topics.
The warning page is : index.php, is the only page that im dealing
with displaying and Setting data. this warning is shown when i called header('Location') on helper adminHelper.php
Im using a class coreConfig.php which sets and
gets the data for the index page.
And some helper classes too.
with the index page im using the same form , Same functions , same routines for setting data in a form. only data changes with the passed argument.
and this page works perfectly with all other set of data, except for one.showing the above warning. i cannot figure it out why this happens.
im formatting the output by using this function
public $mainTabLength = "\t";
public $tabLength = "\t\t";
public function printFormat($text, $class) {
if($this->useDivToPrint) {
echo $this->mainTabLength . "<div class=\"$class\">" . $this->tabLength . "$text\n";
echo $this->mainTabLength . "</div>\n";
}
else{
echo $text;
}
}
I dont want to use buffering of the codes too .. awaiting comments .
Note : I had formatted my php code by removing any white-spaces from the IDE
Update :
The problem was solved by inspecting the buffer output.As expected my code was setting some header information already before im calling header('Location'). But i was sure that i was not doing such a mistake, because my all other piece of data is working fine. But i was surprised to see the output of buffer for working set of data and the one that caused the warning :
form 1: adding new category (working fine header('Location'))
even i can see the following header information already sent :
<!DOCTYPE HTML>
<html>
<head>
<title>E-Commerce</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link href="../css/style.css" media="screen" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="../images/favicon.png"/>
<script type="text/javascript" language="javascript" src="../jses/jquery-1.11.3.min.js"></script>
<script type="text/javascript" language="javascript" src="../jses/scripts.js"></script>
<script type="text/javascript" language="javascript" src="../jses/datePicker.js"></script>
form 2: adding new product (not working header('Location') causing warning)
i can see the same header information already sent :
<!DOCTYPE HTML>
<html>
<head>
<title>E-Commerce</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link href="../css/style.css" media="screen" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="../images/favicon.png"/>
<script type="text/javascript" language="javascript" src="../jses/jquery-1.11.3.min.js"></script>
<script type="text/javascript" language="javascript" src="../jses/scripts.js"></script>
<script type="text/javascript" language="javascript" src="../jses/datePicker.js"></script>
This was the root cause that i was not able to detect a problem with my code.
why it worked for my form1 even though it already sent some header information already !!
Like I said in the comments, the issue is that you are having some output being sent before the call to header which is a no-no. This could include:
output from any included files, inlcuding all below and regardless of depth of included file (included file that includes another file that includes another file...etc).
a newline/space before or after <?php or ?> tags.
echo'ing anything.
even html output from outside of php tags.
a php error or warning.
These, and more, will all output something and will be considered "output before call to header". Because some of it can be hard to see, you might not even see it when viewing a page.
Your options are to either turn on output buffering or find some way to not display output during this request.
If you want to see what is being output (might help find the issue), you can do something like this for testing:
in the first line of the first script being requested (likely index.php, whatever file is requested by the browser), add a call to ob_start() right after <?php. If your file doesn't start with <?php then that is your problem right there.
on the line right before the call to header where you are getting your error, add something like file_put_contents("output.txt", ob_get_contents());.
This will get whatever output there was and write to to a text file. The file will likely run without errors this time (you did just turn on buffering) but it should still write any output. Also remember, it might just be a space or newline written. So if you open the file and see nothing, make sure to check if some non-display character was written.
Now it is just a matter of leaving on buffering or finding and removing that extra space.
I am currently trying to implement a PHP page that will generate a code when a user clicks a button. The code will be generated on the fly, and then the PHP page will trigger a download file that will prompt the user to save the text file on their machine.
After reading numerous posts, I am using this bit of code which is short, concise and does exactly what I need:
{
$result = "Your code is: " . $_POST['req_code'];
header('Content-disposition: attachment; filename=code.lic');
header('Content-type: text/plain');
echo $result . "\n";
}
However, the downloaded file does not only contain the code, it also contains all the HTML from the current page. Below is just a fraction of what is included in the file:
<!DOCTYPE html>
<html lang="en-CA">
<head>
<meta charset="UTF-8" />
<title>My Account | ...
I have tried using the "exit();" function to terminate the stream but it still outputs all the HTML.
Does anyone know what I'm doing wrong here? The file should only contain the contents of $result.
Thank you in advance.
Although this is an old thread, there are search results that still direct to here. So to answer the original question (sort of) by giving a simple stand-alone example that works, here goes:
Create two files, 'index.php' and 'redirect.php'
index.php:
<?php
$head = <<<EOHEAD
<head>
<title>Download document test</title>
<meta http-equiv="Content-Type" content="txt/html; charset=utf-8" />
</head>
EOHEAD;
$body = <<<EOBODY
<body>
<form action="redirect.php" method="post" id="mainform">
<input type="submit" name="download" value="Download"/>
<input type="submit" name="cancel" value="Cancel"/>
</form>
</body>
EOBODY;
echo $head.$body;
?>
redirect.php:
<?php
if (isset($_POST['download'])) {
header('Content-disposition: attachment; filename=test.txt');
header('Content-type: text/plain');
echo "Hello World\n";
}
else {
header("location:index.php");
}
?>
You need to either a) Make a new page to download the file (without any HTML) or b) Remove all HTML from the current page. Also, you are not supposed to send any content before calling header():
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP
Reference: http://php.net/manual/en/function.header.php
You do not have to delete all HTML code from download site, but there cannot be ANY HTML code before function, that downloads your files. Put your code ad the top of the page and it should be fine
I have a site that is functioning fine, but just by refreshing the main page (index_3.php) my error log populates with two warnings.
[08-Oct-2013 11:36:09] PHP Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cache limiter - headers already sent (output started at /home2/mysite/public_html/mysubsite/index_3.php:7) in /home2/mysite/public_html/mysubsite/functions.php on line 12
[08-Oct-2013 11:36:09] PHP Warning: session_regenerate_id() [<a href='function.session-regenerate-id'>function.session-regenerate-id</a>]: Cannot regenerate session id - headers already sent in /home2/mysite/public_html/mysubsite/functions.php on line 13
I have researched enough to understand that something is sending the page data before the session begins, but I can't seem to root out the cause. functions.php is taken right from this tutorial site under "Create PHP Functions." http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Also loading on index_3.php is get_opwire.php which just places a table. The beginning of get_opwire.php looks like:
<?php
include 'db_connect.php';
include 'functions.php';
sec_session_start();
sec_session_start(); is a custom session start located in functions.php
When I try to rearrange the order of the sec_session to the top or shift those around the table breaks. Index_3.php is just the main page, mostly html that has includes for a submit form and get_opwire.php
Would someone be able to help point me to the problem?
Edit: index_3.php (from line 1 through )
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252"/>
<meta name="Generator" content="Xara HTML filter v.6.0.1.335"/>
<meta name="XAR Files" content="index_htm_files/xr_files.txt"/>
<title>index_3</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" type="text/css" href="index_htm_files/xr_main.css"/>
<link rel="stylesheet" type="text/css" href="index_htm_files/xr_text.css"/>
<link rel="stylesheet" type="text/css" href="index_htm_files/custom_styles.css"/>
<script type="text/javascript" src="index_htm_files/roe.js"></script>
<!--[if IE]><script type="text/javascript" src="index_htm_files/prs.js"></script><![endif]--><!--[if !IE]>--><script type="text/javascript" src="index_htm_files/prs3.js"></script><!--<![endif]-->
<script type="text/javascript">var xr_nextpage=""; var xr_transition=0; var xr_transitiontime=0;var xr_prevpage="index_2.htm"; var xr_btransition=0; var xr_btransitiontime=500;</script>
<style type="text/css">.xr_pbd {position: absolute; border:none; left: 50%; margin-left: -380px;}</style>
</head>
EDIT 2: somewhere inside index_3.php
<html>
<body>
<div style="width: 480px; height: 175px; overflow: auto;">
<?php include 'get_opwire.php'; ?>
</div>
</body>
</html>
Try removing the closing ?> tag from all your included php files.
Something somewhere before session start and session regenerate id is putting something on the page. If you are sure you're not echoing or printing anything to the page, it's probably a blank space at the top of one of the files.
EDIT 1
Some text editors/word processors save files with extra invisible characters at the top due to encoding. Try copying and pasting the text of the files into new files in a plain text editor or text editor recommended for coding, such as Notepad++.
EDIT 2
So, those were the most likely solutions.... It says
output started at /home2/mysite/public_html/mysubsite/index_3.php:7
which means that it's line 7 of index_3.php where the output starts at. There is probably a space there or maybe some kind of error that causes output to be sent.
If you really can't find that invisible output, you can use buffering with ob_start etc. to catch all output. Put ob_start before your session start and use ob_end_flush later to display the page. But that's not a real fix for the fact that you're sending output without knowing it.
EDIT 3: "No output" includes any and all HTML.
If there's something in any file that is not inside PHP brackets <?php ?> then that counts. Your index_3.php file starts with HTML. That is output. You have to do get_opwire.php first.
EDIT 4
Concerning how get_opwire.php has both page-start stuff and the table printout, it's an example of why it's a good idea to separate your display code from your functionality code. You have three options:
Have separate files. You would have a file like page_start.php that does includes and session_start that you include at the very top of index_3.php, and a file like display_table.php that displays your table that you include where the table goes.
Turn the table into a function. You would wrap the table output inside a function, include get_opwire.php at the very top of index_3.php, then call the function down where you want the table.
Use output buffering. Output buffering catches the stuff printed out so that you can use it later. It would go like this:
top of index_3.php:
ob_start();
include get_opwire.php;
$table = ob_get_contents();
ob_end_clean();
where the table goes:
echo $table;
I'm not able to get my PDF printed if I add a logo in my template_header.php file.
If I enable include_once("template_header.php") it's not generating any PDF, and it reports this error message:
PHP Fatal error: Call to undefined function imagecreatetruecolor()
If I disable my header (i.e. above the include_once line) it's generating a PDF without a logo and containing text only.
I tried enabling below, but the same problem persists:
define("DOMPDF_ENABLE_REMOTE", true);
My dompdf ver. is dompdf_0-6-0_beta3.
Can anyone help me on this?
Below is the updated code
require_once("dompdf/dompdf_config.inc.php");
$dompdf = new DOMPDF();
$html = '
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>booking</title>
<link rel="stylesheet" href="style/style.css" type="text\css" media="screen" />
</head>
<body>
<div align="center" id="mainwrap">
<?php include_once("template_header.php")?>
</div>
</body>
</html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("sample.pdf");
Please check your GD library installation in php.
Run <?php phpinfo(); ?> in a php file and check for GD library then
Update -
Check your php.ini and look for extension=php_gd2.dll
If ; [commented] then un comment it and restart the services then.