FPDF - generated PDF is not displayed properly in browser - php

I am generating a PDF document with a FPDF library.
I am trying to display a generated document in browser (Firefox, Chrome, Opera) but all i get are strange characters starting with:
%PDF-1.3 3 0 obj <>...
This is my code. I am trying to add two images to the document.
$pdf = new FPDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->Image('./image.png',10,10,0,0,'png');
$pdf->Image('./image.png',10,120,0,0,'png');
$pdf->Output('file.pdf','I');
If I use the output with the 'D' option:
$pdf->Output('file.pdf','D');
and save the file on the disc, the pdf document is fine.

You probably need to add the correct content type header. When the web server serves up a file, it tries to give the correct content type header it guesses from the file, but here, as you're generating it with PHP, the default header will be sent, which is usually text/html. Try adding this to the start of your code:
header('Content-type: application/pdf');
And it should send with the correct content type header.

I run into the same problem and I add ob_get_clean(); before $pdf->OutPut() and I got the correct result.
It was because the header was not correct, but even I set the header before outputting the pdf, it still not correct.

change D to I
$pdf->Output('file.pdf','I');
send the file inline to the browser. The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.
from there documentation
fpdf documentaion

Add exit as follows :
$pdf->Output();
exit;
Reference

Try:
ob_start (); //used before output.
$pdf->Output();
?>

I don't know if i should put it as a comment or answer, i had same issue on my localhost, but once i placed my code on live server the issue resolved automatically. Try cleaning all cookies on your local system and it may help too.

I had applied all the above options with different sequences and this is how finally it works. Thanks
$str = iconv('UTF-8', 'windows-1252', $custom_data);
$final = html_entity_decode($str ,ENT_QUOTES, 'windows-1252');
$pdf = new FPDF();
header('Content-type: application/pdf');
$pdf->AddPage();
$pdf->SetFont('Courier','',16);
$pdf->MultiCell(190, '10', $final, '', 'L');
ob_get_clean();
$pdf->Output($afterDash.".pdf", "I");
exit;

Related

Saving PDF file as "data" - using PHP MPDF

IM trying to save a PDF file, generated from HTML, into the user's local using MPDF. Here is the part of the code responsable for this:
$mpdf = new \Mpdf\Mpdf();
$html = $this->load->view('gestao/relatorios/relatorio_cargo_cidades', $data, true);
$mpdf->WriteHTML($html);
$mpdf->SetFooter(relatorio_footer());
$mpdf->Output('relatorio_cargos_cidades_seletivo_' . $seletivo_id .'_'.date("Ymd_his").'.pdf', 'D');
At first I was trying to show the PDF using the "I" param from the output function, than the user could just see the PDF and choose to download it or not. But when I tried to submit a file into another website, it says that the file is not a PDF. Than I used my linux to see if the file was actually a PDF, here's what I got:
As you can see, the file is being saved as "data" for some reason. I've already tried to use the 'F' param, also from the output function, and than it worked, I saved as PDF. But the F param only save the file inside the code folder, so it was not very usefull for me.
Can anyone tell me how could I save the file as an actually PDF using MPDF?
EDIT
I think that the problem is being caused by CODEIGNITER, not by the MPDF. When I'm setting the last param from the load->view as TRUE, the returned HTML is in a data (string) form, and MPDF is not converting this properly.
Adding ob_clean() might solve your problem:
ob_clean();
$mpdf->Output('relatorio_cargos_cidades_seletivo_' . $seletivo_id .'_'.date("Ymd_his").'.pdf', 'D');
You can simply use the D parameter for downloading:
$mpdf -> Output ('FILENAME.pdf', 'D');
or generate your own header and then output the content as string:
header ("Content-type: application/pdf");
header ("Content-Disposition: inline; filename=FILENAME.pdf");
$mpdf -> Output ('', 'S');

Open generated pdf in browser in another tab

I'm generating pdf through FPDF. Now all I need is to open this generated pdf in browser.
Searched lot for it, but all am getting is solution for existing pdf where as here we need solution for generated pdf through fpdf.
Following is my code:
<?php require('../pdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',12);
$pdf->Cell(40,10,'This is demo');
$pdf->Output();
?>
A quick browse of the FPDF documentation shows that you can add a couple of parameters to the Output() function call to provide display in browser or download functionality
string Output([string dest [, string name [, boolean isUTF8]]])
See more here.
For example:
<?php require('../pdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',12);
$pdf->Cell(40,10,'This is demo');
$pdf->Output('I');
?>
The above example uses 'I' for inline. The other options are:
I: send the file inline to the browser. The PDF viewer is used if available.
D: send to the browser and force a file download with the name given by name.
F: save to a local file with the name given by name (may include a path).
S: return the document as a string.
It is all available in the documentation.
For people still looking, adding target="_blank" to your form tag will open the PDF in a new window.
HTML:
<form method="GET" action="/target-destination/" id="pdfForm" target="_blank">
<!-- Content goes here -->
</form>
mPDF:
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('Hello World');
$mpdf->Output('filename.pdf', 'I');
The FPDF inline method demonstration will attempt to insecurely open an About:Blank which should not be relied on as a method for Inline Display, it simply triggers a security response in the browser to auto download to AV check in sandbox. Use one of the traditional methods like A Href=download I will trust that more and can run a URL checker on your link first...

dompdf stream pdf in browser using localhost, but not in network ip

