I am using mPDF to save form input data to PDF. For English, it is working fine. Anyone can use this code to save HTML Form data to PDF.
Issue: In order to fulfill my project requirement I need to use the Chinese Language. My current code is not working for that.
Form.html
<form action='processPDF.php' method='post'>
<label for="name">Name</label>
<input name="name" type="text" id="name">
<input type='submit' name='submit' value='Download PDF'>
</form>
processPDF.php
<?php
header('Content-Type: text/html; charset=UTF-8');
if (isset($_POST['submit'])) {
if (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$Larmtid = '';
}
if (!isset($error)) {
ob_start();
?>
<div style="padding:20px;">
<p>Name: <?php
echo $name;
?></p>
</div>
<?php
$body = ob_get_clean();
$body = iconv('UTF-8', 'UTF-8//IGNORE', $body);
$body = iconv('UTF-8', 'UTF-8//TRANSLIT', $body);
include("mpdf/mpdf.php");
$mpdf = new \mPDF('c', 'A4', '', '', 0, 0, 0, 0, 0, 0);
$mpdf->SetAutoFont();
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
$mpdf->WriteHTML($body);
$mpdf->Output('SavePDF.pdf', 'D');
}
}
?>
The problem I am having is: In the input field, I typed 怎么用中文说话 and it prints ��������.
If you want to download the source code here is the link to the code
Do not use 'c' as a $mode parameter, that means PDF core fonts only and they do not support chinese characters.
Try '+aCJK' or '-aCJK' instead.
See example – files using chinese font.
My Code is as follow [mpdf v7.0 from composer]
<?php
require_once './vendor/autoload.php';
//report errors
error_reporting(E_ALL);
ini_set("display_errors", 1);
$config = [
'mode' => '+aCJK',
// "allowCJKoverflow" => true,
"autoScriptToLang" => true,
// "allow_charset_conversion" => false,
"autoLangToFont" => true,
];
$mpdf=new \Mpdf\Mpdf($config);
$mpdf->WriteHTML('Hello World 中文');
$mpdf->Output();
This code works fine, you can try it
// We can pass Language code in mpdf config using mode.
<?php
$config = [
'mode' => [LANGUAGE_CODE], // Example: zh-Hans, en, fr etc
];
$mpdf = new \Mpdf\Mpdf($config);
To display Chinese characters correctly, we need to download a fully Chinese support font and place it into a directory, for instance: /app/fonts/yahei.ttf
We can instance it using ConfigVariables and FontVariables:
use Mpdf\Config\ConfigVariables;
use Mpdf\Config\FontVariables;
// Get the default font dirs and append the custom path to it
$defaultConfig = (new ConfigVariables())->getDefaults();
$fontDirs = $defaultConfig['fontDir'];
$fontDirs[] = '/app/fonts/';
// Get the default font data and add the yahei font
$defaultFontConfig = (new FontVariables())->getDefaults();
$fontData = $defaultFontConfig['fontdata'];
$fontData['yahei'] = [
'R' => 'yahei.ttf'
];
$mpdf = new \Mpdf\Mpdf([
'mode' => '+aCJK',
'setAutoTopMargin' => 'stretch',
'setAutoBottomMargin' => 'stretch',
'default_font' => 'yahei',
"autoScriptToLang" => true,
"autoLangToFont" => true,
'fontDir' => $fontDirs,
'fontdata' => $fontData,
]);
Now you can display Chinese characters
Related
When i generate the final PDF the version is being displayed.
Is there any way to hide this information ?
I looked into the package documentation but i could not find anything.
This is information I do not want to share.
I checked if there are any functions but I can't find any.
Here is my code that i use to generate the pdf
$pdf = new \TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdfParams = $this->handlePageParamsByCoverSize($coverSize);
$fontSize = $this->calculateFontSizeByCoverSize($coverSize);
$scissorsIconPath = $this->fileLocator->locate('scissors.png');
$pdf->SetFont(
'helvetica',
'',
$fontSize
);
$pdf->AddPage('L', $pdfParams['format'], true, true);
$pdf->Image(
$coverPath,
$pdfParams['cover']['x'],
$pdfParams['cover']['y'],
$pdfParams['cover']['w'],
$pdfParams['cover']['h'],
'',
'',
'',
false,
300,
'',
false,
false,
0
);
$pdf->Image(
$scissorsIconPath,
$pdfParams['scissorsIcon']['x'],
$pdfParams['scissorsIcon']['y'],
$pdfParams['scissorsIcon']['w'],
$pdfParams['scissorsIcon']['h'],
'',
'',
'',
false,
300,
'',
false,
false,
0
);
$filePath = '/covers/' .$coverName . '.pdf';
$absFileName = $rootPath . $filePath;
try {
$pdf->Output($absFileName, 'F');
} catch (\Exception $e) {
//Move on
}
if (file_exists($absFileName)) {
$result = [
'absPath' => $absFileName,
'path' => $filePath,
];
} else {
$result = ['path' => 'error'];
}
return $result;
I am using the following package
"tecnickcom/tcpdf": "^6.4"
EDIT: Add code and more informations
TCPDF seems to have to methods that might help you:
$tcpdf->SetCreator('My PDF-Generator tool');
$tcpdf->SetAuthor('Your name');
I haven't tried it by myself. I just had a look at the examples of the TCPDF documentation.
Well, if you use a free lib it's quite normal that you can't change that. It would be the same case with other products.
But if you search with a tool such as ripgrep in the source code, you'll see that this string is defined in include/tcpdf_static.php at line 127 and is called by tcpdf.php at two places:
rg "getTCPDFProducer"
Output:
include\tcpdf_static.php
127: public static function getTCPDFProducer() {
tcpdf.php
9554: $out .= ' /Producer '.$this->_textstring(TCPDF_STATIC::getTCPDFProducer(), $oid);
9649: $xmp .= "\t\t\t".'<pdf:Producer>'.TCPDF_STATIC::_escapeXML(TCPDF_STATIC::getTCPDFProducer()).'</pdf:Producer>'."\n";
So if you really have to hide that, you should find a way to override that method, eventually apply a home-made patch or alter the generated file during or after generation.
Using mpdf in a Scriptcase application:
using mpdf 8.0.0 and php 7.0.22
$mpdf = new \Mpdf\Mpdf(
[
'mode' => 'utf-8',
'format' => 'A4',
'orientation' => 'P'
]
);
$mpdf->setFooter('{PAGENO}');
$mpdf->SetTitle($product_naam);
$mpdf->WriteHTML($content);
} catch (\Mpdf\MpdfException $e)
{
echo $e->getMessage();
}
results in a string $pageno in the footer of my PDF output, instead of giving the page number.
Does anyone have workaround for this issue?
Here is the answer:
define ("PAGE", chr (123). 'PAGENO}', TRUE);
$mpdf->setFooter(PAGE);
Ref: https://forum.scriptcase.com.br/t/resolvido-problema-com-no-pdf/12501
I am trying to get a document generated on a php site. It is all working well but the last thing is to add a header to the top of every page after the title page. I have tried so many things and the closest I can get to what I want is the following (stripped down) code.
ob_start();
$mpdf = new Mpdf();
$mpdf->SetDisplayMode('fullpage');
$mpdf->bleedMargin = 0;
$mdpf->crossMarkMargin = 0;
$mpdf->cropMarkMargin = 0;
$mpdf->nonPrintMargin = 0;
// Home page and headers...
$html_header = 'Some Code here';
$mpdf->DefHTMLHeaderByName('PgHeader', $html_header);
$mpdf->AddPage();
$mpdf->Image('cover.jpg', 0, 0, 210, 297, 'jpg', '', true, false);
// Get the content of any pages we have
if($pdf_pages) {
foreach($pdf_pages as $key=>$pg) {
$mpdf->AddPageByArray(array(
'mgt' => '40',
'odd-header-name' => 'PgHeader'
));
$html .= 'the content from the loop';
// Write some HTML code:
$custom_sheet = file_get_contents('/custom.css');
$mpdf->WriteHTML($custom_sheet, 1);
$mpdf->WriteHTML($html, 2);
}
}
// Output a PDF file directly to the browser
$mpdf->Output('Name.pdf', 'I');
ob_end_flush();
I have tried changing the odd-header-name to html_PgHeader based on the documentation but in either case, I get the margin, all the content but the header never shows up. Why? Why is it not being assigned so I can call it in the AddPageByArray?
According to the documentation you need to prefix header/footer names with 'html_'
Try changing;
'odd-header-name' => 'PgHeader',
to;
'odd-header-name' => 'html_PgHeader',
reference here
To show header, you need to add odd-header-value option to AddPageByArray method with value 1.
ob_start();
$mpdf = new Mpdf();
$mpdf->SetDisplayMode('fullpage');
$mpdf->bleedMargin = 0;
$mdpf->crossMarkMargin = 0;
$mpdf->cropMarkMargin = 0;
$mpdf->nonPrintMargin = 0;
// Home page and headers...
$html_header = 'Some Code here';
$mpdf->DefHTMLHeaderByName('PgHeader', $html_header);
$mpdf->AddPage();
$mpdf->Image('cover.jpg', 0, 0, 210, 297, 'jpg', '', true, false);
$pdf_pages = array('key' => 'val');
// Get the content of any pages we have
if($pdf_pages) {
foreach($pdf_pages as $key=>$pg) {
$mpdf->AddPageByArray(array(
'mgt' => '40',
'odd-header-name' => 'PgHeader',
'odd-header-value' => 1,
));
$html .= 'the content from the loop';
// Write some HTML code:
$custom_sheet = file_get_contents('/custom.css');
$mpdf->WriteHTML($custom_sheet, 1);
$mpdf->WriteHTML($html, 2);
}
}
// Output a PDF file directly to the browser
$mpdf->Output('Name.pdf', 'I');
ob_end_flush();
Pt.II
If this, don't help, then try this scenario:
Open console and go to site's root path.
Create index.php file
Run composer require mpdf/mpdf (install composer, if you don't have it).
Paste this code to the index.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
ob_start();
$mpdf = new \Mpdf\Mpdf();
/** same code from previous example here, except Mpdf init **/
Try something like this
#page {
header: header_name;
footer: footer_name;
}
It might help you.
Url: https://mpdf.github.io/headers-footers/headers-footers.html
I have generated a PDF using mpdf library in CodeIgniter. I want to attach header image and footer image with proper margin, I have created one code but header and footer get overlapped.
//controller
$this->load->library('m_pdf');
$param = '"","A4","","",0,0,100,0,6,3,"L"';
$pdf = $this->m_pdf->load($param);
// $pdf->useOddEven = true;
$pdf->SetHTMLHeader('<img src="' . base_url() . 'custom/Hederinvoice.jpg"/>');
$pdf->SetHTMLFooter('<img src="' . base_url() . 'custom/footarinvoice.jpg"/>');
$wm = base_url() . 'custom/Watermark.jpg';
$pdf->SetWatermarkImage($wm);
$pdf->showWatermarkImage = true;
$data['main_content'] = 'dwnld';
$this->load->view('template', $data);
$html = $this->load->view('template_pdf', $data, true);
$this->load->view('template_pdf', $data, true);
$pdf->WriteHTML($html);
$pdf->page = 0;
$pdf->state = 0;
$pdf->Output($pdfFilePath, "D");
$pdf->SetHTMLHeader('<img src="' . base_url() . 'custom/Hederinvoice.jpg"/>');
$pdf->SetHTMLFooter('<img src="' . base_url() . 'custom/footarinvoice.jpg"/>');
$wm = base_url() . 'custom/Watermark.png';
$data['main_content'] = 'dwnld';
//$this->load->view('template', $data);
$html = $this->load->view('template_pdf', $data, true);
$this->load->view('template_pdf', $data, true);
$pdf->AddPage('', // L - landscape, P - portrait
'', '', '', '',
5, // margin_left
5, // margin right
60, // margin top
30, // margin bottom
0, // margin header
0); // margin footer
$pdf->WriteHTML($html);
$pdf->Output($pdfFilePath, "D");
Addpage for to creating page in mpdf and pass parameters of margin top,bottom then we get proper output
You can set custom HTMl Header for first page and Other page as below:
Just add the below snippet above all html content. You can add Inline CSS for it using tags above al html
<htmlpageheader name="firstpage" style="display:none">
<div style="text-align:center"><img src="'.'logo.png"/></div>
</htmlpageheader><sethtmlpageheader name="firstpage" value="on" show-this-page="1" />
<htmlpageheader name="otherpages" style="display:none">
<div style="text-align:center">{PAGENO}</div>
</htmlpageheader><sethtmlpageheader name="otherpages" value="off" />';
Or can use https://mpdf.github.io/headers-footers/headers-footers.html as refrence to use HTML header function
To Set footer one can use:
// Footer Configuration for all pages, can be changed for odd and even pages accordingly
$oddEvenConfiguration =
[
'L' => [ // L for Left part of the header
'content' => 'Your Content',
'font-size' => 10,
'font-family' => 'sans-serif',
'color'=>'#000000'
],
'C' => [ // C for Center part of the header
'content' => '',
],
'R' => [
'content' => '{PAGENO}',
],
'line' => 0, // That's the relevant parameter to remove line style in footer
];
$headerFooterConfiguration = [
'odd' => $oddEvenConfiguration,
'even' => $oddEvenConfiguration
];
I have an html file named welcomemailtemplate.html and I need to convert that file to a PDF.
I first read this file using the following method provided by Yii framework:
$filename = Yii::app()->basePath.'\views\email\welcomemailtemplate.html';
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
$name = $model->name;
fclose($handle);
$message = str_replace ( "[username]", $name, $contents );
Then, to generate the PDF file, the following parameters are set:
Yii::import('application.vendors.*');
require_once('tcpdf/tcpdf.php');
require_once('tcpdf/config/lang/eng.php');
$pdf = new TCPDF();
$pdf->SetCreator("Torget");
$pdf->SetAuthor('test name');
$pdf->SetTitle('Savani Test');
$pdf->SetSubject(' Torget Order Confirmation');
$pdf->SetKeywords(' Torget, Order, Confirmation');
//$pdf->SetHeaderData('', 0, PDF_HEADER_TITLE, '');
$pdf->SetHeaderData('', 0, "Torget Order", '');
$pdf->setHeaderFont(Array('helvetica', '', 8));
$pdf->setFooterFont(Array('helvetica', '', 6));
$pdf->SetMargins(15, 18, 15);
$pdf->SetHeaderMargin(5);
$pdf->SetFooterMargin(10);
$pdf->SetAutoPageBreak(TRUE, 0);
$pdf->SetFont('dejavusans', '', 7);
$pdf->AddPage();
If I pass the content as follows, it creates the PDF:
$pdf->writeHTML("<span>Hello World!</span>", true, false, true, false, '');
But if I pass the read html file content for pdf creating using following method it gives following error:
$pdf->writeHTML($message, true, false, true, false, '');
$pdf->LastPage();
Error message:
Undefined index: thead
Try to validate the file using the w3c validator http://validator.w3.org/.
I've worked with tcpdf before but i gave it up because it didn't seem reliable. You can also try wkhtmltopdf binary (only if your hosting allows you to use proc_open/proc_close). Seems a little more stable to me. It also has a PHP class to help you use it.
CutyCapt seems to be a very good option for you. Its very easy to integrate also.