Create PDF file from Raw PDF Content - php

I am getting raw PDF data from an API and want to create PDF file from this data.
The raw PDF data looks like:
%PDF-1.5
%
....................
....................
%%EOF
I created PDF file with above content with the help of PHP file handling functions and it seems file is created successfully. However when newly created PDF is opened, it simply shows blank white page (without any content). If same file is opened in IDE (like notepad++), it shows the raw content written in correctly.
I even tried PHP header with different params with no luck. I also tried using DOMPDF library and that still doesn't help either.
I guess there is some extra information in raw content (maybe header, filename etc.) and I need to get actual content from it but I have no idea how?
Can anyone guide me what I am missing here?
Thanks!

try following script i think you miss some header:
$path = /path/to/yourfilename.pdf;
$content = <your raw pdf data>;
//put your content to file
file_put_contents($path, $content);
header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
// force download
header('Content-Type: application/force-download');
header('Content-Type: application/octet-stream', false);
header('Content-Type: application/download', false);
header('Content-Disposition: attachment; filename="'.basename($path).'";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($path));
header('Content-Type: application/pdf', false);
readfile($path);
exit();

Related

mpdf file only works in browser, not in adobe acrobat (format error)

I create a pdf file with this code.
case 'D':
//Download file
header('Content-Description: File Transfer');
if (headers_sent())
$this->Error('Some data has already been output to browser, can\'t send PDF file');
//Time on timezone+summertime
if(date('I',filemtime ($name))==1){ $timez=filemtime ($name)+3*3600;}else{ $timez=filemtime ($name)+2*3600;}
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', $timez).' GMT');
//header('Content-Type: '.'application/pdf');
//header('Content-Type: application/pdf');
header('Content-Type: application/force-download');
//header('Content-Type: application/octet-stream', false);
//header('Content-Type: application/download', false);
//header('Content-Type: application/pdf', false);
header('Content-Disposition: attachment; filename="'.$name.'.pdf"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
The PDF file will create successful. If I open the created file in my browser, all is ok. If I click in my explorer and try to open with adobe acrobat, I get a error-message that
adobe could not open the file caused by unsupported filetype or damaged/corrupt file.
So I play a bit about the different header options, but in every case at the end I have the same result.
How I can create a pdf file with mpdf which is supported by adobe acrobat to open it with them?
Follow this post(How to make mPDF 6.1 work with PHP 7.1.5), won't fix the problem.
Thanks
At the end the problem was easy to fix.
So i open the pdf-file in my coding/text-editor.
There i could see some php-errors/error-warnings.
In the mpdf.php i changed the $errorlevel=error_reporting(E_ERROR | E_PARSE);
thats all.

PHPExcel - instead of downloading save it to the directory

I'm trying to store Excel generated file to server directory instead of downloading after reaching path.
My code:
// worksheet
$objPHPExcel->getActiveSheet()->setTitle('Podaci');
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="mjesecni_podaci.xlsx"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate');
header ('Pragma: public'); // HTTP/1.0
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//$objWriter->save('php://output');
$putanja_spremanja_fajla = 'mail/mjesecni_podaci.xlsx';
$objWriter->save($putanja_spremanja_fajla);
sleep(1);
slanje_maila($db, $datum);
I tried to remove some of header lines, but then my file is corrupted or I get some of errors.
Any suggestions?
Remove all header()'s
Use full path's: e.g /home/database/public_html/application/mail/
Cron job: Remove if (PHP_SAPI == 'cli') die('This example should only be run from a Web Browser'); because this line of code checks if script is "called" by server(cgi-fcgi) or user(cli).
After that, you can use cron jobs or similar (if sever trying to run .php script).
If you trying to reach link trough web browser, you must use headers because headers talk with browser.
the following lines tell the browser to expect a file. (The Excelfile mjesecni_podaci.xlsx to be exact)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="mjesecni_podaci.xlsx"');
If you tell PHPExcel to save the file to disk, no file is delivered to the browser.
If there is no output at all or some kind of echo or something else, you will either get an Error-Message or the browser "downloads" the file "mjesecni_podaci.xlsx" with the output you produced.
For example:
<?php
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="mjesecni_podaci.xlsx"');
echo "Hello World!"
?>
This code will download the File "mjesecni_podaci.xlsx" with the content "Hello World!". (Save the file to disk and open it with an editor like Notepad++ or similar)
In your code, you should just remove the two lines, and make sure that your program can write to the subfolder "mail". Your code should work after that. (at least the part before sleep(1);) .

PHPEXCEL set UTF-8 encode

I have headers:
header('Content-Type: text/html; charset=UTF-8');
header("Content-type: application/octetstream");
header('Content-Disposition: attachment; filename="export.csv"');
but decoding not work correct if I have word in database "Pagrindinė" in excel show "PagrindinÄ", what is wrong with my headers ?
What is wrong with my headers ?
Nothing, your headers are looking fine.
What is wrong with Excel?
The user who opens the file in Excel needs to tell Excel that the file is in UTF-8 encoding. Direct that user to contact the vendor of the software it uses for her/his support options.
Users of LibreOffice or a derivate of it do not have that problem btw., so one solution is to tell those to install a suite of such, open the CSV file and save it as Excel file for example.
Or you directly create the Excel file on your server.
Maybe if you change the format text encoding of your .php file when you save it, to Unicode (UTF-8). It works for me.
Hope it helps.
try this:
header('Content-Transfer-Encoding: binary');
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
header('Content-Disposition: attachment; filename = "Export '.date("Y-m-d").'.xls"');
header('Pragma: no-cache');
//these characters will make correct encoding to excel
echo chr(255).chr(254).iconv("UTF-8", "UTF-16LE//IGNORE", $out);

"Excel found unreadable content" warning when opening Excel files made with PHPExcel

I'm trying to download Excel files (xlsx) using PHPExcel as follows.
require_once("../../phpExcel/Classes/PHPExcel.php");
require_once("../../phpExcel/Classes/PHPExcel/IOFactory.php");
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("Tiny")
->setLastModifiedBy("Tiny")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
$objPHPExcel->setActiveSheetIndex(0);
$sheet=$objPHPExcel->getActiveSheet();
$sheet->setCellValue('A1', 'Hello');
$sheet->setCellValue('B2', 'world!');
$sheet->setCellValue('C1', 'Hello');
$sheet->setCellValue('D2', 'world!');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="test.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
It works but when I try to open the Excel file, it asks for a confirmation in a conform dialog.
Excel found unreadable content in 'test.xlsx'. Do you want to recover
the contents of this workbook? If you trust the source of this
workbook, click Yes.
I also tried to change the header as follows
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=test.xlsx");
header("Content-Transfer-Encoding: binary");
It still asks for the same confirmation. What am I doing wrong here, please?
As told by questioning user Tiny on his own comment:
Finally, it worked. I just added exit at the end of my PHP script (at
the end of the first code snippet in the question). Thanks very much
all of you for giving me useful hints.
To give some constructive additional tips on this kind of problems:
A good tip is that you can omit the closing tag ?> on all your PHP script files, that way you know that you're not sending any aditional invisible whitespace at the end of it.
Also enconding PHP script files on UTF-8 on wrongfully configured web server can send an undesirable couple bytes at the begining of the script. Open the PHP file on Notepad++, check if it's UTF-8, and in that case, convert it to ANSI. If that makes it work, check your webserver/php configuration.
Just before the header calls, you can check if headers has been wrongfully sent with:
if ( headers_sent() ) die("**Error: headers sent");
If you can't prevent that some function call sends undesirable strings to the browser, you can "erase" all of it using at the very beginning of your script:
ob_start();
and then, just before the first headers call, use:
ob_clean();
Be careful that with doing so will prevent you for receiving error feedback.
And lastly, as already said, if nothing has to be executed afterwards some point on the script, call exit or die.
Well I had this problem, my solution was changing the header Content-type to :
header('Content-Type: application/openxmlformats-officedocument.spreadsheetml.sheet');
I had before:
header('Content-Type: application/vnd.ms-excel');
and I changed the format to Excel2007, I was using Excel5 for excel 2003 xls format.
I tried all the solutions from this page and all the other pages with the same question but not luck.
So basically, I just changed the output format of my excels and that solved the problem.
This error can also be triggered by serving the file without the Content-Length headers.
Look at the example given here in php.net
Give the active sheet a title:
$sheet->setTitle('Some title string here');
I Put just exit; After
PHPExcel_IOFactory::createWriter($phpExcelObject, 'Excel2007')->save("php://output");
and it work's for me :)
$file_name .= "_".\Carbon\Carbon::now()->format('d_m_Y_H_i').'.xlsx';
// Prepare To Download
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename='.$file_name);
header('Cache-Control: max-age=0');
header('Pragma: public');
PHPExcel_IOFactory::createWriter($phpExcelObject, 'Excel2007')->save("php://output");
exit;
This might help to someone who tries to download excel using https://github.com/Maatwebsite/Laravel-Excel package in laravel with get route with ajax
I got response something like PK ¾#G’D²X ð [Content_Types].xml­”MNÃ0…÷œ"ò%nY „švAa •(0ö¤±êØ–gúw{&i‰#ÕnbEö{ßøyìÑdÛ¸l mð¥‘×ÁX¿(ÅÛü)¿’òF¹à¡;#1_滘±Øc)j¢x/%ê…Eˆày¦ ©QÄ¿i!£ÒKµ y3ÜJ<§œZ1½0?YÙL%zV cäÖIb7؇û‰ìa/lÙ¥P1:«qáríÍjªÊj0A¯–Íuë""íàÙ(Œ ”Á€WìMä)Tjå and much more content
i tried many of the solution but fails
finally i achieved by doing this in onclick event
$(document).on('click','#elementId',function(e){
e.preventDefault();
window.location.assign('your action url'+'?param='+ param_data);
}
my php : 7.4.1 os: Ubuntu 18.04 frameword: Yii2.0.37 I had also this problem and my solution is that I use exit and ob_clean()
$objPHPExcel = new \PHPExcel();
$objPHPExcel->getProperties()->setCreator("Murodjon Abduvohidov")
->setLastModifiedBy("Murodjon Abduvohidov");
$objPHPExcel->getActiveSheet()->getPageSetup()-> setOrientation(\PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE)
->setPaperSize(\PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
$objPHPExcel->getActiveSheet()->getSheetView()->setZoomScale(70);
$objPHPExcel->getActiveSheet()->getSheetView()->setZoomScaleNormal(82);
$objPHPExcel->getActiveSheet()->getSheetView()->setView(\PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW);
$objPHPExcel->getActiveSheet()->getPageSetup()->setScale(63);
$objPHPExcel->getActiveSheet()->getPageMargins()->setTop(0.4);
$objPHPExcel->getActiveSheet()->getPageMargins()->setRight(0.4);
$objPHPExcel->getActiveSheet()->getPageMargins()->setLeft(0.4);
$objPHPExcel->getActiveSheet()->getPageMargins()->setBottom(0.4);
$objPHPExcel->getDefaultStyle()->getFont()->setName('Arial');
$objPHPExcel->getDefaultStyle()->getFont()->setSize(10); $objPHPExcel->getActiveSheet()->getCell('A2')->setValue('salom');
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');ob_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="abdulqodir.xlsx"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$objWriter->save("php://output");exit;`

Linking to a forced download script in a pdf

I am generating dynamic PDF reports in PHP and having some issues with links to the web.
My links are to a PHP script that forces the download of a file attachment. This script works perfectly in all browser when accessed via the browser. It also works from the PDF in all browser except Internet Explorer.
Instead of IE seeing the file as a PDF, PNG, or whatever the file is, the download prompt says the document type is: "HTML Plugin Document"
If the user clicks "Open" or "Save" IE says it cannot download the file and gives the filename as "index2.php". That is the beginning of the URI of address.
The correct filesize is given so I know it is getting the file. Maybe it is a header issue?
Here is the header I'm creating on the download script:
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT;");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT;");
header("Pragma: no-cache;"); // HTTP/1.0
header('Content-Type: '.$file->file_mime_type.';');
header("Content-Description: File Transfer");
header("Cache-Control: public");
header('Content-Disposition: attachment; filename="'.$file->file_name.'";');
header('Content-Length: '.$file->file_size.';');
header('Content-transfer-encoding: binary');
Any input would be greatly appreciated.
Here's what I use and that is proven to work:
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.$file->file_name.'"');
readfile($filename);
have you tried something like this?
header('Content-Disposition: attachment; filename="'.$file->filename.'"');
It might be worth mentioning that there is also a known issue on several versions of IE when transferring files over SSL which requires the following work around:
header("Cache-Control: maxage=1");
header("Pragma: public");
There is more information regarding this bug here: http://support.microsoft.com/kb/812935

Categories