yii2tech / html2pdf Goto Github PK
View Code? Open in Web Editor NEWYii2 component for HTML to PDF conversion
License: Other
Yii2 component for HTML to PDF conversion
License: Other
in my main.php
'html2pdf' => [
'class' => 'yii2tech\html2pdf\Manager',
//'viewPath' => '@app/views/pdf',
'converter' => [
'class' => 'yii2tech\html2pdf\converters\Wkhtmltopdf',
'defaultOptions' => [
'pageSize' => 'A4'
],
]
],
I installed the windows version here
https://wkhtmltopdf.org/downloads.html
Unable to convert file 'C:\xampp\htdocs\yii2\frontend\runtime\html2pdf\wkh3801.tmp.html': 'wkhtmltopdf' is not recognized as an internal or external command,
operable program or batch file.
How do i get it to work on my localhost? and once i move my site to my ubuntu server? What am i missing here? Thanks
Q | A |
---|---|
This Package Version | 1.?.? |
Yii Framework Version | 2.0.43 |
PDF Converter | wkhtmltopdf |
PDF Converter Version | ?.?.? |
PHP version | 8.0.8 |
Operating system | Windows 10 |
It has taken me "ages" to get the cover, headers and footers and toc correctly rendered into the pdf.
The problem was that the order in the command of the option is important!
If the order is something like:
cover, header-html, footer-html
The headers and footers wont be rendered
cover, toc, header-html, footer-html
The headers and footers will only be on the toc page.
The order is impotent!
The options must be used in that order:
header-html, footer-html, cover, toc
To get the cover (which is rendered without header footer), toc (with header footer) and all other pages with header + footer rendered.
I found this here:
https://stackoverflow.com/questions/10583272/wkhtmltopdf-header-on-every-page
maybe it will be good if those options are added to the command manually and not by
foreach ($this->normalizeOptions($options)
At least this is the issue with the windows version wkhtmltopdf 0.12.4 (with patched qt)
I get this exception when trying the second example below:
Yii::$app->html2pdf
->render('invoice', ['user' => Yii::$app->user->identity])
->saveAs('/path/to/output.pdf');
Unable to convert file '/var/www/yii2-project/runtime/html2pdf/wkhtmltopdfT3fSRk.html': Loading pages (1/6)
[> ] 0%
[======> ] 10%
[======> ] 10%
[============================================================] 100%
Counting pages (2/6)
[============================================================] Object 1 of 1
Resolving links (4/6)
[============================================================] Object 1 of 1
Loading headers and footers (5/6)
Printing pages (6/6)
[> ] Preparing
[============================================================] Page 1 of 1
Done
Exit with code 1 due to network error: ContentNotFoundError
Hi i have created a pdf from a view.
The pdf is correctly rendered.
How can i "send" the file?
I tried:
$pdf->send($file, $options = ['inline'=> false]);
$pdf->send($file, $options = ['inline'=> false]);
But always getting an error.
The problem is that the Tempfile destructor deletes the file automatically on php end.
https://github.com/yii2tech/html2pdf/blob/master/src/TempFile.php#L36
So that the File couldn't been send because it's already deleted.
If i remove that line the file sending works flawlessly.
Wouldn't at be better to delete the file after download?
Yii::$app->response->sendFile($pdf->name)->on(\yii\web\Response::EVENT_AFTER_SEND, function ($event) {
unlink($event->data);
}, $pdf->name);
Of course i could create another copy of that file, but then i don't understand the functions to send that file.
But maybe there is another solution which i don't know to prevent the call of the __destruct
call.
Generate pdf
Get generated pdf
Exception
html2pdf - 1.0.7
Yii2 - 2.0.40-dev
PDF Converter - wkhtmltopdf
PDF Converter Version - 0.12.x
PHP - 7.2 - 7.4
OS - Centos 6, Ubuntu 20
To avoid "Unable to write to destination" or "Block access to file ..." errors, please extend Manager to support cli arguments, which fix these issues.
Arguments are:
--enable-local-file-access
--disable-local-file-access
--allow
Reference: https://stackoverflow.com/questions/62315246/wkhtmltopdf-0-12-6-warning-blocked-access-to-file
In 7.* branch Mpdf use namespaces and this is producing class not found
error.
Exception 'Error' with message 'Class 'mPDF' not found'
in /***/vendor/yii2tech/html2pdf/converters/Mpdf.php:39
docs: https://mpdf.github.io/fonts-languages/fonts-in-mpdf-7-x.html
from yii2tech\html2pdf\converters\Mpdf, this line should merged with defaults config from Mpdf (see docs) or should be removed. With one font dir i got errors about include defaults fonts
if (isset($options['fontDir'])) {
$config['fontDir'] = Yii::getAlias($options['fontDir']);
unset($options['fontDir']);
}
my call:
$html = $this->render('pdf', [
'model' => $model,
]);
$defaultConfig = (new \Mpdf\Config\ConfigVariables())->getDefaults();
$fontDirs = $defaultConfig['fontDir'];
$defaultFontConfig = (new \Mpdf\Config\FontVariables())->getDefaults();
$fontData = $defaultFontConfig['fontdata'];
$path = Yii::getAlias('@app/data/pdf/');
$targetFile = $path . $model->qr_key . '.pdf';
$fontDir = Yii::getAlias('@app/data/fonts/Roboto');
$options = [
'fontDir' => array_merge($fontDirs, [
$fontDir,
]),
'fontdata' => $fontData + [
'Roboto' => [
'R' => 'Roboto-Regular.ttf',
'I' => 'Roboto-Italic.ttf',
'B' => 'Roboto-Bold.ttf',
]
],
'default_font' => 'Roboto'
];
Yii::$app->html2pdf
->convertFile($path . 'pdf-template-raw.html', $options)
->saveAs($targetFile);
Error:
yii\base\ErrorException: strncmp() expects parameter 1 to be string, array given in /var/www/site/vendor/yiisoft/yii2/BaseYii.php:133
Stack trace:
#0 /var/www/site/vendor/yii2tech/html2pdf/src/converters/Mpdf.php(47): yii\BaseYii::getAlias()
#1 /var/www/site/vendor/yii2tech/html2pdf/src/BaseConverter.php(33): yii2tech\html2pdf\converters\Mpdf->convertInternal()
#2 /var/www/site/vendor/yii2tech/html2pdf/src/BaseConverter.php(41): yii2tech\html2pdf\converters\Mpdf->convert()
#3 /var/www/site/vendor/yii2tech/html2pdf/src/Manager.php(241): yii2tech\html2pdf\converters\Mpdf->convertFile()
#4 /var/www/site/controllers/DocumentController.php(521): yii2tech\html2pdf\Manager->convertFile()
#5 /var/www/site/vendor/yiisoft/yii2/base/InlineAction.php(57): app\controllers\DocumentController->actionPdf()
#6 /var/www/site/vendor/yiisoft/yii2/base/InlineAction.php(57): ::call_user_func_array:{/var/www/site/vendor/yiisoft/yii2/base/InlineAction.php:57}()
#7 /var/www/site/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams()
#8 /var/www/site/vendor/yiisoft/yii2/base/Module.php(528): app\controllers\DocumentController->runAction()
#9 /var/www/site/vendor/yiisoft/yii2/web/Application.php(103): yii\web\Application->runAction()
#10 /var/www/site/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest()
#11 /var/www/site/web/index.php(48): yii\web\Application->run()
#12 {main}
my versions:
"mpdf/mpdf": "^7.1.0",
"yii2tech/html2pdf": "~1.0.0",
"yiisoft/yii2": "~2.0.16",
PHP 7.1
2019-06-19 10:52:44 [error][yii\base\ErrorException:2] yii\base\ErrorException: unlink(project/runtime/html2pdf/html2pdf5d09cdac4814a4.39909384.pdf): Text file busy in project/vendor/yiisoft/yii2/helpers/BaseFileHelper.php:407
Stack trace:
#0 project/vendor/yii2tech/html2pdf/src/TempFile.php(98): yii\helpers\BaseFileHelper::unlink()
#1 project/vendor/yii2tech/html2pdf/src/TempFile.php(36): yii2tech\html2pdf\TempFile->delete()
#2 project/controllers/FilesController.php(91): yii2tech\html2pdf\TempFile->__destruct()
#3 project/vendor/yiisoft/yii2/base/InlineAction.php(57): app\controllers\FilesController->actionAct()
#4 project/vendor/yiisoft/yii2/base/InlineAction.php(57): ::call_user_func_array:{project/vendor/yiisoft/yii2/base/InlineAction.php:57}()
#5 project/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams()
#6 project/vendor/yiisoft/yii2/base/Module.php(528): app\controllers\FilesController->runAction()
#7 project/vendor/yiisoft/yii2/web/Application.php(103): yii\web\Application->runAction()
#8 project/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest()
#9 project/web/index.php(10): yii\web\Application->run()
#10 {main}
Usages:
// FilesController.php
$response = \Yii::$app->html2pdf->render('upload', [
'upload' => $upload,
'company' => $company,
'otherData' => $otherData,
'format' => new Format(),
])->send(uniqid('', true) . '.pdf');
return $response;
// upload.php
<a class="download-doc" href="<?= \yii\helpers\Url::to([
'/files/act',
'upload_id' => $upload->id,
]) ?>"><i class="icon"></i>Скачать документ</a>
Possible reasons:
No closed an open file pointer in class TempFile method send
Component | Version
html2pdf | 1.0.5
Yii | 2.0.15.1
Composer | 1.6.5
PHP | 7.2.12
Operating system | Vagrant 2.2.3 / CentOS Linux release 7.6.1810
After the documentation https://wkhtmltopdf.org/usage/wkhtmltopdf.txt
and the manual printed by -h option.
The parameter is page-size
not pageSize
as it is used in the readme
https://github.com/yii2tech/html2pdf/blob/master/README.md
if the same "defaultOptions" should be used regarding if the converter is mpdf or wkhtmltopdf then it must be replaced for wkhtmltopdf.
Anyhow the given examples sets pageSize for the wkhtmltopdf which is not correct.
Yii::$app->html2pdf
->convert($html)
->saveAs('/path/to/output.pdf');
It gives following error
Getting unknown property: yii\web\Application::html2Pdf
When calling yii2tech\html2pdf\Manager::convert()
with mPDF as the converter, the following exception is thrown:
Mpdf\MpdfException: Temporary files directory "/my-project/vendor/mpdf/mpdf/src/Config/../../tmp" is not writable in /my-project/vendor/mpdf/mpdf/src/Cache.php:17
Stack trace:
#0 /my-project/vendor/mpdf/mpdf/src/Mpdf.php(983): Mpdf\Cache->__construct('/my-project/ven...')
#1 /my-project/vendor/yii2tech/html2pdf/src/converters/Mpdf.php(42): Mpdf\Mpdf->__construct(Array)
#2 /my-project/vendor/yii2tech/html2pdf/src/BaseConverter.php(33): yii2tech\html2pdf\converters\Mpdf->convertInternal('<!DOCTYPE html>...', '/my-project/run...', Array)
#3 /my-project/vendor/yii2tech/html2pdf/src/Manager.php(224): yii2tech\html2pdf\BaseConverter->convert('<!DOCTYPE html>...', '/my-project/run...', Array)
#4 /my-project/controllers/SiteController.php(23): yii2tech\html2pdf\Manager->convert('<!DOCTYPE html>...')
#5 [internal function]: app\controllers\backend\SiteController->actionPdf()
#6 /my-project/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#7 /my-project/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#8 /my-project/vendor/yiisoft/yii2/base/Module.php(528): yii\base\Controller->runAction('pdf', Array)
#9 /my-project/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction('backend/site/pd...', Array)
#10 /my-project/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#11 /my-project/web/index.php(31): yii\base\Application->run()
#12 {main}
This happens because the constructor of the main mPDF object requires tempDir
to be already properly configured when instantiating its Mpdf\Cache
in Mpdf\Mpdf::__construct()
(line 983 in v7.1.0):
$this->cache = new Cache($config['tempDir']);
the default value for which comes from Mpdf\Config\ConfigVariables::$defaults
:
$this->defaults = [
...
'tempDir' => __DIR__ . '/../../tmp',
...
];
but your yii2tech\html2pdf\converters\Mpdf::convertInternal()
does not set it to a valid value when instantiating mPDF:
$pdf = new \Mpdf\Mpdf([
'mode' => $charset,
'format' => $pageSize,
]);
so that even setting tempDir
properly in yii2tech\html2pdf\converters\Mpdf::$defaultOptions
has no effect.
Get cracking! 😉
EDIT:
Component | Version |
---|---|
html2pdf | 1.0.3 |
mPDF | 7.1.0 |
Yii | 2.0.15.1 |
Composer | 1.6.5 |
PHP | 7.0.30 |
Operating system | Ubuntu 16.04.4 LTS |
Exception – yii\base\Exception Unable to convert file '/Applications/XAMPP/xamppfiles/htdocs/sahel/backend/runtime/html2pdf/wkhtmltopdfAsG4nc.html': sh: wkhtmltopdf: command not found
when i want create pdf i get above error .
`$html = <<<HTML
Simple Content
HTML; Yii::$app->html2pdf ->convert($html) ->saveAs(base_dir."up/".rand(9,9999).".pdf");` 'html2pdf' => [ 'class' => 'yii2tech\html2pdf\Manager', 'viewPath' => '@app/pdf', 'converter' => 'wkhtmltopdf', ],
where am i go wrong !
Is there are posibility to convert html page that generates from controller/view with css and other like in mPDF
i have page:
site.com/page/
how can i generate pdf from this page
mPDF its like this:
class PrintController extends Controller
{
public function actionPrint()
{
$this->layout = "print";
..................
$render = $this->render('....................', [
.......................
]);
$mpdf = new Mpdf(
[
'mode' => '+aCJK',
"autoScriptToLang" => true,
"autoLangToFont" => true,
]
);
$mpdf->SetMargins(0,0,5);
$mpdf->SetDisplayMode('fullpage');
$stylesheet = file_get_contents('........................'); // external css
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($render);
$mpdf->Output();
}
or u can save it to file.
html2pdf can do like this?
I have a download button in gridview actions, which should generate pdf based on current row model. No errors appear, but the pdf is empty.
View being converted to pdf
<?php
/* @var $this \yii\web\View */
/* @var $context \yii2tech\html2pdf\Template */
/* @var $app \app\models\ApplicationForm */
$context = $this->context;
// specify particular PDF conversion for this template:
$context->pdfOptions = [
'pageSize' => 'A4',
// ...
];
?>?>
<html>
<head>
<title><?= $app->getFullName() ?> | <?= $app->title ?></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="keywords" content="" />
<meta name="description" content="" />
</head>
<body>
<div id="doc2" class="yui-t7">
<div id="inner">
<div id="hd">
<div class="yui-gc">
<div class="yui-u first">
<h1><?= $app->getFullName() ?></h1>
<h2><?= $app->title ?></h2>
</div>
<div class="yui-u">
<div class="contact-info">
<h3><?= $app->phone ?></h3>
<h3><a href="mailto:<?= $app->email ?>"><?= $app->email ?></a></h3>
<h3><?= $app->address ?></h3>
</div><!--// .contact-info -->
</div>
</div><!--// .yui-gc -->
</div><!--// hd -->
<div id="bd">
<div id="yui-main">
<div class="yui-b">
<div class="yui-gf">
<div class="yui-u first">
<h2>Education</h2>
</div><!--// .yui-u -->
<div class="yui-u">
<?php foreach($edus as $edu): ?>
<div class="job">
<h2><?= $edu->institution ?></h2>
<h3><?= $edu->specialization ?> - <?= $edu->degree->degree ?></h3>
<h4><?= $edu->start_date ?>-<?= $edu->end_date ?></h4>
</div>
<?php endforeach; ?>
</div><!--// .yui-u -->
</div><!--// .yui-gf -->
<div class="yui-gf last">
<div class="yui-u first">
<h2>Experience</h2>
</div><!--// .yui-u -->
<div class="yui-u">
<?php foreach($exps as $exp): ?>
<div class="job">
<h2><?= $exp->company ?></h2>
<h3><?= $exp->industry ?> - <?= $exp->title ?></h3>
<h4><?= $exp->start_date ?>-<?= $exp->end_date ?></h4>
<p><?= $exp->summary ?></p>
</div>
<?php endforeach; ?>
</div><!--// .yui-u -->
</div><!--// .yui-gf -->
</div><!--// .yui-b -->
</div><!--// yui-main -->
</div><!--// bd -->
</div><!-- // inner -->
</div><!--// doc -->
</body>
</html>
Controller action
public function actionGenerate($id)
{
$app = ApplicationForm::findOne($id);
$edus = EduForm::find()->where(['app_id'=>$app->id])->all();
$exps = ExpForm::find()->where(['app_id'=>$app->id])->all();
$path = Yii::getAlias('@webroot') . '/uploads/resumes/' . $app->getFullName() . '\'s_resume.pdf';
Yii::$app->html2pdf
->render('resume',
[
'app' => $app,
'edus' => $edus,
'exps' => $exps
]
)->saveAs($path);
if (file_exists($path)) {
return Yii::$app->response->xSendFile($path);
} else {
throw new NotFoundHttpException("{$app->getFullName()}'s_resume.pdf file doesn't exist");
}
}
Gridview action buttons
[
'class' => 'yii\grid\ActionColumn',
'template' => '{download} {view} {delete}',
'buttons' => [
'download' => function ($url, $model) {
return Html::a(
'<span class="fa fa-download"></span>',
['candidate/generate', 'id' => $model->id],
[
'title' => 'Download PDF',
'data-pjax' => '0',
]
);
},
],
],
layout
<?php
/* @var $this \yii\web\View */
/* @var $content string */
?>
<?= $content ?>
hi,
i am getting error
Unable to convert file 'I:\xx\xx\frontend\runtime\html2pdf\wkh54DA.tmp.html': The filename, directory name, or volume label syntax is incorrect.
$report=$this->renderPartial('pdf',['objectPrint'=>$result_object]); Yii::$app->html2pdf ->convert($report) ->saveAs('/path/to/output.pdf');
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.