i need to know why dompdf doesn't stream a pdf in browser before download on network ip like 192.168.1.77 , but it works on localhost.
when using network ip, it just immediately download the file , it won't show pdf preview in browser
i'm using dompdf version 0.6.2
this is my code
$dompdf = new DOMPDF();
ob_start();
$this->load->view('report_me',array_merge($this->sesi,$this->session->userdata('printdata')));
// header('Pragma','public');
$html = ob_get_contents();
ob_end_clean();
// $this->session->unset_userdata('printdata');
// $dompdf->set_option('setIsHtml5ParserEnabled', true);
$dompdf->load_html($html);
// (Optional) Setup the paper size and orientation
// $dompdf->setPaper('A4', 'potrait');
// Render the HTML as PDF
$dompdf->render();
$canvas = $dompdf->get_canvas();
$font = Font_Metrics::get_font("helvetica", "bold");
$canvas->page_text(44, 760, "Page {PAGE_NUM} of {PAGE_COUNT}", $font, 8, array(0,0,0));
//ERASE SESSION
// Output the generated PDF to Browser
$dts = date('Y-m-d');
// $dompdf->output();
// $dompdf->stream();
$dompdf->stream('inv_'.$this->Master_model->getInvoiceNumber().'_'.$dts.'.pdf',array('Attachment'=>0));
i had enabling the
ENABLE_REMOTE
to TRUE
Seems like i'm the only one that face the problem, hope someone can help me through this..
Encountered a similar problem on Laravel and tried adding headers. Doesn't work.
I added exit; after stream() and it started displaying. I am guessing the framework may be doing something after stream() causing headers to revert to text/html.
You need to set the header at the top:
header("Content-type: application/pdf");
This should display it in the browser.
If you want it to download set the header like this:
header('Content-disposition: attachment; filename='path/to/file/name.pdf');
this can be set after you have created the pdf and saved it somewhere
NB: path/to/file/name.pdf is on the server not on your local machine
Try to remove some spaces or line breaks between html head body starting and closing tags. Like this <html><head> </head><body> </body><html>.
Also remove thead tbody tfoot tags from your html (sometimes this is not necessary, but in mycase I needed to remove).
And if you are calling the DOM class multiple times. Change the assigned variables (dont let them to be same variable which is in my case was $pdf = new DOMPDF. In second class call I was using same variable. I changed it to $pdf2)
It has taken from here; https://github.com/dompdf/dompdf/issues/902#issuecomment-197655763

PDF created with FPDF cannot be opened by Adobe Reader

My PDF file cannot be opened with Adobe Reader. What's weird is that the PDF used to work in Adobe Reader just a few days ago and now it does not work, and of course I didn't modify the code otherwise it would be easy to fix.
I validated my PDF and learned it was a PDF/A-3, could be that it is not a PDF/A-1? If so why did it work for a time and suddenly stopped working?
EDIT
The problem was that somehow, some HTML code was output inside the PDF file, thus making the PDF file invalid for Adobe Reader, but not for Firefox, making all this much more confusing than it should be.
So a tip to anyway having trouble with PDF, open it with a text editor such as Notepad++ for Windows or GEdit for Linux, and compare with another PDF file which works fine. You should find the problem pretty quickly.
I read a lot of questions about this and I understood that the problem is happening with:
ob_start();
Without this line, my FPDF was not working with the message explained that there was another buffer first.
With this line, the PDF was readable only with Browser.
I changed this line to:
ob_clean();
and now I can open PDF with any reader.
This was happening to me, too. It did work in Firefox for me, but not in Chrome and it wouldn't open in Adobe.
The problem was that I was trying to run the script in a function and calling the function from a button. I fixed it simply by adding the script to it's own PHP file, and then linking to the php file directly.
Note: I did try ob_start() (and alternatively ob_clean() as noted in the other answer) and ob_end_flush(), but it didn't make a difference in the function. When it's in its own file it doesn't need it anyway.
// file.php
<?php
require $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/eri-webtools-plugin/libraries/fpdf/fpdf.php'; // <-- File path for WordPress plugin
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output(); // To Download, use $pdf->Output('D', 'test.pdf', true);
?>
// html
View PDF

FPDF error: Some data has already been output, can't send PDF file

well I get this error trying to use php class FPDF:
FPDF error: Some data has already been output, can't send PDF file (output started at
/mnt/webc/e1/12/5691512/htdocs/adminpanel/fpdf/test.php:1)
My test.php
<?php
require_once("fpdf.php");
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
There are no blanks or anything... So where is the error???
Some editors adds BOM at the start of a file.
View your file in hex and remove it
it is becouse of two reason
1-there is no leading space before the opening
2-are some data has been output before
The solution of 2 reson is
go to fpdf.inc.php
and find this funciton
function Output($name='', $dest='') {
and then in the defination of this function write this at starting
ob_clean();
this will clean the previous output.
For me, it was the deprecation warnings. I added & ~E_DEPRECATED to my error_reporting in my php.ini and rebooted Apache.
I got same problem in Live Server only. But its working on Local Machine. Adds BOM at the start of a file also its not working on Server. But working in local Machine. Some changes need in your Live code.
1. Place the ob_start() in first line of your file.
Example:
ob_start();
$DOCROOTPATH = $_SERVER['DOCUMENT_ROOT'];
$DOCROOTBASEPATH = dirname($_SERVER['DOCUMENT_ROOT']);
include_once($DOCROOTPATH."/lib/commonarray.inc");
include_once($DOCROOTPATH."/includes/class.payslip.php");
include_once($_SERVER['DOCUMENT_ROOT']."/menucontrol.php");
define('FPDF_FONTPATH','fpdf/font/');
require('fpdf/fpdf.php');
2. After the $pdf->Output(),you should place ob_end_flush() in Same File .
Example:
$pdf=new PDF();
$pdf->Open();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',12);
$pdf->pdfAllPages();
$pdf->Output();
ob_end_flush();
Now go to hit the browser and see the pdf which you want.
(OR)
Some editors adds BOM at the start of a file.
View your file in hex and remove it

Categories