FPDF cannot display japanese word - php

Now I'm doing a task about exporting data into PDF from CodeIgniter framework. I'm using FPDF http://www.fpdf.org/ for exporting the PDF. And here is my controller:
public function exportPDF()
{
$pdf = new FPDF('l','mm','A4');
// create new page
$pdf->AddPage();
// setting font type
$pdf->SetFont('Arial','B',8);
$pdf->Cell(40,6,'オーダー番号',1,0);
$pdf->Cell(35,6,'デリバリー日',1,0);
$pdf->Cell(30,6,'カスタマー名',1,0);
$pdf->Cell(60,6,'住所',1,0);
$pdf->Cell(12,6,'数量',1,1);
$pdf->SetFont('Arial','',8);
//fetch data
$res['data'] = $this->session->userdata('logistic_account');
$data['orderlist'] = $this->Bll_products->exportPDF($res['data']['logistic_id']);
foreach ($data['orderlist'] as $row) {
$pdf->Cell(40,6,$row->order_number,1,0);
$pdf->Cell(35,6,$row->delivery_date,1,0);
$pdf->Cell(30,6,$row->name,1,0);
$pdf->Cell(60,6,$row->address,1,0);
$pdf->Cell(12,6,$row->order_quantity,1,1);
}
$filename = $res['data']['pic_name']."_".date("Y-m-d H:i:s").'.pdf';
$pdf->Output($filename, 'D');
}
But the result like this:
How do I can display a Japanese word in that .pdf file?

Related

How To Merge 2 PDF in MPDF Using PHP Laravel

I want to Merge 2 pdf stored in my storage folder of Laravel app. i only want to merge using MPDF.
i've a function create pdf. From that Function I created a pdf
Here is the Function to create a PDF.
public function generateProjectPDF(){
$projects = Projects::all();
$file_name = 'Project_Task'.rand(1,1000).'.pdf';
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML(view('pdf.projectpdf',['projects'=>$projects]));
$mpdf->Output('storage/app/files/'.$file_name,'F');
DB::table('merge_pdf')->insert(
[
'name' => $file_name,
]
);
}
Now I have a function to merge 2 pdf.
Now i don't know how to merge the two pdfs.
public function mergePDF(){
$content1 = Storage::get('files/filename.pdf');
$content1 = Storage::get('files/filename.pdf');
}
Change your mergePDF function accordingly.
public function mergePDF(){
$mpdf = new \Mpdf\Mpdf();
$mpdf->SetImportUse(); //only with mPDF <8.0
$pagecount1 = $mpdf->SetSourceFile('file1.pdf');
$tplId1 = $mpdf->importPage($pagecount1);
$mpdf->useTemplate($tplId1);
$pagecount2 = $mpdf->SetSourceFile('file2.pdf');
$tplId2 = $mpdf->importPage($pagecount2);
$mpdf->useTemplate($tplId2);
$mpdf->Output();
}
For more details , please refer https://mpdf.github.io/reference/mpdf-functions/importpage-v8.html
merge multiple pdf using Mpdf library
merge pdf function
function mergePdf($pdfArr){
$pdf = new Mpdf();
foreach($pdfArr as $currentPdf){
$pagecount = $pdf->SetSourceFile($currentPdf);
for($i = 1; $i <= $pagecount; $i++){
$pdf->AddPage();
$tplId = $pdf->importPage($i);
$pdf->useTemplate($tplId);
}
}
//direct show on browser
$pdf->Output();
//spacefic location save file
$outputpath = 'location/output.pdf';
$pdf->Output($outputpath, 'F');
}
Call this function
mergePdf(['path/pdf1.pdf','path/pdf2.pdf', .....])

Tcpdf by using Separate management file

I am using TCPDF to generate the PDF.
I have two files.The contents of the first file are the invoice contents (table, photo, etc..../without code TCPDF)
The contents of the second file are the following code(Coded by my colleague).
$_factorUrl = PathAllocator::getBaseUrlByPath(__FILE__)."modules/printer/views_pdf/".$billName.".php?order_id=".$orderId;
ob_start();
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//Before Write
// set some language dependent data:
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'rtl';
$lg['a_meta_language'] = 'fa';
$lg['w_page'] = 'page';
// set some language-dependent strings (optional)
$pdf->setLanguageArray($lg);
//After Write
$pdf->setRTL(true);
// set font
$pdf->SetFont('dejavusans', '', 12);
// add a page
$pdf->AddPage();
// Persian content
$pdf->WriteHTML(execute($_factorUrl), true, 0, true, 0);
//Close and output PDF document
//$pdf->Output("factor.pdf");
ob_end_clean();
$pdfFileName = $billName."-".$orderId.md5(rand(1,1000).microtime().UserAuth::getCustomerId().$billName.$orderId);
$_fullFilePath = $sourcePath."modules/printer/dl/".$pdfFileName.".pdf";
$pdf->Output($_fullFilePath, 'FI');
header("location: ".PathAllocator::getBaseUrlByPath(__FILE__)."modules/printer/dl/".$pdfFileName.".pdf");
Now I have the output(second image), But no style is applied, the tables do not look good and ...
when I add any tcpdf statement to first file, I have no output.
for example I add to the first file :
<?php
$html = '<h1>Example of HTML text flow</h1>';
?>
first image is Invoice appearance on web page
second image is Invoice pdf
you have to use tcpdf image for background image
https://tcpdf.org/examples/example_009/
and you need to use tcpdf table
https://tcpdf.org/examples/example_045/

