I use wkhtmltopdf with php, and it works well.
Now, i want to add some variables from the php file to the html one, but i don't find a solution.
the PHP file:
<?php
require '/path/vendor/autoload.php';
use mikehaertl\wkhtmlto\Pdf;
$pdf = new Pdf(array(
'no-outline',
'margin-top' => 0,
'margin-right' => 0,
'margin-bottom' => 0,
'margin-left' => 0,
// Default page options
'disable-smart-shrinking',
));
if($_GET['file'] == 'public'){
$pdf = new Pdf('template_public.html');
}else{
$pdf = new Pdf('template_pro.html');
}
$pdf->send();
?>
The HTML file:
<html>
<head>
<title>Generated PDF file</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<div>
{title}
</div>
</body>
</html>
How can i replace the {title} in the HTML file?
This should replace all of the {variables} in the html files with their values, given an array of parameters.
$params = ["title"=>"title_val", "content" => "something", "key" => "value"];
$pdf = new Pdf();
$html = file_get_contents($templateFile);
foreach($params as $key=>$value) {
$html = str_replace("{".$key."}", $value, $html);
}
//Renders the pdf directly from the html string, instead of loading the file directly
$pdf->addPage($html);
$pdf->send();
Refer this for setting page options.
https://github.com/mikehaertl/phpwkhtmltopdf#setting-options
You can set title,page number etc...
Use addPage option to apply page options to specific page.
My task is to pass real client ip value to pdf. When I read IP as $ENV{REMOTE_ADDR} I got server IP, not client IP.
I use this code to solve the problem:
wkhtmltopdf --cookie remote_addr $IP
It passes IP variable to pdf. Then, my html page can read cookie values and show them inside text.
Related
lets assume that I want to organize my pages as following:
<?php include('header.inc.php'); ?>
my-page-content
<?php include('footer.inc.php'); ?>
in the header we have .css files and in the footer we have .js files.
how do I do if I want to load only the CSS and JS that the current page needs?
for example, on the article page I don't need to load the JS resources that manage maps and calendar.
Personally, I think it is useless to insert other files into html that will never be used - for cache management purposes. The smaller the html cache space used, the more efficient and powerful the html page will be.
Consider the following example:
file: library.php
<?php
function includeFiles(string $typeFile, array $source_arr, array $request_file): array
{
$tmp = [];
$element = $typeFile === "css" ? "<link rel=\"stylesheet\" href=\"%s\">" : "<script src=\"%s\"><script>";
foreach ($request_file as $file) {
if (array_key_exists($file, $source_arr)) {
array_push($tmp, [sprintf($element, "https://example.com" .$css[$file])]);
}
}
return count($tmp) > 0 ? $tmp : false;
}
// Make a list of all .js and .css files using the php array:
$css = [
// List all the .css files you are using here
"css1" => "/css/css1.css",
"css2" => "/css/css2.css",
"css3" => "/css/css3.css",
"css4" => "/css/css4.css",
"css5" => "/css/css5.css"
];
$js = [
// List all the .js files you are using here
"js1" => "/js/js1.js",
"js2" => "/js/js2.js",
"js3" => "/js/js3.js",
"js4" => "/js/js4.js"
];
?>
file: main_html.php
<?php
include "library.php";
$css_files = ["css1", "css3", "css5"];
$headers = implode(PHP_EOL, includeFiles("css", $css, $css_files));
$js_files = ["js1", "js3", "js5"];
$footer = implode(PHP_EOL, includeFiles("js", $js, $js_files));
?>
<!-- Here html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<?php echo $headers; ?>
<!-- and other your required head element parameters -->
</head>
<body>
<!-- includes .js files -->
<?php echo $footer; ?>
</body>
</html>
Sketched out a PHP page to pull data from a DynamoDB table. The page pulls a field with XML data, submissionMessageSent, and displays it twice.
First Occurrence: Looks like the data with the XML tags missing.
Second Occurrence: Looks like the data with the XML tags in place.
Between the two occurrences the variable isn't updated by code in the page. The data is stored w/tags in Dynamo as a big old string.
Why are the XML tags stripped out in one case but not the other?
<html>
<head>
<title>Spyglass</title>
<link rel="stylesheet" type="text/css" href="./style.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="get">
Submission Identifier: <input name="submission_id" type="submission_identifier" size="45" value="<?php $submissionId ?>"/>
<input type="submit">
</form>
<?php
date_default_timezone_set('UTC');
$configs = include('./config.php');
require './vendor/autoload.php';
use Aws\DynamoDb\Exception\DynamoDbException;
use Aws\DynamoDb\Marshaler;
if ( isset($_GET["submission_id"]) && $_GET["submission_id"] != "" ) {
$aws_credentials = new Aws\Credentials\Credentials(
$configs['aws_account_key'],
$configs['aws_account_secret']
);
$sdk = new Aws\Sdk([
'region' => $configs['aws_region_identifier'],
'version' => "2012-08-10",
'credentials' => $aws_credentials
]);
$dynamodb = $sdk->createDynamoDb();
$marshaler = new Marshaler();
$ddb_query_predicate = '{":id": "' . $_GET["submission_id"] . '"}';
$eav = $marshaler->marshalJson($ddb_query_predicate);
$params = [
'TableName' => "Orders",
'KeyConditionExpression' => '#submissionId = :id',
'ExpressionAttributeNames'=> ["#submissionId" => "submissionId"],
'ExpressionAttributeValues' => $eav
];
try {
$submissionQueryResponse = $dynamodb->query($params);
$submission = $submissionQueryResponse['Items'][0];
$submissionObject = $marshaler->unmarshalItem($submission, true);
// Extract the message sent to the ERP system by the preprocessor
$submissionMessageSent = $submissionObject->submissionMessageSent;
echo "<p><b>1:</b> $submissionMessageSent</p>";
echo <<<EOT
<textarea id="sent" wrap="off" placeholder="Sent" rows="20" cols="75">$submissionMessageSent</textarea>
EOT;
} catch (DynamoDbException $e) {
echo "Unable to query:\n";
echo $e->getMessage() . "\n";
}
}
?>
</body>
</html>
NOTE: Complete disclosure. I had to pull out portions of the page's code to not disclose sensitive information. Don't crucify me if I missed a tag some place in the purge. You get the gist of my problem.
Your XML is rendered as HTML, they are ignored by the webbrowser. It possible to see them within the textarea as this will escape the tag's characters.
The tags will be there when viewing the raw html output.
So I'm a bit stuck, and I've been given various solutions, none of which work. Any hotshot PHP folks out there? Here's the deal, I'm trying to get an image to display on my website, from another website, that has a randomly generated IMG. Though I'm actually trying to do this off a personal art site of mine, this example will serve perfectly.
http://commons.wikimedia.org/wiki/Special:Random/File
A random image page with an image on it pops up with that link. Now, I'd like to display THAT random image, or whatever image comes up, on another site. The two possible solutions I have encountered is gathering an array of URL LINKS from a given link. And then re displaying that array as images on another site, like a: < a href="https
The code I get back from what I'm talking about looks like this:
Array
(
[0] => https ://kfjhiakwhefkiujahefawef/awoefjoiwejfowe.jpg
[1] => https ://oawiejfoiaewjfoajfeaweoif/awoeifjao;iwejfoawiefj.png
)
Instead of the print out however, I'd like the actual images displayed, well specifically array [0], but one thing at a time. The code that's actually doing this is:
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
$url = 'http://commons.wikimedia.org/wiki/Special:Random/File';
// Fetch page
$string = FetchPage($url);
// Regex that extracts the images (full tag)
$image_regex_src_url = '/<img[^>]*'.
'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex, $string, $out, PREG_PATTERN_ORDER);
$img_tag_array = $out[0];
echo "<pre>"; print_r($img_tag_array); echo "</pre>";
// Regex for SRC Value
$image_regex_src_url = '/<img[^>]*'.
'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex_src_url, $string, $out, PREG_PATTERN_ORDER);
$images_url_array = $out[1];
echo "<pre>"; print_r($images_url_array); echo "</pre>";
// Fetch Page Function
function FetchPage($path)
{
$file = fopen($path, "r");
if (!$file)
{
exit("The was a connection error!");
}
$data = '';
while (!feof($file))
{
// Extract the data from the file / url
$data .= fgets($file, 1024);
}
return $data;
}
for($i=0; $i<count($arr1); $i++) {
echo '<img src="'.$arr1[$i].'">';
}
?>
Solution two,
Use a file_get_contents command. Which is this:
<?php
$html =
file_get_contents("http://commons.wikimedia.org/wiki/Special:Random/File");
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$image_src = $xpath->query('//div[contains(#class,"fullImageLink")]/a/img')
[0]->getAttribute('src') ;
echo "<img src='$image_src'><br>";
?>
However, there's unfortunately an error message I get: Fatal error: Cannot use object of type DOMNodeList as array in /home/wilsons888/public_html/wiki.php on line 11. Or, if I remove a "}" at the end, I just get a blank page.
I have been told that the above code will work, but with openssl extension included. Problem is, I have no idea how to do this. (I'm very new to PHP). Anyone know how to plug it in, so to speak? Thank you so much! I feel like I'm close, just missing the last element.
I was able to load the random image, and "print it" as an image directly (so you can embed the php file directly on the IMG tag) using this code:
<?php
$html = file_get_contents("http://commons.wikimedia.org/wiki/Special:Random/File");
$dom = new DOMDocument();
$dom->loadHTML($html);
$remoteImage = $dom->getElementById("file")->firstChild->attributes[0]->textContent;
header("Content-type: image/png");
header('Content-Length: ' . filesize($remoteImage));
echo file_get_contents($remoteImage);
?>
Get a new file called showImage.php and put this code in it:
<!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=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<img src="test.php">
</body>
</html>
Next, go to your browser and get the showImage.php path, and will show a random image fromt he site you asked...
I want to parsing data from homepage on this url. As you can see this url is HTML file and I read below:
// Create a DOM object from a HTML file
$html = file_get_html('test.htm');
so I just type a code below
include "simple_html_dom.php";
$html = file_get_html('eecs.kookmin.ac.kr/site/computer/notice.htm');
echo $html->plaintext;
The error message is:
Error message Warning: file_get_contents(eecs.kookmin.ac.kr/site/computer/notice.htm): failed to open stream: No such file or directory in C:\Bitnami\wampstack-5.6.27-0\apache2\htdocs\simple_html_dom.php on line 76
what should I do?
You can get the HTML code using the Snoopy Class (https://sourceforge.net/projects/snoopy). Next code displays the HTML code inside of a <textarea> tag, then it displays the page itself, copy-paste next code in a PHP file and open it in your browser:
<!DOCTYPE html>
<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=euc-kr">
<META HTTP-EQUIV="Content-language" CONTENT="ko">
</head>
<body>
<?php
require("Snoopy.class.php"); // ◄■■ GET SNOOPY FROM https://sourceforge.net/projects/snoopy
$snoopy = new Snoopy;
$snoopy->fetch("http://eecs.kookmin.ac.kr/site/computer/notice.htm");
$html = mb_convert_encoding( $snoopy->results, "UTF-8", "EUC-KR" ); // ◄■■ GET HTML CODE.
echo "<textarea rows='25' cols='80'>$html</textarea>"; // ◄■■ DISPLAY THE HTML.
echo $html; // ◄■■ DISPLAY THE WEBPAGE.
?>
</body>
</html>
The Snoopy Class is only one file, make sure the file is in the same directory your PHP file is.
I am using HTML2PDF library of PHP to create PDF from HTML. My page url is as below ::
http://domain.com/admin/invoice/invoicedownload
To create pdf using below code ::
ob_start();
$width_in_mm = 240;
$height_in_mm = 250;
$html2pdf = new HTML2PDF('P', array($width_in_mm,$height_in_mm), en, true, 'UTF-8', array(15, 10, 15, 10));
$html2pdf->setDefaultFont('Arial');
$html2pdf->pdf->SetTitle('Invoice Details');
$html2pdf->writeHTML($pdf_template);
$html2pdf->Output($file_name,'I');
die();
This code open pdf view in browser new tab.
Issue I am facing is that that new tab title is set as "Invoice Details - invoicedownload" but I want it as "Invoice Details". Always url's last part is append in title.
Please help me for this.
Thank you in advance.
In order to define your own tab title, you can use the 'embed' html tag.
File n°1 (main):
html, body, embed
{
width: 100%;
height: 100%;
}
body
{
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Your title</title>
</head>
<body>
<embed src=/path-to-your-pdf type='application/pdf'/>
</body>
</html>
File n°2 (/path-to-your-pdf):
<?php
$html2pdf = new Html2Pdf('P, 'A4', 'en');
$html2pdf->writeHTML($pdf_template);
$html2pdf->output();
Hope this helps ;)