How to generate a pdf on post saving or updating - php
I'm trying to create a PDF from post content, including some ACF fields. Currently I've got it working on a POST form and dynamically creating a PDF each time, but I'd like to make it generate the PDF on saving the post so I can then just have a download button which downloads the PDF generated from saving the post, but having difficulty doing so. Any help would be grand!
I've tried to create this as a function in functions.php hooking into the acf/save_post action at prioirty 15 so it's after the initial save.
function vehicle_details_pdf( $post_id ) {
require('wp-content/themes/murrayscott-nelson/fpdf/fpdf.php');
class PDF extends FPDF
{
function Header()
{
$vehicleRef = $_POST['ref'];
$this->Image('wp-content/themes/murrayscott-nelson/assets/logo.jpg',10,10,80);
$this->SetFont('Arial','B',15);
$this->Cell(80);
$this->Cell(85,10,'Vehicle Details - Ref:' . $vehicleRef ,0,0,'R');
$this->Ln(20);
}
function Footer()
{
$this->SetY(-15);
$this->SetFont('Arial','I',8);
$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
}
$vehicleName = get_the_title();
$vehicleBodyStyle = get_field('body_type', $post_id);
$vehiclePrice = get_field('price', $post_id);
$vehicleEngCap = get_field('engine_capacity', $post_id);
$vehicleMileage = get_field('mileage', $post_id);
$vehicleSteering = get_field('steering', $post_id);
$vehicleDescription = get_field('description', $post_id);
$vehicleRef = get_field('reg_ref', $post_id);
$images = get_field('vehicle_images', $post_id);
$image = $images[0];
$image = $image['url'];
$vehicleImage = preg_replace("/^https:/i", "http:", $image);
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Arial','B',17);
$pdf->Image( $vehicleImage, $pdf->GetX(), $pdf->GetY(), 190);
$pdf->Ln(130);
$pdf->Cell(0,10,$vehicleName);
$pdf->Ln(10);
$pdf->SetFont('Arial','',12);
$pdf->Cell(0,7,'Body Style: ' . $vehicleBodyStyle . ' | Steering: ' . $vehicleSteering . ' | Engine Capacity: ' . $vehicleEngineCap . 'cc | Mileage: ' . $vehicleMileage . ' miles' );
$pdf->Ln(7);
$pdf->Write (6, $vehicleDescription);
$pdf->SetFont('Arial','B',17);
$pdf->Ln(0);
$pdf->Cell( 0, 10, iconv("UTF-8", "ISO-8859-1", "£") . $vehiclePrice, 0);
$pdf->Ln(10);
$pdf->setFillColor(230,230,230);
$pdf->SetFont('Arial','B',15);
$pdf->MultiCell(0,7,"If you'd like to arrange a viewing please call 01723 361 227",0,'C',1);
$pdf->MultiCell(0,7,"quoting reference: " . $vehicleRef ,0,'C',1);
$pdf->setFillColor(38,54,29);
$pdf->setTextColor(255,255,255);
$pdf->Ln(5);
$pdf->MultiCell(0,7,"Finance Available - Ask for details" ,0,'C',1);
$pdf->setTextColor(0,0,0);
$filepath= wp_get_upload_dir() . '/vehicledetails/' ;
$pdf->Output('F', $filepath . $vehicleRef . '.pdf');
}
add_action('acf/save_post', 'vehicle_details_pdf', 15);
I expect the code to create a pdf file in the wp-content/uploads/vehicledetails directory
error messages:
[01-Sep-2019 10:49:10 UTC] PHP Warning: Invalid argument supplied for
foreach() in /app/public/wp-includes/class-wp-post-type.php on line
597 [01-Sep-2019 10:49:10 UTC] PHP Warning: Invalid argument supplied
for foreach() in /app/public/wp-includes/class-wp-post-type.php on
line 597 [01-Sep-2019 10:49:15 UTC] PHP Warning: Invalid argument
supplied for foreach() in
/app/public/wp-includes/class-wp-post-type.php on line 597
[01-Sep-2019 10:49:15 UTC] PHP Warning: Invalid argument supplied for
foreach() in /app/public/wp-includes/class-wp-post-type.php on line
597 [01-Sep-2019 10:49:17 UTC] PHP Warning: Invalid argument supplied
for foreach() in /app/public/wp-includes/class-wp-post-type.php on
line 597 [01-Sep-2019 10:49:17 UTC] PHP Warning: Invalid argument
supplied for foreach() in
/app/public/wp-includes/class-wp-post-type.php on line 597
[01-Sep-2019 10:49:17 UTC] PHP Warning: Invalid argument supplied for
foreach() in /app/public/wp-includes/class-wp-post-type.php on line
597 [01-Sep-2019 10:49:18 UTC] PHP Warning: Invalid argument supplied
for foreach() in /app/public/wp-includes/class-wp-post-type.php on
line 597 [01-Sep-2019 10:49:19 UTC] PHP Warning: Invalid argument
supplied for foreach() in
/app/public/wp-includes/class-wp-post-type.php on line 597
[01-Sep-2019 10:49:19 UTC] PHP Warning: Invalid argument supplied for
foreach() in /app/public/wp-includes/class-wp-post-type.php on line
597 [01-Sep-2019 10:49:20 UTC] PHP Warning: Invalid argument supplied
for foreach() in /app/public/wp-includes/class-wp-post-type.php on
line 597 [01-Sep-2019 10:49:20 UTC] PHP Warning: Invalid argument
supplied for foreach() in
/app/public/wp-includes/class-wp-post-type.php on line 597
[01-Sep-2019 10:49:21 UTC] PHP Warning:
require(wp-content/themes/murrayscott-nelson/fpdf/fpdf.php): failed to
open stream: No such file or directory in
/app/public/wp-content/themes/murrayscott-nelson/functions.php on line
81 [01-Sep-2019 10:49:21 UTC] PHP Warning:
require(wp-content/themes/murrayscott-nelson/fpdf/fpdf.php): failed to
open stream: No such file or directory in
/app/public/wp-content/themes/murrayscott-nelson/functions.php on line
81 [01-Sep-2019 10:49:21 UTC] PHP Fatal error: require(): Failed
opening required 'wp-content/themes/murrayscott-nelson/fpdf/fpdf.php'
(include_path='.:/usr/share/php:/www/wp-content/pear') in
/app/public/wp-content/themes/murrayscott-nelson/functions.php on line
81 [01-Sep-2019 10:49:21 UTC] PHP Fatal error: require(): Failed
opening required 'wp-content/themes/murrayscott-nelson/fpdf/fpdf.php'
(include_path='.:/usr/share/php:/www/wp-content/pear') in
/app/public/wp-content/themes/murrayscott-nelson/functions.php on line
81 [01-Sep-2019 10:50:16 UTC] PHP Warning: Invalid argument supplied
for foreach() in /app/public/wp-includes/class-wp-post-type.php on
line 597 [01-Sep-2019 10:52:17 UTC] PHP Warning: Invalid argument
supplied for foreach() in
/app/public/wp-includes/class-wp-post-type.php on line 597
[01-Sep-2019 10:54:18 UTC] PHP Warning: Invalid argument supplied for
foreach() in /app/public/wp-includes/class-wp-post-type.php on line
597 [01-Sep-2019 10:56:18 UTC] PHP Parse error: syntax error,
unexpected '$vehicleName' (T_VARIABLE), expecting function
(T_FUNCTION) or const (T_CONST) in
/app/public/wp-content/themes/murrayscott-nelson/functions.php on line
114 [01-Sep-2019 10:58:19 UTC] PHP Parse error: syntax error,
unexpected '$vehicleName' (T_VARIABLE), expecting function
(T_FUNCTION) or const (T_CONST) in
/app/public/wp-content/themes/murrayscott-nelson/functions.php on line
114
Your upload directory is not set correctly.
Try this:
$uploads = wp_upload_dir();
$pdf->Output('F', $uploads['basedir'] . '/vehicledetails/' . $vehicleRef . '.pdf');
Related
Unable to Get Documents from a Nested Collection with Cloud Firestore using PHP
Following Google's official documentation at https://github.com/GoogleCloudPlatform/php-docs-samples/blob/master/firestore/src/get_all_docs.php, I am unable to retrieve documents that are part of a nested collection, i.e.: $db = new FirestoreClient([ 'projectId' => $projectId, ]); //$citiesRef = $db->collection('cities'); //working original example $citiesRef = $db->collection('countries')->document('USA')->collection('cities'); //this throws an HTTP Error 500 $documents = $citiesRef->documents(); foreach ($documents as $document) { if ($document->exists()) { printf('Document data for document %s:' . PHP_EOL, $document->id()); print_r($document->fields()); printf(PHP_EOL); } else { printf('Document %s does not exist!' . PHP_EOL, $snapshot->id()); } } The above code throws an HTTP Error 500. Here is my example database: The error log (CentOS 6) shows: [06-May-2018 22:24:26 UTC] PHP Warning: Module 'protobuf' already loaded in Unknown on line 0 [06-May-2018 22:24:26 UTC] PHP Warning: Module 'protobuf' already loaded in Unknown on line 0 [06-May-2018 22:24:27 UTC] PHP Fatal error: Call to undefined method Google\Protobuf\Timestamp::getFields() in /home/user/public_html/my/vendor/google/gax/src/ApiCore/Serializer.php on line 222 [06-May-2018 22:25:02 UTC] PHP Warning: Module 'protobuf' already loaded in Unknown on line 0 [06-May-2018 22:25:02 UTC] PHP Warning: Module 'protobuf' already loaded in Unknown on line 0 I'm aware that Firestore is still in beta. Is this one of the known issues/limitations?
As a workaround, I am able to get the data from the nested document like so: $db = new FirestoreClient([ 'projectId' => $projectId, ]); //$citiesRef = $db->collection('cities'); //working original example $citiesRef = $db->collection('countries')->document('USA')->collection('cities'); $documents = $citiesRef->select(['capital','country','name','population','state'])->documents(); foreach ($documents as $document) { if ($document->exists()) { printf('Document data for document %s:' . PHP_EOL, $document->id()); //print_r($document->fields()); //this no longer works print_r($document->data()); printf(PHP_EOL); } else { printf('Document %s does not exist!' . PHP_EOL, $snapshot->id()); } }
Open XLSX file that protected by a password with PHPSpreadsheet
I'm trying to open an Excel file (.xlsx) that is protected by a password with PHPSpreadsheet (documentation). I know the password but I don't find a way to open it. The load()method of \PhpOffice\PhpSpreadsheet\Reader\Xlsx doesn't give the possibility to insert a password and when I try to load the file it returns an error (of course). use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $spreadsheet = $reader->load('hello world.xlsx'); $sheet = $spreadsheet->getActiveSheet(); echo $sheet->getCell('A1')->getValue() . "\n"; And here is the error Warning: ZipArchive::getFromName(): Invalid or uninitialized Zip object in /PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php on line 311 Warning: ZipArchive::getFromName(): Invalid or uninitialized Zip object in /PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php on line 313 Warning: Invalid argument supplied for foreach() in /PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php on line 350 Warning: ZipArchive::getFromName(): Invalid or uninitialized Zip object in /PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php on line 311 Warning: ZipArchive::getFromName(): Invalid or uninitialized Zip object in /PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php on line 313 Warning: Invalid argument supplied for foreach() in /PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php on line 397 Warning: ZipArchive::getFromName(): Invalid or uninitialized Zip object in /PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php on line 311 Warning: ZipArchive::getFromName(): Invalid or uninitialized Zip object in /PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php on line 313 Warning: Invalid argument supplied for foreach() in /PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php on line 1855 Warning: ZipArchive::close(): Invalid or uninitialized Zip object in /PHPOffice/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php on line 1883 How can this code deal with passwords?
I welcome you to check out my PHPDecryptXLSXWithPassword repo. It also works for DOCX/PPTX files, but this answer is specific to your question: first decrypt the file with password, and then use the decrypted file with PHPSpreadsheet. Here is an example: require_once('PHPDecryptXLSXWithPassword.php'); $encryptedFilePath = 'hello world.xlsx'; $password = 'mypassword'; // password to "open" the file $decryptedFilePath = 'temp_path_to_decrypted_file.xlsx'; decrypt($encryptedFilePath, $password, $decryptedFilePath); use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $spreadsheet = $reader->load($decryptedFilePath); $sheet = $spreadsheet->getActiveSheet(); echo $sheet->getCell('A1')->getValue() . "\n"; Note: This is an experimental code, so use with caution. DO NOT use in production!
At this moment i can't try but, I suppose that you have to do something like this: use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $spreadsheet = $reader->load('hello world.xlsx'); $sheet = $spreadsheet->getActiveSheet(); $sheet->getProtection()->setSheet(true); $sheet->getProtection()->setPassword('THEPASSWORD'); echo $sheet->getCell('A1')->getValue() . "\n"; I'm not sure, tomorrow I will be to the office and can try.
PHP Mac: fopen fails to open strea: no such file or directory and others
I have registration.php in my data folder which is in the source folder so that isn't the issue. What I'm doing is recording my website's form data $dataRecord and trying to save it in this csv file that I have. But I'm getting four errors: Warning: fopen(data/registration.csv): failed to open stream: No such file or directory in /users/s/j/sjflanag/www-root/cs008/lab11/form.php on line 225 Warning: fputcsv() expects parameter 1 to be resource, boolean given in /users/s/j/sjflanag/www-root/cs008/lab11/form.php on line 228 Warning: fclose() expects parameter 1 to be resource, boolean given in /users/s/j/sjflanag/www-root/cs008/lab11/form.php on line 231 Fatal error: Call to undefined function sendMail() in /users/s/j/sjflanag/www-root/cs008/lab11/form.php on line 273 $myFolder = 'data/'; $myFileName = 'registration'; $fileExt = '.csv'; $filename = $myFolder . $myFileName . $fileExt; if ($debug) { print PHP_EOL . '<p>filename is ' . $filename; } $file = fopen($filename, 'a'); fputcsv($file, $dataRecord); fclose($file);
PHP Error uploading large file xlsx with PHPexcel
I have an error on upload files with aprox 130.000 rows (23MB). The code works good with small files but when I try to upload bigger ones this error always comes out. I have already tried the cell caching method to reduce memory usage but the error remains. In my php.ini the parameters are memory_limit=128M / upload_max_filesize=64M / post_max_size=64M. Warning: simplexml_load_string(): Memory allocation failed in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 Warning: simplexml_load_string(): Entity: line 2: parser error : Memory allocation failed : xmlSAX2Characters in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 Warning: simplexml_load_string(): "><c r="I935190" s="9"/></row><row r="935191" spans="9:9" x14ac:dyDescent="0.25" in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 Warning: simplexml_load_string(): ^ in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 Warning: simplexml_load_string(): Memory allocation failed : building attribute in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 Warning: simplexml_load_string(): Memory allocation failed : building attribute in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 Warning: simplexml_load_string(): Memory allocation failed in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 Warning: simplexml_load_string(): Entity: line 2: parser error : Extra content at the end of the document in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 Warning: simplexml_load_string(): "><c r="I935190" s="9"/></row><row r="935191" spans="9:9" x14ac:dyDescent="0.25" in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 And when I try the uploading again it appear: Warning: simplexml_load_string(): Memory allocation failed : growing buffer in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 Warning: simplexml_load_string(): Memory allocation failed : growing buffer in C:\xampp\htdocs\lib\PHPExcel\Reader\Excel2007.php on line 652 A piece of the php code, all warnigs appear on the 9th line when I load the file: $total = count($_FILES["file"]["name"]); for($j=0; $j<$total; $j++){ $tmpFilePath =$_FILES["file"]["tmp_name"][$j]; if ($tmpFilePath != ""){ $newFilePath = 'ficheros/'. $_FILES["file"]["name"][$j]; } if(move_uploaded_file($tmpFilePath, $newFilePath)){ $objReader = PHPExcel_IOFactory::createReader('Excel2007'); $objReader->setReadDataOnly(true); $objPHPExcel = $objReader->load($newFilePath); $sheetCount = $objPHPExcel ->getSheetCount(); $sheetNames = $objPHPExcel -> getSheetNames(); $objWorksheet = $objPHPExcel -> getSheetByName("Sheet1"); $highestRow = $objWorksheet->getHighestRow(); $highestColumn = $objWorksheet->getHighestColumn(); $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); $rows = array(); for ($row = 2; $row <= $highestRow; ++$row) { for ($col = 0; $col <= $highestColumnIndex; ++$col) { $rows[$col] = $objWorksheet->getCellByColumnAndRow($col, $row)->getCalculatedValue(); } mysql_query.. } } Thanks in advance
Need to parse a photo with DuckDuckGo
<?php $get = file_get_contents("https://duckduckgo.com/i.js?q=love&s=1"); $decode = json_decode($get, TRUE); foreach($decode['results'] as $res) { echo "".$res['image'].""; } ?> Nothing happens. What's wrong? Warning: file_get_contents(https://duckduckgo.com/i.js?q=love&s=1) [function.file-get-contents]: failed to open stream: No such file or directory in /home01/rfep/nzfrka/home/mydomain/myfeed/sssfi.php on line 2 failed to open stream Warning: Invalid argument supplied for foreach() in /home01/rfep/nzfrka/home/mydomain/myfeed/sssfi.php on line 4