Generate HTML to PDF, and upload generated PDF to storage (laravel) (Dompdf Library)

I want to use storeAs() but it doesn't work (Dompdf library)
How to put the converted PDF file in storage ?
$data = ['discription' => 'tifa'];
$pdf = PDF::loadView('file.viewFile', compact('data'))->storeAs("public/uploud",'filename');
return $pdf->stream("file.pdf");`
$data = ['discription'=>'tifa'];
$pdf =PDF::loadView('file.viewFile',compact('data'));
$content = $pdf->output();
$x= storage_path("app/public/uploud/anyname.pdf");
file_put_contents($x, $content);
return $pdf->stream(" anyname.pdf");

Saving HTML content generated by PHP as a PDF file

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);
}

Merge PDF files with PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
My concept is - there are 10 pdf files in a website. User can select some pdf files and then select merge to create a single pdf file which contains the selected pages. How can i do this with php?
Below is the php PDF merge command.
$fileArray= array("name1.pdf","name2.pdf","name3.pdf","name4.pdf");
$datadir = "save_path/";
$outputName = $datadir."merged.pdf";
$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$outputName ";
//Add each pdf file to the end of the command
foreach($fileArray as $file) {
$cmd .= $file." ";
}
$result = shell_exec($cmd);
I forgot the link from where I found it, but it works fine.
Note: You should have gs (on linux and probably Mac), or Ghostscript (on windows) installed for this to work.
i suggest PDFMerger from github.com, so easy like ::
include 'PDFMerger.php';
$pdf = new PDFMerger;
$pdf->addPDF('samplepdfs/one.pdf', '1, 3, 4')
->addPDF('samplepdfs/two.pdf', '1-2')
->addPDF('samplepdfs/three.pdf', 'all')
->merge('file', 'samplepdfs/TEST2.pdf'); // REPLACE 'file' WITH 'browser', 'download', 'string', or 'file' for output options
I've done this before. I had a pdf that I generated with fpdf, and I needed to add on a variable amount of PDFs to it.
So I already had an fpdf object and page set up (http://www.fpdf.org/)
And I used fpdi to import the files (http://www.setasign.de/products/pdf-php-solutions/fpdi/)
FDPI is added by extending the PDF class:
class PDF extends FPDI
{
}
$pdffile = "Filename.pdf";
$pagecount = $pdf->setSourceFile($pdffile);
for($i=0; $i<$pagecount; $i++){
$pdf->AddPage();
$tplidx = $pdf->importPage($i+1, '/MediaBox');
$pdf->useTemplate($tplidx, 10, 10, 200);
}
This basically makes each pdf into an image to put into your other pdf. It worked amazingly well for what I needed it for.
$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=".$new." ".implode(" ", $files);
shell_exec($cmd);
A simplified version of Chauhan's answer
Both the accepted answer and even the FDPI homepage seem to give botched or incomplete examples. Here's mine which works and is easy to implement. As expected it requires fpdf and fpdi libraries:
FPDF: http://www.fpdf.org/en/download.php
FPDI: https://www.setasign.com/products/fpdi/downloads
require('fpdf.php');
require('fpdi.php');
$files = ['doc1.pdf', 'doc2.pdf', 'doc3.pdf'];
$pdf = new FPDI();
// iterate over array of files and merge
foreach ($files as $file) {
$pageCount = $pdf->setSourceFile($file);
for ($i = 0; $i < $pageCount; $i++) {
$tpl = $pdf->importPage($i + 1, '/MediaBox');
$pdf->addPage();
$pdf->useTemplate($tpl);
}
}
// output the pdf as a file (http://www.fpdf.org/en/doc/output.htm)
$pdf->Output('F','merged.pdf');
I've had similar problem in my software. We've wanted to merge several PDF files into one PDF file and submit it to an outer service. We've been using the FPDI solution as shown in Christa's solution.
However, the input PDF's we've been using could be in version higher than 1.7. We've decided to evaluate the FPDI commercial add-on. However, it turned out that some of the documents scanned by our office copier were having malformed indexes, which crashed the commercial FPDI add-on. So we've decided to use Ghostscript solution as in Chauhan's answer.
But then we got some strange metadata in the output PDF properties.
Finally we've decided to join two solutions to get PDF's merged and downgraded by Ghostscript, but the metadata is set by FPDI. We don't know yet how it would work with some advanced formatted pdfs, but for scans we use it works just fine. Here's our class excerpt:
class MergedPDF extends \FPDI
{
private $documentsPaths = array();
public function Render()
{
$outputFileName = tempnam(sys_get_temp_dir(), 'merged');
// merge files and save resulting file as PDF version 1.4 for FPDI compatibility
$cmd = "/usr/bin/gs -q -dNOPAUSE -dBATCH -dCompatibilityLevel=1.4 -sDEVICE=pdfwrite -sOutputFile=$outputFileName";
foreach ($this->getDocumentsPaths() as $pdfpath) {
$cmd .= " $pdfpath ";
}
$result = shell_exec($cmd);
$this->SetCreator('Your Software Name');
$this->setPrintHeader(false);
$numPages = $this->setSourceFile($outputFileName);
for ($i = 1; $i <= $numPages; $i++) {
$tplIdx = $this->importPage($i);
$this->AddPage();
$this->useTemplate($tplIdx);
}
unlink($outputFileName);
$content = $this->Output(null, 'S');
return $content;
}
public function getDocumentsPaths()
{
return $this->documentsPaths;
}
public function setDocumentsPaths($documentsPaths)
{
$this->documentsPaths = $documentsPaths;
}
public function addDocumentPath($documentPath)
{
$this->documentsPaths[] = $documentPath;
}
}
The usage of this class is as follows:
$pdf = new MergedPDF();
$pdf->setTitle($pdfTitle);
$pdf->addDocumentPath($absolutePath1);
$pdf->addDocumentPath($absolutePath2);
$pdf->addDocumentPath($absolutePath3);
$tempFileName = tempnam(sys_get_temp_dir(), 'merged');
$content = $pdf->Render();
file_put_contents($tempFileName, $content);
I have tried similar issue and works fine, try it. It can handle different orientations between PDFs.
// array to hold list of PDF files to be merged
$files = array("a.pdf", "b.pdf", "c.pdf");
$pageCount = 0;
// initiate FPDI
$pdf = new FPDI();
// iterate through the files
foreach ($files AS $file) {
// get the page count
$pageCount = $pdf->setSourceFile($file);
// iterate through all pages
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// import a page
$templateId = $pdf->importPage($pageNo);
// get the size of the imported page
$size = $pdf->getTemplateSize($templateId);
// create a page (landscape or portrait depending on the imported page size)
if ($size['w'] > $size['h']) {
$pdf->AddPage('L', array($size['w'], $size['h']));
} else {
$pdf->AddPage('P', array($size['w'], $size['h']));
}
// use the imported page
$pdf->useTemplate($templateId);
$pdf->SetFont('Helvetica');
$pdf->SetXY(5, 5);
$pdf->Write(8, 'Generated by FPDI');
}
}
This worked for me on Windows
download PDFtk free from https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/
drop folder (PDFtk) into the root of c:
add the following to your php code where $file1 is the location and name of the first PDF file, $file2 is the location and name of the second and $newfile is the location and name of the destination file
$file1 = ' c:\\\www\\\folder1\\\folder2\\\file1.pdf';
$file2 = ' c:\\\www\\\folder1\\\folder2\\\file2.pdf';
$file3 = ' c:\\\www\\\folder1\\\folder2\\\file3.pdf';
$command = 'cmd /c C:\\\pdftk\\\bin\\\pdftk.exe '.$file1.$file2.$newfile;
$result = exec($command);
I created an abstraction layer over FPDI (might accommodate other engines).
I published it as a Symfony2 bundle depending on a library, and as the library itself.
The bundle
The Library
usage:
public function handlePdfChanges(Document $document, array $formRawData)
{
$oldPath = $document->getUploadRootDir($this->kernel) . $document->getOldPath();
$newTmpPath = $document->getFile()->getRealPath();
switch ($formRawData['insertOptions']['insertPosition']) {
case PdfInsertType::POSITION_BEGINNING:
// prepend
$newPdf = $this->pdfManager->insert($oldPath, $newTmpPath);
break;
case PdfInsertType::POSITION_END:
// Append
$newPdf = $this->pdfManager->append($oldPath, $newTmpPath);
break;
case PdfInsertType::POSITION_PAGE:
// insert at page n: PdfA={p1; p2; p3}, PdfB={pA; pB; pC}
// insert(PdfA, PdfB, 2) will render {p1; pA; pB; pC; p2; p3}
$newPdf = $this->pdfManager->insert(
$oldPath, $newTmpPath, $formRawData['insertOptions']['pageNumber']
);
break;
case PdfInsertType::POSITION_REPLACE:
// does nothing. overrides old file.
return;
break;
}
$pageCount = $newPdf->getPageCount();
$newPdf->renderFile($mergedPdfPath = "$newTmpPath.merged");
$document->setFile(new File($mergedPdfPath, true));
return $pageCount;
}
myokyawhtun's solution worked best for me (using PHP 5.4)
You will still get an error though - I resolved using the following:
Line 269 of fpdf_tpl.php - changed the function parameters to:
function Image($file, $x=null, $y=null, $w=0, $h=0, $type='', $link='',$align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0) {
I also made this same change on line 898 of fpdf.php

Categories