- генерация PDF на основе ресурсов
- Комментарии: 5
- Saved searches
- Use saved searches to filter your results more quickly
- License
- sjstoelting/MODx-htmlToPDF
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- printPdf
- Как создать pdf файл:
- Css классы:
- Js cобытия:
- startPrint
- createPdf
- Дерево настроек:
- 1.1.1-pl (15.12.21)
- 1.1.0-pl (23.03.20)
- 1.0.1-pl
- 1.0.0-pl
генерация PDF на основе ресурсов
Добрый день, подскажите пожалуйста каким образмо можно сгенерировать pdf с помощью HTMLTOPDF чтобы в pdf можно было вывести картинки из тв или результат работы какого нибудь сниппета?
Сергей Скат /users/shectermen modx.pro https://modx.pro
Комментарии: 5
getOption('base_path'); $corePath = $modx->getOption('core_path'); $id = $resource->get('id'); $tpl = $modx->getOption('pdfTpl', $scriptProperties, 'pdfTpl'); $css = $modx->getOption('cssTpl', $scriptProperties, 'cssTpl'); $createField = $modx->getOption('pdfTV', $scriptProperties, 'createPDF'); $processTVs = $modx->getOption('processTVs', $scriptProperties, null); $siteurl = $modx->getOption('site_url'); $params = array(); $assetsPath = $modx->getOption('assets_path'); $createPDF = $resource->getTVValue($createField); if($createPDF != '1') { @unlink($assetsPath.$id.'.pdf'); //remove file if it exists return false; //exit plugin } $params = $resource->toArray(); $tvs = $modx->getCollection('modTemplateVar'); foreach ($tvs as $tv) { $params[$tv->get('name')] = (empty($processTVs) ? $tv->getValue($id) : $tv->renderOutput($id)); if($tv->get('name') == 'pdfTpl' && $tv->getValue($id) != '' ) { $tpl = $tv->getValue($id); } } $html = $modx->getChunk($tpl, $params); $css = $modx->getChunk($css, $params); unset($params); require_once($corePath.'components/htmltopdf/mpdf.php'); $mpdf = new mPDF('utf-8', 'A4', '8', '', 10, 10, 7, 7, 10, 10); $mpdf->charset_in = 'utf-8'; $stylesheet = $css; $mpdf->WriteHTML($stylesheet, 1); $mpdf->list_indent_first_level = 0; $mpdf->WriteHTML($html, 2); $mpdf->Output($assetsPath.'pdf/'.$id.'.pdf', 'F');
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Create PDF on the fly with this flexible MODx snippet
License
sjstoelting/MODx-htmlToPDF
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
This repository will not be maintained anymore
I don’t work with MODX anymore.
This package contains source for an HTML to PDF converter for MODX Evolution, which is available at the MODX Website
Currently it is not planned to create a copy for MODX Revolution.
If you use Microsoft Windows in any version, please notice, that all files of this project have UNIX based line breaks.
The source is licensed under the GNU Lesser General Public License, version 2.1 as published at http://www.gnu.org/licenses/lgpl-2.1.html
This MODX snippet uses TCPDF, available at http://www.tcpdf.org/, to create the PDF Files from the content of a web document, published with MODX. TCPDF is part of the package. TCPDF itself is licensed under LGPL V3, as described at http://www.tcpdf.org/license.php. The current version of TCPDF used in this package is 5.9.145.
The main goal is to create highly configurable PDF documents. This is possible with parameters that one can use in the snippet tag and through the usage of chunks. All chunks make use of the placeholders as defined in other MODX snippets.
###Upload### For the installation you need to upload the TCPDF in the directory:
The snippet classes should be located at:
###Create the snippet htmlToPDF### Create a new snippet with the source of snippet.hmtlToPDF.php and call the snippet within your templates, probably at the top of the template. For the snippet call you can add several chunks as templates. Examples are in the assets/snippets/htmlToPDF/chunks/ directory.
###Create the plugin htmlToPDF### Create a new plugin with the source of plugin.htmlToPDF. On the page «System Events» choose these two options in the area «Documents»:
Here is an example for a call to htmlToPDF:
[!htmlToPDF? &author=``Stefanie Janine Stoelting`` &tvKeywords=``documentTags`` &headerLogo=``logo.png`` &chunkContentFooter=``pdf-contentfooter`` &chunkStandardHeader=``pdf-header-text`` &chunkStyle=``pdf-style`` !]
Place the snippet in the template of the document, where you want your readers to download the content as PDF. The advantage is, that you only have one call for all your documents.
If you have documents where that you do not want to publish as PDF and you only want to use one template, than try it with a template variable (TV) for this and PHX for the call and put your call to htmlToPDF into a snippet:
Where printPDF ist a possible name for the TV and snippetCAllhtmlToPDF is the name of the snippet.
###Link Generation### There is a chunk named pdf-link.txt that includes an example how to create a link to the current document. The example looks like the following:
The snippet default properties are only needed, if you want to set TCPDF, htmlToPDF, or the document output to other paths, as defined by default. If you need to change this information, go the «Properties» tab on the htmlToPDF snippet and add the following parameters to the field «Default Properties» and afterwards insert your paths: &basePath=The base path for TCPDF and htmlToPDF;string; &htmlToPdfPath=The path to the classes of htmlToPDF;string; &tcpdfPath=The path to TCPDF;string; &outputPdfPath=The path, where the PDF documents are stored. You need to give read, delete, and create rights to that folder (777).;string;
###Parameters### The following parameters are available:
Name | Description | Possible Values | Default |
---|---|---|---|
isPDF | Is added to the document URI, to identify PDF calls. | true | |
languageCode | The PDF document language code. | EN, DE. | EN |
setDateFormat | The date format string for all dates. | Y-m-d, d.m.Y | Y-m-d |
marginLeft | The left margin of the document. | number in mm | 10 |
marginRight | The right margin of the document. | number in mm | 10 |
marginTop | The top margin of the document. | number in mm | 30 |
marginBottom | The top margin of the document. | number in mm | 25 |
marginHeader | The header margin of the document. | number in mm | 5 |
marginFooter | The footer margin of the document. | number in mm | 10 |
headerFontType | The header font type for standard headers. | Font | helvetica |
headerFontSize | The font size for standard headers. | number | 16 |
headerFontBold | Whether the header font is bold, or not. | Number 0 or 1 | 1 |
headerLogo | The logo for standard headers, the logo has to be in the folder assets/lib/tcpdf/images/ to be found byTCPDF. | GIF, JPG, PNG | |
footerPositionFromBottom | The footer position from the bottom. | number in mm | 15 |
footerFontType | The footer font type for standard footers. | Font | helvetica |
footerFontItalic | Whether the header font is italic, or not for standard footers. | Number 0 or 1 | 1 |
footerFontSize | The font size for standard footers. | number | 8 |
contentFontType | The content font type for standard content. | Font | times |
contentFontSize | The font size for standard content. | number | 10 |
longTitleAboveContent | Whether the documents long title should be in the document above the content, or not, only for standard content. | Number 0 or 1 | 1 |
stripCSSFromContent | Strip in-line CSS, or not, only for standard content. | Number 0 or 1 | 1 |
rewritePDF | If a PDF document exists, the document is not rewritten every time, when the PDF document is requested. This is a cache function for PDF documents. | Number 0 or 1 | 1 |
author | Author for PDF document properties. | string | |
tvKeywords | A template variable for keywords for the PDF document properties. Keywords are comma separated, you may reuse keywords for tag clouds. | Template Variable | |
chunkHeader | Chunk for customized headers | Chunk | |
chunkContentFooter | Chunk for customized text placed under the content. For example for a link to the current document on the website inside the PDF document. Only used with standard content. | Chunk | |
chunkStyle | A chunk for CSS styles in the PDF document. | Chunk | |
chunkContent | A chunk for individual arrangement of the content in the document. | Chunk | |
fontMonoSpaced | The Monospaced font. | Font | courier |
imageScaleRatio | The scale ratio for images. | number | 1.25 |
footerChunk | The footer chunk name. | Chunk | Page %1s / %2s |
basePath | The base path for TCPDF and htmlToPDF. | string | MODX_BASE_PATH |
htmlToPdfPath | The path to the classes of htmlToPDF. | string | assets/snippets/htmlToPDF/| |
tcpdfPath | The path to TCPDF. | string | assets/lib/tcpdf/ |
outputPdfPath | The path, where the PDF documents are stored. You need to give read, delete, and create rights to that folder (777). | string | assets/pdf/ |
headerImageHeight | Sets the height for a logo in the header of the PDF document in mm. | int | 20 |
printHeader | Whether to print a header, or not. | Number 0 or 1 | 1 |
printFooter | Whether to print a footer, or not. | Number 0 or 1 | 1 |
lineColor | String with 3 comma separated values as RGB. | string | 0,0,0 |
About
Create PDF on the fly with this flexible MODx snippet
printPdf
Дополнительные поля в ресурсе и профиле пользователя.
Как создать pdf файл:
- container — контейнер, который нужно распечатать. По умолчанию: ‘body’
- mode — режим печати: default или page. По умолчанию: default
$(document).on('click', '#printPdf', function(e){ e.preventDefault(); printPdf('.printPdf'); });
- default — Обычная печать, но существует ограничение по кол-ву страниц ~ 6.
- page — Постраничная печать. Разделяет каждый контейнер на отдельную страницу. Ограничений нет, но не умеет сохранять ссылки — аналогично обычному скриншоту.
Css классы:
- print-break — используется для разрыва страницы. Работает только в режиме: ‘default’
- print-hide — для скрытия элементов при печати.
Js cобытия:
startPrint
$(document).on('startPrint', function(e){ let config = e.detail.config; config.print.filename = 'newFileName'; });
createPdf
$(document).on('createPdf', function(e){ let pdf = e.detail.pdf; let totalPages = pdf.internal.getNumberOfPages(); let logo = '/assets/img/printPdf/modstore.png'; for (i = 1; i
endPrint
$(document).on('endPrint', function(e){ let pdf = e.detail.pdf; let content = 'Вы можете открыть файл по ссылке'; swal('prindPdf', content, 'info'); });
Еще примеры:
Открываем pdf в новом окне:
$(document).on('createPdf', function(e){ let pdf = e.detail.pdf; // Здесь можно изменить содержимое pdf // Открываем в номом окне pdf.output("pdfobjectnewwindow"); });
Дерево настроек:
- config
- print
- margin — Отступы в PDF файле. По умолчанию: [0,0,0,0]
- filename — Имя файла для экспортированного PDF
- image
- type — Тип изображения. Возможные значения: «png», «jpeg» и «webp» (в Chrome). По умолчанию: «jpeg»
- quality — Качество изображения от 0 до 1
- scale — Масштаб. Влияет на качество pdf файла. По умолчанию: 2
- useCORS — Загрузить изображения с сервера с помощью CORS. По умолчанию: false
- unit — Единица измерения, которая будет использоваться при указании координат. По умолчанию: «in»
- format — Формат страницы. По умолчанию: auto
- orientation — Ориентация страницы. По умолчанию: auto
- compress — Сжать сгенерированный PDF. По умолчанию: true
1.1.1-pl (15.12.21)
1.1.0-pl (23.03.20)
- Все параметры перенесены в системные настройки.
- Переписаны скрипты и стили
- Обновлены библиотеки
- Добавлены события
1.0.1-pl
1.0.0-pl
- print