I have a function which takes two parameters data(html),name. In the function i am trying to save the data in PDF file on my localhost/abc-folder. Unfortunately it runs fine but don't write in specific file or so..
Here is my code.
<?php
function pdf($data, $name) {
if (count($name) > 1) {
$name = "Orders";
} else {
$name = 'Order_'.$name[0]['order_id'];
}
$pdf = new DOMPDF;
$pdf->load_html($data);
$pdf->render();
$str=$pdf->output();
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/aabcd.pdf","wb");
fwrite($fp,$str);
fclose($fp);
}
?>
Related
I am using PDFTOHTML (a php library) to convert pdf files to html and it's working fine but it's showing converted file in a browser and not storing in local folder, i want to store converted html in local folder using php with the same name as pdf was i-e mydata.pdf to mydata.html
Code that is converting pdf to html is:-
<?php
// if you are using composer, just use this
include 'vendor/autoload.php';
$pdf = new \TonchikTm\PdfToHtml\Pdf('cv.pdf', [
'pdftohtml_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdftohtml.exe',
'pdfinfo_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdfinfo.exe'
]);
// get content from all pages and loop for they
foreach ($pdf->getHtml()->getAllPages() as $page) {
echo $page . '<br/>';
}
?>
Just change your foreach to
$filePdf = 'cv'; // your pdf filename without extension
$pdf = new \TonchikTm\PdfToHtml\Pdf($filePdf.'.pdf', [
'pdftohtml_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdftohtml.exe',
'pdfinfo_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdfinfo.exe'
]);
$counterPage = 1;
foreach ($pdf->getHtml()->getAllPages() as $page) {
$filename = $filePdf . "_" . $counterPage.'.html'; // set as string directory and filename where you want to save it
if (file_exists($filename)) {
// if file exist do something
} else {
// else
$fileOpen = fopen($filename, 'w+');
fputs($fileOpen, $page);
fclose($fileOpen);
}
$counterPage++;
echo $page . '<br/>';
}
This will create you file for example: example_1.html, example_2.html and so on.
if this not help you then probably you need to use file_put_contents with ob_start() and ob_get_contents() read more here
Look this :
<?php
// if you are using composer, just use this
include 'vendor/autoload.php';
$pdf = new \TonchikTm\PdfToHtml\Pdf('cv.pdf', ['pdftohtml_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdftohtml.exe', 'pdfinfo_path' => 'C:/wamp64/www/new/poppler-0.51/bin/pdfinfo.exe']);
// get content from all pages and loop for they
$file = fopen('cv.html', 'w+');
$data = null;
foreach ($pdf->getHtml()->getAllPages() as $page) {
$data .= "".$page."<br/>";
}
fputs($file, $data);
fclose($file);
I did not test this code
I'm new to Codeigniter and I need to export the mySQL data into a PDF file.
How can I do that?
Download library from here
Library explanation
After download extract folder You have you will find two files namely class.ezpdf.php/cezpdf.php and class.pdf.php. Now put these two .php files inside application/libraries. To make these work within CI you will have to a modification in the cezpdf.php/class.ezpdf.php. The modification is to be done in the include statement :
include_once(APPPATH . 'libraries/class.pdf.php');
Now go to your controller folder and there make a new file name generate.php and pdf_helper.php.
pdf_helper.php :
<?php
function prep_pdf($orientation = 'portrait')
{
$CI = & get_instance();
$CI->cezpdf->selectFont(base_url() . '/fonts');
$all = $CI->cezpdf->openObject();
$CI->cezpdf->saveState();
$CI->cezpdf->setStrokeColor(0,0,0,1);
if($orientation == 'portrait') {
$CI->cezpdf->ezSetMargins(50,70,50,50);
$CI->cezpdf->ezStartPageNumbers(500,28,8,'','{PAGENUM}',1);
$CI->cezpdf->line(20,40,578,40);
$CI->cezpdf->addText(50,32,8,'Printed on ' . date('m/d/Y h:i:s a'));
$CI->cezpdf->addText(50,22,8,'PDF Tutorial');
}
else {
$CI->cezpdf->ezStartPageNumbers(750,28,8,'','{PAGENUM}',1);
$CI->cezpdf->line(20,40,800,40);
$CI->cezpdf->addText(50,32,8,'Printed on ' . date('m/d/Y h:i:s a'));
$CI->cezpdf->addText(50,22,8,'PDF Tutorial');
}
$CI->cezpdf->restoreState();
$CI->cezpdf->closeObject();
$CI->cezpdf->addObject($all,'all');
}
?>
generate.php :
<?php
class Generate extends CI_Controller
{
function Generate()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
function create()
{
$this->load->library('cezpdf');
$this->cezpdf->ezText('PDF REPORT OF LOGIN TABLE', 12, array('justification' => 'center'));
$this->cezpdf->ezSetDy(-10);
$i=1;
$content="";
$fname="";
$query = $this->db->query('SELECT * FROM table_name');
$num = $query->num_fields();
$farr=array();
while($i <= $num){
$test = $i;
$value = $this->input->post($test);
if($value != ''){
$fname= $fname." ".$value;
array_push($farr, $value);
}
$i++;
}
$fname = trim($fname);
$fname=str_replace(' ', ',', $fname);
$this->db->select($fname);
$query = $this->db->get('table_name');
$result = $query->result();
foreach ($farr as $j)
{
$content= strtoupper($j)."\n\n";
foreach($result as $res){
$content = $content.$res->$j."\n";
}
$this->cezpdf->ezText($content, 10);
$this->cezpdf->ezStream();
}
}
In the above, first thing we do is load the R&OS library for use. Next we use the ezText() function to create a title for our document. This function takes the text it will display as the first argument, the size of that text and an optional array of additional configuration options.
After the whites pace we put the rest of the content for the document in a variable called $content and add it to our document using the ezText() function again. Finally, we create our document using the ezStream() function which actually creates the document and sends it to the users which prompts them to view/download the generated PDF document.
I have a getPass.php which creates a Pass instance. Here is the code:
//create new pass instance
$coupon = new Pass("pass/source");
//fill in dynamic data
$coupon->content['serialNumber'] = (string)uniqid();
$coupon->content['coupon']['secondaryFields'][0]['value'] =
(string)$_POST['name'];
$coupon->content['locations'][0] =
$locations[(int)$_POST['location']];
$coupon->writePassJSONFile();
$coupon->writeRecursiveManifest();
$coupon->writeSignatureWithKeysPathAndPassword("pass", '12345');
$fileName = $coupon->writePassBundle();
echo "File saved to - $fileName";
**/* THIS IS WHERE IM TRYING TO PRESENT IT */**
$this->outputPassBundleAsWebDownload($fileName);
Then Pass.php does a lot of stuff, which works because Ive used it for emailing working passes but Im replacing the emailing functionality with the presentation/download functionality. So here is the code for Pass.php:
<?php
class Pass {
private $workFolder = null;
private $ID = null;
var $content = null;
var $passBundleFile = null;
private function copySourceFolderFilesToWorkFolder($path) {
//recurse over contents and copy files
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST);
foreach($files as $name => $fileObject){
if (is_file($name) &&
substr($fileObject->getFileName(), 0, 1)!=".") {
copy($name,
$this->workFolder."/".str_replace($path."/", "",$name));
} else if (is_dir($name)) {
mkdir($this->workFolder."/".
str_replace($path."/", "",$name));
}
}
}
//import a json file into the object
function readPassFromJSONFile($filePath) {
//read the json file and decode to an object
$this->content =
json_decode(file_get_contents($filePath),true);
}
//export a json file from the object
function writePassJSONFile() {
file_put_contents($this->workFolder."/pass.json",
json_encode($this->content));
}
//generate the manifest file
function writeRecursiveManifest() {
//create empty manifest
$manifest = new ArrayObject();
//recurse over contents and build the manifest
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($this->workFolder),
RecursiveIteratorIterator::SELF_FIRST);
foreach($files as $name => $fileObject){
if (is_file($name) &&
substr($fileObject->getFileName(), 0, 1)!=".") {
$relativeName = str_replace($this->workFolder.
"/","",$name);
$sha1 = sha1(file_get_contents(
$fileObject->getRealPath()
));
$manifest[$relativeName] = $sha1;
}
}
//printf debug
// print_r($manifest);
//write the manifest file
file_put_contents($this->workFolder."/manifest.json",
json_encode($manifest));
}
//generate the bundle signature
function writeSignatureWithKeysPathAndPassword($keyPath, $pass) {
$keyPath = realpath($keyPath);
if (!file_exists($keyPath.'/WWDR.pem'))
die("Save the WWDR certificate as
$keyPath/WWDR.pem");
if (!file_exists($keyPath.'/passcertificate.pem'))
die("Save the pass certificate as
$keyPath/passcertificate.pem");
if (!file_exists($keyPath.'/passkey.pem'))
die("Save the pass certificate key as
$keyPath/passkey.pem");
$output = shell_exec("openssl smime -binary -sign". " -certfile '".$keyPath."/WWDR.pem'".
" -signer '".$keyPath."/passcertificate.pem'".
" -inkey '".$keyPath."/passkey.pem'".
" -in '".$this->workFolder."/manifest.json'".
" -out '".$this->workFolder."/signature'".
" -outform DER -passin pass:'$pass'");
}
//signature debugging
//print(file_get_contents($this->workFolder."/signature"));
//create the zip bundle from the pass files
function writePassBundle() {
//1 generate the name for the .pkpass file
$passFile = $this->workFolder."/".$this->ID.".pkpass";
//2 create Zip class instance
$zip = new ZipArchive();
$success = $zip->open($passFile, ZIPARCHIVE::OVERWRITE);
if ($success!==TRUE) die("Can't create file $passFile");
//3 recurse over contents and build the list
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($this->workFolder),
RecursiveIteratorIterator::SELF_FIRST);
//4 add files to the archive
foreach($files as $name => $fileObject){
if (is_file($name) &&
substr($fileObject->getFileName(), 0, 1)!=".") {
$relativeName = str_replace($this->workFolder."/",
"",$name);
$zip->addFile($fileObject->getRealPath(), $relativeName);
}
}
//5 close the zip file
$zip->close();
//6 save the .pkpass file path and return it too
$this->passBundleFile = $passFile;
return $passFile;
}
//make new instance from a source folder
function __construct($path) {
assert(file_exists($path."/pass.json"));
$this->ID = uniqid();
$this->workFolder = sys_get_temp_dir()."/".$this->ID;
mkdir($this->workFolder);
assert(file_exists($this->workFolder));
$this->copySourceFolderFilesToWorkFolder($path);
$this->readPassFromJSONFile($this->workFolder."/pass.json");
}
//delete all auto-generated files in the temp folder
function cleanup()
{
//recurse over contents and delete files
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($this->workFolder),
RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $name => $fileObject){
if (is_file($name)) {
unlink($name);
} else if (is_dir($name)) {
rmdir($name);
}
}
rmdir($this->workFolder);
}
//cleanup the temp folder on object destruction
function __destruct() {
$this->cleanup();
}
**/* THIS I ADDED AS A NEW FUNCTION TO PRESENT/DOWNLOAD */
function outputPassBundleAsWebDownload($fileName) {
//dump the generated pass to the browser
header("Content-Type: application/vnd.apple.pkpass");
header("Content-Disposition: attachment; ".
"filename=".basename($this->$fileName));
header("Content-Transfer-Encoding: binary");
header("Content-Length: ". filesize($this->$fileName));
flush();
readfile($this->$fileName);**
}
}
?>
The thing is the pass isnt being presented. Its being created properly because I get the echo on the screen with the fileName. What am Im missing? Im calling the output function from the getPass.php and passing in the $fileName. Why isnt it working?
You need to comment out the line that echos the file name. Echoing content to the browser forces PHP to automatically generate headers for text output, so it can serve the text of your file name.
Once output to the browser has started, you cannot send additional headers. This is why your headers in your output pass bundle function are being ignored and your pass is not being downloaded.
I am new to PHP .I want to merge mp3 files into one mp3 file.i googled this query and found this code .It is working fine and give me back the merged file. But this code give me merged file as save file .but i want to save the merged file in a folder .so that i can give the URL of the file to some application.
class mp3{
var $str;
var $time;
var $frames;
// Create a new mp3
function mp3($path="")
{
if($path!="")
{
$this->str = file_get_contents($path);
}
}
// Put an mp3 behind the first mp3
function mergeBehind($mp3){
$this->str .= $mp3->str;
}
// Calculate where's the end of the sound file
function getIdvEnd(){
$strlen = strlen($this->str);
$str = substr($this->str,($strlen-128));
$str1 = substr($str,0,3);
if(strtolower($str1) == strtolower('TAG')){
return $str;
}else{
return false;
}
}
// Calculate where's the beginning of the sound file
function getStart(){
$strlen = strlen($this->str);
for($i=0;$i<$strlen;$i++){
$v = substr($this->str,$i,1);
$value = ord($v);
if($value == 255){
return $i;
}
}
}
// Remove the ID3 tags
function striptags(){
//Remove start stuff...
$newStr = '';
$s = $start = $this->getStart();
if($s===false){
return false;
}else{
$this->str = substr($this->str,$start);
}
//Remove end tag stuff
$end = $this->getIdvEnd();
if($end!==false){
$this->str = substr($this->str,0,(strlen($this->str)-129));
}
}
// Display an error
function error($msg){
//Fatal error
die('<strong>audio file error: </strong>'.$msg);
}
// Send the new mp3 to the browser
function output($path){
//Output mp3
//Send to standard output
if(ob_get_contents())
$this->error('Some data has already been output, can\'t send mp3 file');
if(php_sapi_name()!='cli'){
//We send to a browser
header('Content-Type: audio/mpeg3');
if(headers_sent())
$this->error('Some data has already been output to browser, can\'t send mp3 file');
header('Content-Length: '.strlen($this->str));
header('Content-Disposition: attachment; filename="'.$path.'"');
}
echo $this->str;
return '';
}
}
// First File: (Google speech)
$mp3 = new mp3('1.mp3');
$mp3->striptags();
//Second file
$second = new mp3("2.mp3");
$mp3->mergeBehind($second);
$mp3->striptags();
$mp3->output('word.mp3'); //Output file (current a blank file)
The solution code will be very appreciate able ..Thanks in advance
Add this method to your mp3 class.
// Save the new mp3 into the file system
function savefile($path){
return file_put_contents($path, $this->str);
}
Then to use it simply ... replace
$mp3->output('word.mp3'); //Output file (current a blank file)
with this
$mp3->savefile('/path/to/directory/file.mp3');
and make sure you modify the path to a real directory within your file system.
I have searched the forum but the closest question which is about the control stream did not help or I did not understand so I want to ask a different question.
I have an html form which uploads multiples files to a directory. The upload manager that handles the upload resides in the same script with a different code which I need to pass the file names to for processing.
The problem is that the files get uploaded but they don't get processed by the the other code. I am not sure about the right way to pass the $_FILES['uploadedFile']['tmp_name']) in the adjoining code so the files can be processed with the remaining code. Please find below the script.
More specif explanation:
this script does specifically 2 things. the first part handles file uploads and the second part starting from the italised comment extracts data from the numerous uploaded files. This part has a variable $_infile which is array which is suppose to get the uploaded files. I need to pass the files into this array. so far I struggled and did this: $inFiles = ($_FILES['uploadedFile']['tmp_name']); which is not working. You can see it also in the full code sample below. there is no error but the files are not passed and they are not processed after uploading.
<?php
// This part uploads text files
if (isset($_POST['uploadfiles'])) {
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
}
echo "Files successfully uploaded . <br/>" ;
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode(',', $uploaded_files);
*/* This is the start of a script to accept the uploaded into another array of it own for* processing.*/
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
**$inFiles = ($_FILES['uploadedFile']['tmp_name']);**
$outFile = fopen("outputRMC.txt", "w");
$outFile2 = fopen("outputGGA.txt", "w");
//processing individual files in the array called $inFiles via foreach loop
if (is_array($inFiles)) {
foreach($inFiles as $inFileName) {
$numLines = 1;
//opening the input file
$inFiles = fopen($inFileName,"r");
//This line below initially was used to obtain the the output of each textfile processed.
//dirname($inFileName).basename($inFileName,'.txt').'_out.txt',"w");
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inFiles)) {
$line = fgets($inFiles);
$lineTokens = explode(',',$line);
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile,$line)===FALSE){
echo "Problem w*riting to file\n";
}
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(',',$line);
$searchCriteria2 = array('$GPGGA');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile2,$line)===FALSE){
echo "Problem writing to file\n";
}
}
}
}
echo "<p>For the file ".$inFileName." read ".$numLines;
//close the in files
fclose($_FILES['uploadedFile']['tmp_name']);
fflush($outFile);
fflush($outFile2);
}
fclose($outFile);
fclose($outFile2);
}
?>
Try this upload class instead and see if it helps:
To use it simply Upload::files('/to/this/directory/');
It returns an array of file names that where uploaded. (it may rename the file if it already exists in the upload directory)
class Upload {
public static function file($file, $directory) {
if (!is_dir($directory)) {
if (!#mkdir($directory)) {
throw new Exception('Upload directory does not exists and could not be created');
}
if (!#chmod($directory, 0777)) {
throw new Exception('Could not modify upload directory permissions');
}
}
if ($file['error'] != 0) {
throw new Exception('Error uploading file: '.$file['error']);
}
$file_name = $directory.$file['name'];
$i = 2;
while (file_exists($file_name)) {
$parts = explode('.', $file['name']);
$parts[0] .= '('.$i.')';
$new_file_name = $directory.implode('.', $parts);
if (!file_exists($new_file_name)) {
$file_name = $new_file_name;
}
$i++;
}
if (!#move_uploaded_file($file['tmp_name'], $file_name)) {
throw new Exception('Could not move uploaded file ('.$file['tmp_name'].') to: '.$file_name);
}
if (!#chmod($file_name, 0777)) {
throw new Exception('Could not modify uploaded file ('.$file_name.') permissions');
}
return $file_name;
}
public static function files($directory) {
if (sizeof($_FILES) > 0) {
$uploads = array();
foreach ($_FILES as $file) {
if (!is_uploaded_file($file['tmp_name'])) {
continue;
}
$file_name = static::file($file, $directory);
array_push($uploads, $file_name);
}
return $uploads;
}
return null;
}
}