I have created a php code to generate a PDF using mPDF. The code works correctly on the local. But on the server this error is shown:
Data has already been sent to output, unable to output PDF file
I searched over net and find these solution all from stackoverflow but non of them works. I tried all these solutions and no one works.
1- There is not output before $pdf->Output() like echo
2- I set ini_set("session.auto_start", 0); before creating PDF
3- I use ob_end_clean with include mPDF library
But when I change output parameter from $pdf->Output('file.pdf','D') to $pdf->Output('file.pdf','F'), the pdf is creating in the directory correctly. (D mean download the file and F means save file in directory)
Why mPDF can create PDF in the server but cannot send to browser and force file to be downloaded? Any suggestion for why file cannot be downloaded by D parameter?
Edit #1: The codes:
<?php
include "/DIR/cost/mpdf/vendor/autoload.php";
if (isset($_POST['hazine'])) {
try{
$mpdf = new \Mpdf\Mpdf();
$rand = rand();
$stylesheet1 = file_get_contents('/DIR/cost/style.css');
$mpdf->WriteHTML($stylesheet1, 1);
ob_start();
include "/DIR/cost/entere_data.php";
include "/DIR/cost/php.php";
ob_end_clean();
include '/DIR/cost/footer.php';
ob_end_clean();
$dir = '/DIR/DCC/DDC' . $rand . '.pdf';
$pdf_file = 'DDC' . $rand . '.pdf';
$mpdf->Output($pdf_file, 'D');
}
} catch(\Mpdf\MpdfException $e){
echo $e->getMessage();
}
}
include "/DIR/cost/form.php";
?>
This 3 includes: include "/DIR/cost/entere_data.php"; , include "/DIR/cost/php.php"; , include '/DIR/cost/footer.php'; are PDF file contents.
I have some issue when i saving RTF file with phpword lib.
I open an RTF file with IOFactory::load, then i save it with function write and I have some metadata on the file i don't know why.
Here is my code:
<?php
include_once 'vendor/phpoffice/phpword/samples/Sample_Header.php';
// Read contents
$name = 'Sample';
$source = __DIR__ . "/vendor/phpoffice/phpword/samples/resources/{$name}.rtf";
echo date('H:i:s'), " Reading contents from `{$source}`", EOL;
$phpWord = \PhpOffice\PhpWord\IOFactory::load($source, 'RTF');
// Save file
echo write($phpWord, basename(__FILE__, '.php'), $writers);
include_once 'vendor/phpoffice/phpword/samples/Sample_Footer.php';
and when i open the new file who have been save It shows:
"Normal;Default Paragraph Font;Normal Table;Body Text;Corps de texte Car;footer;Pied de page Car;page number;Balloon Text;Texte de bulles Car;?;;?;;?;;?;?;?;?;?;?;;http://schemas.microsoft.com/office/word/2003/wordml2450
6
1
...)()()()()()Annexe I"
If someone have an idea why I have some metadata on my file that will be good.
I'm trying to save HTML content generated by PHP as a PDF file.
To do this I found FPDF.
My script is as follows:
if(isset($_POST['content_to_save']) && isset($_POST['name_to_save'])){
$file_name = $_POST['name_to_save'];
$file_content = $_POST['content_to_save'];
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Helvetica','',12);
$pdf->Cell(40,10,$file_content);
$content = $pdf->Output('../my_folder/'.$file_name.'.pdf','F');
}
My two variables ($file_name & $file_content) are set as I want them with no issues and it creates the PDF in the correct location with the correct file name, however the actual content is the HTML in text format rather than the actual rendered HTML.
Edit
I have now started trying to use TCPDF
My code now is as follows:
if(isset($_POST['po_content_to_save']) && isset($_POST['po_name_to_save'])){
$file_name = $_POST['po_name_to_save'];
$file_content = $_POST['po_content_to_save'];
require('TCPDF/tcpdf.php');
$pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetFont('helvetica', '', 12);
$pdf->AddPage();
$pdf->writeHTML($file_content);
$pdf->Output('../my_folder/'.$file_name.'.pdf', 'I');
}
However, now I get the following error:
TCPDF ERROR: Some data has already been output, can't send PDF file
So after alot of trial and error with a few different libraries I finally found Dompdf
The following code now does what I was trying to achieve:
require '../vendor/autoload.php';
use Dompdf\Dompdf;
if(isset($_POST['po_content_to_save']) && isset($_POST['po_name_to_save'])){
$file_name = $_POST['po_name_to_save'];
$file_content = $_POST['po_content_to_save'];
$document = new Dompdf();
$document->loadHtml($file_content);
$document->setPaper('A4', 'portrait');
$document->render();
$output = $document->output();
file_put_contents('../my_folder/'.$file_name.'.pdf', $output);
}
I'm using a PHPWord to create word documents. To do so I'm using layouts:
$template = new \PhpOffice\PhpWord\TemplateProcessor($this->config->application->fileTemplateFolder.'invoice.docx');
$template->setValue('date', date("F jS, Y"));
$temp_file = tempnam(sys_get_temp_dir(), 'invoice_');
$temp_file .= '.docx';
$template->saveAs($temp_file);
It works fine. My problem is to create the a PDF file. Here is how I trying to create the file:
$path = '/Users/andredx/Projects/x/vendor/dompdf/dompdf';
require_once __DIR__ . '/../../vendor/dompdf/dompdf/autoload.inc.php';
\PhpOffice\PhpWord\Settings::setPdfRendererPath($path);
\PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');
$temp_doc = \PhpOffice\PhpWord\IOFactory::load($temp_file); // this line executes
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($temp_doc , 'PDF'); // this one get' my an error which I cannot see
$xmlWriter->save('/Users/andredx/Projects/x/_test.pdf', TRUE);
unlink($temp_file);
I can't figure out what I'm doing wrong. Maybe the path of the converter, but I'm trying to insert the path in many ways and it is not working.
Relevant info: the document has images and tables.
Can you help me to find out what I'm doing wrong?
Thanks
is it possible to edit existing docx file using phpword?
i want to add footer text to my existing docx file.
there are lot of examples but those examples are creating the doc file from scratch not editing the file
can someone link to me an example? thank you
just like this.
<?php
require_once 'PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
// Add header
$header = $section->createHeader();
$table = $header->addTable();
$table->addRow();
$table->addCell(4500)->addText('This is the header.');
$table->addCell(4500)->addImage('_earth.jpg', array('width'=>50, 'height'=>50, 'align'=>'right'));
// Add footer
$footer = $section->createFooter();
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', array('align'=>'center'));
// Write some text
$section->addTextBreak();
$section->addText('Some text...');
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('HeaderFooter.docx');
?>
Yes you can edit.
From documentation
PHPWord is a library written in pure PHP that provides a set of
classes to write to and read from different document file formats. The
current version of PHPWord supports Microsoft Office Open XML (OOXML
or OpenXML), OASIS Open Document Format for Office Applications
(OpenDocument or ODF), and Rich Text Format (RTF).
Actually this is the procedure
Load our existing file as template.
Edit
Save
From the Documentation, I found an example,
<?php
include_once 'Sample_Header.php';
// Template processor instance creation
echo date('H:i:s'), ' Creating new TemplateProcessor instance...', EOL;
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('resources/Sample_07_TemplateCloneRow.docx');
// Variables on different parts of document
$templateProcessor->setValue('weekday', htmlspecialchars(date('l'))); // On section/content
$templateProcessor->setValue('time', htmlspecialchars(date('H:i'))); // On footer
$templateProcessor->setValue('serverName', htmlspecialchars(realpath(__DIR__))); // On header
// Simple table
$templateProcessor->cloneRow('rowValue', 10);
$templateProcessor->setValue('rowValue#1', htmlspecialchars('Sun'));
$templateProcessor->setValue('rowValue#2', htmlspecialchars('Mercury'));
$templateProcessor->setValue('rowValue#3', htmlspecialchars('Venus'));
$templateProcessor->setValue('rowValue#4', htmlspecialchars('Earth'));
$templateProcessor->setValue('rowValue#5', htmlspecialchars('Mars'));
$templateProcessor->setValue('rowValue#6', htmlspecialchars('Jupiter'));
$templateProcessor->setValue('rowValue#7', htmlspecialchars('Saturn'));
$templateProcessor->setValue('rowValue#8', htmlspecialchars('Uranus'));
$templateProcessor->setValue('rowValue#9', htmlspecialchars('Neptun'));
$templateProcessor->setValue('rowValue#10', htmlspecialchars('Pluto'));
$templateProcessor->setValue('rowNumber#1', htmlspecialchars('1'));
$templateProcessor->setValue('rowNumber#2', htmlspecialchars('2'));
$templateProcessor->setValue('rowNumber#3', htmlspecialchars('3'));
$templateProcessor->setValue('rowNumber#4', htmlspecialchars('4'));
$templateProcessor->setValue('rowNumber#5', htmlspecialchars('5'));
$templateProcessor->setValue('rowNumber#6', htmlspecialchars('6'));
$templateProcessor->setValue('rowNumber#7', htmlspecialchars('7'));
$templateProcessor->setValue('rowNumber#8', htmlspecialchars('8'));
$templateProcessor->setValue('rowNumber#9', htmlspecialchars('9'));
$templateProcessor->setValue('rowNumber#10', htmlspecialchars('10'));
// Table with a spanned cell
$templateProcessor->cloneRow('userId', 3);
$templateProcessor->setValue('userId#1', htmlspecialchars('1'));
$templateProcessor->setValue('userFirstName#1', htmlspecialchars('James'));
$templateProcessor->setValue('userName#1', htmlspecialchars('Taylor'));
$templateProcessor->setValue('userPhone#1', htmlspecialchars('+1 428 889 773'));
$templateProcessor->setValue('userId#2', htmlspecialchars('2'));
$templateProcessor->setValue('userFirstName#2', htmlspecialchars('Robert'));
$templateProcessor->setValue('userName#2', htmlspecialchars('Bell'));
$templateProcessor->setValue('userPhone#2', htmlspecialchars('+1 428 889 774'));
$templateProcessor->setValue('userId#3', htmlspecialchars('3'));
$templateProcessor->setValue('userFirstName#3', htmlspecialchars('Michael'));
$templateProcessor->setValue('userName#3', htmlspecialchars('Ray'));
$templateProcessor->setValue('userPhone#3', htmlspecialchars('+1 428 889 775'));
echo date('H:i:s'), ' Saving the result document...', EOL;
$templateProcessor->saveAs('results/Sample_07_TemplateCloneRow.docx');
echo getEndingNotes(array('Word2007' => 'docx'));
if (!CLI) {
include_once 'Sample_Footer.php';
}
Now see the lines of code given below , how to access existing header and footer
$headers = $section->getHeaders();
$header1 = $headers[1]; // note that the first index is 1 here (not 0)
$elements = $header1->getElements();
$element1 = $elements[0]; // and first index is 0 here normally
// for example manipulating simple text information ($element1 is instance of Text object)
$element1->setText("adding text here - old part: " . $element1->getText());
$footers = $section->getFooters(); // to access footer
You can find more examples here . If you want to add more styles, please read this page. And you can also see some recipes in their documentation.
In the footer of your file(template) docx, you can put a variable like this ${var1}.
Open a file as template with "TemplateProcessor".
$templateObject = new TemplateProcessor($filename);
Replace var1 variable in your file
$templateObject->setValue('var1', 'test');
Transform your template into a PhpWord
$fileName = $templateObject->save();
$phpWordObject = IOFactory::load($fileName);
unlink($fileName);
return $phpWordObject;
Save/Render your phpWord instance
// create the writer
$writer = $this->wordService->createWriter($phpWordObject, 'Word2007');
// create the response
$response = $this->wordService->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'export.docx'
);
$response->headers->set('Content-Type', 'application/msword');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
Might be useful for Laravel 5 users. You can use this in your controllers.
public function wordDocumentFromWordTemplate() {
$templateFile = public_path('templates') . '/template-file.docx';
$templateObject = new TemplateProcessor($templateFile);
$templateObject->setValue('var1', 'Text for var1');
$wordDocumentFile = $templateObject->save();
$headers = [
'Content-Type' => 'application/msword',
'Cache-Control' => 'max-age=0'
];
return response()->download($wordDocumentFile, 'result.docx', $headers);
}