HTML2PDF How to pass id to the html site to be converted - php

I´ve started using HTML2PDF (https://www.html2pdf.fr/) to create invoices, now the following code works:
try {
ob_end_clean();
ob_start();
include('../faktura/fa.php');
$html = ob_get_contents();
ob_end_clean();
$content = $html;
$html2pdf = new Html2Pdf('P', 'A4', 'cs',true,"UTF-8");
$html2pdf->setDefaultFont('freeserif');
$html2pdf->pdf->SetFont('freeserif');
$html2pdf->writeHTML($content);
$pdfContent = $html2pdf->output('my_doc.pdf', 'S');
} catch (Html2PdfException $e) {
$html2pdf->clean();
$formatter = new ExceptionFormatter($e);
echo $formatter->getHtmlMessage();
}
The content of fa.php is converted to pdf, however if I change one of the lines to:
include('../faktura/fa.php?id=105');
note that I only added ?id=105, it returns only a blank page.
The php file fa.php includes:
$id = (int) $_GET['id'];
What I need to do is to pass an ID to that php script so the invoice of the exact order is generated.

Include basically means "copy the code from that file to here".
So if you change the included file code from $id = (int) $_GET['id']; to $id = $thatId;
And prior to the include() function you'd write $thatId = 105;
The included file will be able to access the variable.
File A:
$id = 105;
include('../faktura/fa.php');
File fa.php
//$id = (int) $_GET['id']; // no need this anymore as we've declared a $id variable with a value;
// .. Do something with $id
// .. for example:
echo $id; //will print 105
Or, in case you want fa.php to continue working with QUERY PARAMETER and to work with your invoice (2pdf) code:
if(!isset($id) && isset($_GET['id'])) {
$id = (int) $_GET['id'];
}

Related

Web scraping information from the site in PHP

I do PHP script, the script must copy the list of publications (from the homepage) and copy the information that is inside these publications.
I need to copy content from my previous site and add the content to the new site!
I have some success, my PHP script copies the list of publications on the home page. I need to make a script that pulled information inside each publication (title, photo, full text)!
For this, I wrote a function that extracts a link to each post.
Help me write a function that will copy information on a given link!
<?php
header('Content-type: text/html; charset=utf-8');
require 'phpQuery.php';
function print_arr($arr){
echo '<pre>' . print_r($arr, true) . '</pre>';
}
$url = 'http://goruzont.blogspot.com/';
$file = file_get_contents($url);
$doc = phpQuery::newDocument($file);
foreach($doc->find('.blog-posts .post-outer .post') as $article){
$article = pq($article);
$text = $article->find('.entry-title a')->html();
print_arr($text);
$texturl = $article->find('.entry-title a')->attr('href');
echo $texturl;
$text = $article->find('.date-header')->html();
print_arr($text);
$img = $article->find('.thumb a')->attr('style');
$img."<br>"; if (preg_match('!background:url.(.+). no!',$img,$match)) {
$imgurl = $match[1];
} else
{echo "<img src = http://goruzont.blogspot.com".$item.">";}
echo "<img src='$imgurl'>";
}
?>

PHP: Fatal error: Call to a member function appendChild() on a non-object in

I am trying to use data entered by the user to store it into an XML Database file for use further down the line. However, for some reason I continue to get this error.
The problem code is summarised below and the whole PHP file is below that for context.
I have tried converting the integer I got (I was using mt_rand() before using uniqid()) using strval(), also tried Type Casting to (string), even tried Type Casting to (object). All no luck. uniqid() returns a string already. In fact, the error returned when I try Type Casting to object (both from uniqid() and mt_rand()) was different, and made life confusing:
[![Error 2 Where the output of idGenerated is an object][2]][2]
Why oh why does a createTextNode hate Strings, Integers AND Objects?? And why do the other variables in the file (undergoing the SAME process) pass by absolutely fine?
Summarised Problem Code
$idGenerated = uniqid();
$dom = new DOMDocument();
$dom->load('../test.xml');
$idDec = $dom->createTextNode($idGenerated);
$id->appendChild($idDec);
$messageElement->appendChild($id);
Whole File:
<?php
session_start();
//Generate random number to avoid overwrite of file
$randomNumber = mt_rand(10, 99);
move_uploaded_file($_FILES['attachment'][tmp_name], "../uploads/" . $randomNumber . $_FILES['attachment'][name]);
//General Variables
***$idGenerated = uniqid();***
$currentDate = date('l jS \of F h:i:s A');
$sender = $_SESSION['user'];
$message = $_POST['messageText'];
$up_file = $randomNumber . $_FILES['attachment'][name];
$up_file_location = "uploads/" . $up_file;
echo "<br>";
var_dump($currentDate);
echo "<br>";
var_dump($sender);
echo "<br>";
var_dump($message);
echo "<br>";
var_dump($up_file);
echo "<br>";
var_dump($up_file_location);
$dom = new DOMDocument();
$dom->load('../test.xml');
//Dom Variable Declarations
//Declare String Data
***$idDec = $dom->createTextNode($idGenerated);***
$date = $dom->createTextNode($currentDate);
$name = $dom->createTextNode($sender);
$messageText = $dom->createTextNode($message);
$link = $dom->createTextNode($up_file_location);
$linkName = $dom->createTextNode($up_file);
//Declare Data Elements
$id = $dom->createElement('id');
$timecode = $dom->createElement('timecode');
$author = $dom->createElement('author');
$content = $dom->createElement('content');
$filePath = $dom->createElement('filePath');
$fileName = $dom->createElement('fileName');
$messageElement = $dom->createElement('message');
//Create XML Data Structure
//ID
***$id->appendChild($idDec);***
//Date
$timecode->appendChild($date);
//Name
$author->appendChild($name);
//Message
$content->appendChild($messageText);
//File (if there is one!)
$filePath->appendChild($link);
$fileName->appendChild($linkName);
//Message Wrapper Element
***$messageElement->appendChild($id);***
$messageElement->appendChild($timecode);
$messageElement->appendChild($author);
$messageElement->appendChild($content);
$messageElement->appendChild($filePath);
$messageElement->appendChild($fileName);
//Load last existing XML entry for reference (which, since they are all in reverse order, will actually be the FIRST entry in the database)
$xml = simplexml_load_file('../test.xml');
$lastEntry = $xml->log->message[0];
//Place new data BEFORE the last existing message Element
$newEntry = $dom->firstChild->appendChild($messageElement);
$lastEntry->parentNode->insertBefore($newEntry, $lastEntry);
$dom->save('../test.xml');
header("Location: ../index.php");
?>
Whenever you get Call to a member function … on a non-object, you’re using something as an object which at the time of calling is not an object. (This often seen in loops where you access a array element, expecting it to be an object when it’s not.)
But in your case, it’s simply the fact that $messageElement is not defined. Maybe you copy/pasted the code from somewhere else and forgot to copy the initial definition/initialisation of the $messageElement variable.

Passing variables from controller to view that works with DOMPDF in CodeIgniter

Best regards!
Today I'm with an issue trying to generate invoices in PDF with DOMPDF.
Let's explain:
I have a view that i select the invoice id. When I click the "generate PDF" button it goes this way:
(takes you to controller)
foreach ($this->input->post('check') as $key)
{
$testLayout = load_modulo('bankX', 'invoice_bankX'); //here I call the file in views dir(bankX) and the view inside the file (case 'invoice_bankX') that brings me the bank invoice layout
$filename = 'invoice_'.$key;
pdf_create($testLayout, $filename, TRUE);
}
(the load_modulo function)
function load_modulo($modulo = NULL, $tela = NULL, $diretorio = 'panel') {
$CI = & get_instance();
if ($modulo != NULL) {
return $CI->load->view("$diretorio/$modulo", array('tela' => $tela), TRUE);
} else {
return FALSE;
}
}
(the pdf_create function)
function pdf_create($html, $filename = '', $stream = TRUE) {
require_once("dompdf/dompdf_config.inc.php");
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
if ($stream) {
$dompdf->stream($filename . ".pdf");
} else {
$output = $dompdf->output();
file_put_contents('Brochure.pdf', $output);
}
Now knowing that I have more data to pass through to the 'invoice_bankX' view (I need 1 var that retain the bank and client values that I can callback in this view to mount the invoice with the client and store datas )
i.e.
$invoiceData = array();
$invoiceData['invoice_number'] = 344;
$invoiceData['client_name'] = 'John Masters';
Because this way I can pass the values to mount the invoice correctly.
Anyone knows how to?
*note - right now, if I click the button to generate invoice(PDF), this works. But the invoice comes with the static data that I wrote to test
I found a way to do this by setting the number of the invoice on session.
The controller now looks like this and it works:
foreach ($this->input->post('check') as $key)
{
$dataInvoice = array('invoice_number' => $key);
$this->session->set_userdata($dataInvoice);
$testLayout = load_modulo('bankX', 'invoice_bankX');
$filename = 'invoice_'.$key;
pdf_create($testLayout, $filename, TRUE);
}
So that way I could call at the view the
$invoice_number = $this->session->userdata('invoice_number');
and do all the queries that i want

How to convert dynamic php file which accepts data from database to pdf?

I am working on WordPress website. And on front-end I am giving the functionality to create a resume online & on submitting the form he will get a option to download & print the resume in PDF format. Till now everything is working fine If I am passing a simple html file to convert into PDF. But I want to create a PDF out of the fields of resume inserted in the database. If I am passing the plain html file for conversion it works fine.
But what if I want to create a dynamic PDF file of the PHP file.
Here is my tried code:
I have used html2pdf conversion library for this.
This is a file from which the call to test.php goes.
require("html2pdf/html2fpdf.php");
$htmlFile = "test.php";
$buffer = file_get_contents($htmlFile);
$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('test.pdf', 'F');
And the test.php file is:
<html>
<body>
<?php
$username = "";
$password = "";
$hostname = "";
$dbname = "";
// Create connection
$con = mysqli_connect($hostname, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo $result = mysqli_query($con,"SELECT * FROM wp_resume ORDER BY id DESC LIMIT 1");
echo "hioooooo";
while($row = mysqli_fetch_array($result))
{
?>
<div>
<label>First Name</label><script type="text/php"><?php echo $row['firstName']; ?></script><br>
<label>Last Name</label><script type="text/php"><?php echo $row['lastName']; ?></script><br>
</div>
<?php
}
?>
</body>
</html>
Now after submitting the form I am getting a PDF file which contains only this data:
First Name
Last Name
And I want all the details of the entry inserted. Clearly this ignores the code inside the <?php ?> tags. So even if I used var_dump(), I didn't get anything.
SO please help me out in this guys. How can I pass the PHP data to PDF file.
Hey I got the solution for this. And the correct code is:
require("html2pdf/html2fpdf.php");
$html = '<h2>Resume</h2>';
$query = "SELECT * FROM wp_resume order by id desc limit 1";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$html .= '<div>
<label>First Name</label> '. $row['firstName'].'<br>
<label>Last Name</label> '. $row['lastName']. '<br>
</div>';
}
$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($html);
$pdf->Output('test.pdf', 'F');
I hope this will help somebody....
file_get_contents returns the content of a file, without it being parsed as PHP...
Replace
$buffer = file_get_contents($htmlFile);
With
ob_start();
include($htmlFile);
$buffer = ob_end_clean();
What we are doing: opening an output buffer (this prevents the echo from going to the client as they appear) then we include the PHP file so it gets parsed and all. Remember all the echo's are in the output buffer, so grab it with ob_end_clean() and use the generated HTML to make a PDF.

Concrete5 Load Area with Ajax

I am trying to pull area of a page with AJAX.
In JS I have on click I pass href to PHP;
in PHP(located in tools):
<?php defined('C5_EXECUTE') or die("Access Denied.");
$path = ($_POST['path']);
$page = Page::getByPath($path);
$a = new Area('Main');
$ret = $a->display($page);
echo json_encode($ret);
?>
If I make:
echo json_encode($page);
I receive the page so everything working, But when I try to receive an Area I get this error:
concrete\elements\block_area_header_view.php on line 5
In this File I found this
$c = Page::getCurrentPage();
$areaStyle = $c->getAreaCustomStyleRule($a);
So as I understand $c is null that why I have this error how can I fix this??
This line of code:
$ret = $a->display($page);
...does not do what you think it does. The "display" function does not return the content -- instead it outputs it to the browser. So your json_encode($ret) is just encoding and echo'ing an empty variable.
To capture the displayed content and put it into a variable, you can use php's output buffering feature, like so:
ob_start();
$a->display($page);
$ret = ob_end_clean();

Categories