tcpdf edit footer - edit

How do I edit a footer using tcpdf? I want to add current date & time at the footer. Please help.

Override the class like this :
class MYPDF extends TCPDF {
public function Footer() {
$image_file = "img/bg_bottom_releve.jpg";
$this->Image($image_file, 11, 241, 189, '', 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
$this->SetY(-15);
$this->SetFont('helvetica', 'N', 6);
$this->Cell(0, 5, date("m/d/Y H\hi:s"), 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
}
then instead of calling :
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
do :
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

You have to extend the TCPDF class and override the Footer() method as explained on the default example n. 3. Check the official http://www.tcpdf.org website and forums for further information.

How can I create 2 footer lines, please?
class MYPDF extends TCPDF {
private $customFooterText = "";
/**
* #param string $customFooterText
*/
public function setCustomFooterText($customFooterText)
{
$this->customFooterText = $customFooterText;
}
public function Footer()
{
$this->SetY(-15);
// Set font
$this->SetFont('helvetica', 'I', 8);
// Page number
$this->Cell(0, 10, $this->customFooterText, 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
}
Usage
$pdf = new MYPDF();
$pdf->setCustomFooterText('THIS IS CUSTOM FOOTER');

If you want dynamically change footer text extends TCPDF like this
class MYPDF extends TCPDF {
private $customFooterText = "";
/**
* #param string $customFooterText
*/
public function setCustomFooterText($customFooterText)
{
$this->customFooterText = $customFooterText;
}
public function Footer()
{
$this->SetY(-15);
// Set font
$this->SetFont('helvetica', 'I', 8);
// Page number
$this->Cell(0, 10, $this->customFooterText, 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
}
usage:
$pdf = new MYPDF();
$pdf->setCustomFooterText('THIS IS CUSTOM FOOTER');
// .... etc

If you want put an different content on more than one page:
define("bottom_info", "|FIRST PAGE|SECOND PAGE|THIRD PAGE|...", true);
the info will be separated by " | " (with explode function)
class:
class MYPDF extends TCPDF {
public function Header() {
}
// Page footer
public function Footer() {
$this->SetY(-15);
$this->SetFont('helvetica', '', 7);
// Page number
$titulos = explode("|",bottom_info);
$this->Cell(0, 10, $titulos[$this->page].' - Pagina '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
}

After the EOD use the below code to overwrite the footer method.
EOD;
$txt = date("m/d/Y h:m:s");
// print a block of text using Write()
$pdf->Write($h=0, $txt, $link='', $fill=0, $align='C', $ln=true, $stretch=0, $firstline=false, $firstblock=false, $maxh=0);

I figured it out and here's the solution for others that might come across this thread.
Edit the file "tcpdf.php".
Search for "public function Footer()"
Add timestamp here:
$timestamp = date("m/d/Y h:m:s");
if (empty($this->pagegroups)) {
$pagenumtxt = ' Created on ' .$timestamp.' '.$this->l['w_page'].' '.$this->getAliasNumPage().' / '.$this->getAliasNbPages();
} else {
$pagenumtxt = ' Created on ' .$timestamp.' '. $this->l['w_page'].' '.$this->getPageNumGroupAlias().' / '.$this->getPageGroupAlias();
}

Related

Multiple renderer in esri map

I have requirement which is using classbreakrenderer for showing clusters size as it breaks down, now i want to use one renderer which shows different different symbol for single cluster based on some attribute value.
I have tried to use UniqueValueRenderer but it not working.
Any suggestion
I have requirement which is using classbreakrenderer for showing clusters size as it breaks down, now i want to use one renderer which shows different different symbol for single cluster based on some attribute value.
I have tried to use UniqueValueRenderer but it not working.
I have requirement which is using classbreakrenderer for showing clusters size as it breaks down, now i want to use one renderer which shows different different symbol for single cluster based on some attribute value.
I have tried to use UniqueValueRenderer but it not working.
<script type="text/javascript">
window.dojoConfig = {
async: true,
packages: [
{
name: 'app',
location: window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + '/src'
}
]};
</script>
<!-- ArcGIS API for JavaScript library references -->
<script src="https://js.arcgis.com/3.15compact"></script>
<script>
require(["esri/map",
"esri/dijit/Geocoder",
"esri/dijit/HomeButton",
"esri/renderers/SimpleRenderer",
"esri/symbols/PictureMarkerSymbol",
"esri/layers/FeatureLayer",
"esri/InfoTemplate",
"esri/graphic",
"esri/graphicsUtils",
"app/clusterfeaturelayer",
"esri/symbols/SimpleMarkerSymbol",
"esri/symbols/SimpleLineSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/PictureMarkerSymbol",
"esri/renderers/ClassBreaksRenderer",
"esri/renderers/HeatmapRenderer",
"esri/renderers/UniqueValueRenderer",
"dojo/_base/Color",
"dojo/on",
"dojo/dom-style",
"dojo/_base/fx",
"dojo/fx/easing",
"dojo/dom",
"dojo/domReady!"],
function (Map, Geocoder, HomeButton, SimpleRenderer, PictureMarkerSymbol, FeatureLayer, UniqueValueRenderer, InfoTemplate, Graphic, graphicsUtils, ClusterFeatureLayer, SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, PictureMarkerSymbol, ClassBreaksRenderer, HeatmapRenderer, Color, on, domStyle, fx, easing, dom) {
// Locals
var map,
popup,
clusterLayer,
geocoder,
infoTemplate,
defaultSym,
selectedSym,
activeClusterElement;
// Create map
map = new Map("mapDiv", {
basemap: "dark-gray",
center: [-120, 50],
zoom: 3
});
// Create widget
geocoder = new Geocoder({
value: "California, United States",
autoNavigate: true,
maxLocations: 25,
autoComplete: true,
arcgisGeocoder: {
outFields: "Place_addr, PlaceName, Score"
},
map: map
}, "search");
geocoder.startup();
var home = new HomeButton({
map: map
}, "homeButton");
home.startup();
// Add raw points
// var featureLayer = new FeatureLayer("http://services.arcgis.com/oKgs2tbjK6zwTdvi/arcgis/rest/services/Major_World_Cities/FeatureServer/0", {
// infoTemplate: infoTemplate,
// outFields: ["*"]
// });
// map.addLayer(featureLayer);
// Add heatmap
// var featureLayer2 = new FeatureLayer("http://services.arcgis.com/oKgs2tbjK6zwTdvi/arcgis/rest/services/Major_World_Cities/FeatureServer/0");
// var heatmapRenderer = new HeatmapRenderer();
// featureLayer2.setRenderer(heatmapRenderer);
// map.addLayer(featureLayer2);
// Add clusters
map.on("load", function () {
// Add layer
addClusterLayer();
addClusterLayerEvents();
});
// Set popup
popup = map.infoWindow;
popup.highlight = false;
popup.titleInBody = false;
popup.domNode.className += " light";
//popup.domNode.style.marginTop = "-17px"; // for pins only
// Popup content
//infoTemplate = new InfoTemplate("Seismic Activity > 4.0", "<p>Location: ${NAME}</p><p>Magnitude: ${OTHER_MAG1}</p><p>Date: ${YEAR}/${MONTH}/${DAY}</p>");
infoTemplate = new InfoTemplate("<b>${CITY_NAME}</b>", "<p>COUNTRY: ${CNTRY_NAME}</p><p>STATE/PROVINCE: ${ADMIN_NAME}</p><p>POPULATION: ${POP}</p>");
// Option 1: Esri marker for single locations and selections
// defaultSym = new createPictureSymbol("./images/blue-cluster-pin.png", 0, 8, 9, 16);
// selectedSym = new createPictureSymbol("./images/blue-cluster-pin.png", 0, 9, 11, 20);
// Option 2: Use circle markers for symbols - Red
defaultSym = new SimpleMarkerSymbol("circle", 16,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([102,0,0, 0.55]), 3),
new Color([255, 255, 255, 1]));
selectedSym = new SimpleMarkerSymbol("circle", 16,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([102,0,0, 0.85]), 3),
new Color([255, 255, 255, 1]));
// Create a feature layer to get feature service
function addClusterLayer() {
var renderer,
renderer1,
small,
medium,
large,
xlarge;
// Add cluster renderer
clusterLayer = new ClusterFeatureLayer({
"url": "http://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/World_Cities/FeatureServer/0",
//"url": "http://services.arcgis.com/BG6nSlhZSAWtExvp/arcgis/rest/services/GlobalSeismographyNetwork/FeatureServer/0",
// "url": "http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Earthquakes/Since_1970/MapServer/0",
"distance": 95,
"id": "clusters",
"labelColor": "#fff",
"resolution": map.extent.getWidth() / map.width,
//"singleColor": "#888",
"singleSymbol": defaultSym,
"singleTemplate": infoTemplate,
"useDefaultSymbol": false,
"zoomOnClick": false,
"showSingles": true,
"objectIdField": "FID",
outFields: ["*"]
});
renderer = new ClassBreaksRenderer(defaultSym, "clusterCount");
// Red Clusters
small = new SimpleMarkerSymbol("circle", 25,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([212,116,60,0.5]), 15),
new Color([212,116,60,0.75]));
medium = new SimpleMarkerSymbol("circle", 50,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([178,70,37,0.5]), 15),
new Color([178,70,37,0.75]));
large = new SimpleMarkerSymbol("circle", 80,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([144,24,13,0.5]), 15),
new Color([144,24,13,0.75]));
xlarge = new SimpleMarkerSymbol("circle", 110,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([102,0,0,0.5]), 15),
new Color([102,0,0,0.75]));
// Break values - can adjust easily
renderer.addBreak(2, 50, small);
renderer.addBreak(50, 250, medium);
renderer.addBreak(250, 1000, large);
renderer.addBreak(1000, 50000, xlarge);
// Providing a ClassBreakRenderer is also optional
clusterLayer.setRenderer(renderer);
//added second renderer
var renderer1 = new UniqueValueRenderer(defaultSymbol, "CNTRY_NAME");
//add symbol for each possible value
renderer1.addValue("United States", new PictureMarkerSymbol({
"angle": 0,
"xoffset": 0,
"yoffset": 8,
"type": "esriPMS",
"url": "./images/blue-pin.png",
"contentType": "image/png",
"width": 24,
"height": 24
}));
renderer1.addValue("Argentina", new PictureMarkerSymbol({
"angle": 0,
"xoffset": 0,
"yoffset": 12,
"type": "esriPMS",
"url": "./images/blue-cluster-pin.png",
"contentType": "image/png",
"width": 24,
"height": 24
}));
//added to cluster
clusterLayer.setRenderer(renderer1);
map.addLayer(clusterLayer);
}
// Create png marker
// function createPictureSymbol(url, xOffset, yOffset, xWidth, yHeight) {
// return new PictureMarkerSymbol(
// {
// "angle": 0,
// "xoffset": xOffset,
// "yoffset": yOffset,
// "type": "esriPMS",
// "url": url,
// "contentType": "image/png",
// "width": xWidth,
// "height": yHeight
// }
// );
// }
// Create new graphic and add to map.graphics
function addSelectedFeature() {
var selIndex = map.infoWindow.selectedIndex,
selFeature;
if (selIndex !== -1) {
selFeature = map.infoWindow.features[selIndex];
// Remove old feature first
removeSelectedFeature();
// Add new graphic
map.infoWindow._lastSelected = new Graphic(selFeature.toJson());
map.infoWindow._lastSelected.setSymbol(selectedSym);
map.graphics.add(map.infoWindow._lastSelected);
}
}
// Remove graphic from map.graphics
function removeSelectedFeature() {
if (map.infoWindow._lastSelected) {
map.graphics.remove(map.infoWindow._lastSelected);
map.infoWindow._lastSelected = null;
}
}
// Highlight clusters
function setActiveClusterOpacity(elem, fillOpacity, strokeOpacity) {
var textElm;
if (elem) {
elem.setAttribute("fill-opacity", fillOpacity);
elem.setAttribute("stroke-opacity", strokeOpacity);
// Overide inherited properties for the text in the circle
textElm = elem.nextElementSibling;
if (textElm && textElm.nodeName === "text") {
textElm.setAttribute("fill-opacity", 1);
}
}
}
// Hide popup if selected feature is clustered
function onClustersShown(clusters) {
var i = 0,
extent;
if (map.infoWindow.isShowing && map.infoWindow._lastSelected) {
for (i; i < clusters.length; i++) {
if (clusters[i].attributes.clusterCount > 1) {
extent = clusterLayer._getClusterExtent(clusters[i]);
if (extent.contains(map.infoWindow._lastSelected.geometry)) {
map.infoWindow.hide();
break;
}
}
}
}
}
// Wire cluster layer events
function addClusterLayerEvents() {
// Mouse over events
clusterLayer.on("mouse-over", onMouseOverCluster);
clusterLayer.on("mouse-out", onMouseOutCluster);
// Clusters drawn
clusterLayer.on("clusters-shown", onClustersShown);
}
// Save the last selected graphic so we can highlight it
map.infoWindow.on("selection-change", function () {
addSelectedFeature();
animateInfoWindow();
});
// Clear selected graphic when infoWindow is hidden
map.infoWindow.on("hide", function () {
// re-activate cluster
setActiveClusterOpacity(activeClusterElement, 0.75, 0.5);
removeSelectedFeature();
});
// Popup enhancements
function onMouseOverCluster(e) {
if (e.graphic.attributes.clusterCount === 1) {
e.graphic._graphicsLayer.onClick(e);
} else {
if (e.target.nodeName === "circle") {
activeClusterElement = e.target;
setActiveClusterOpacity(activeClusterElement, 1, 1);
} else {
setActiveClusterOpacity(activeClusterElement, 1, 1);
}
}
}
function onMouseOutCluster(e) {
if (e.graphic.attributes.clusterCount > 1) {
if (e.target.nodeName === "circle" || e.target.nodeName === "text") {
setActiveClusterOpacity(activeClusterElement, 0.75, 0.5);
setActiveClusterOpacity(e.target, 0.75, 0.5);
}
}
}
function animateInfoWindow() {
domStyle.set(map.infoWindow.domNode, "opacity", 0);
fx.fadeIn({node: map.infoWindow.domNode,
duration: 150,
easing: easing.quadIn}).play();
}
// Click to close
map.on('click', function () {
if (map.infoWindow.isShowing) {
map.infoWindow.hide();
}
});
// ESC is pressed
map.on('key-down', function (e) {
if (e.keyCode === 27) {
map.infoWindow.hide();
}
});
// Dynamically reposition popups when map moves
map.on('extent-change', function () {
if (map.infoWindow.isShowing) {
map.infoWindow.reposition();
}
});
// Auto recenter map - optional
autoRecenter(map);
function autoRecenter(map) {
on(map, 'load', function (map) {
on(window, 'resize', map, map.resize);
});
on(map, 'resize', function(extent, width, height) {
map.__resizeCenter = map.extent.getCenter();
setTimeout(function() {
map.centerAt(map.__resizeCenter);
}, 100);
});
}
});
</script>
</head>
<body>
<div id="mapDiv"></div>
<div id="search"></div>
<div id="homeButton"></div>
</body>
</html>

override searchProvider.php does not work

Create : override/modules/ps_facetedsearch/src/Product/SearchProvider.php
Create : override/modules/ps_facetedsearch/ps_facetedsearch.php
Delete the cache manually
Version : 1.7.6.4
override SearchProvider.php doesn't work
override ps_facetedsearch.php work
I need to delete 2 types of sorting ... into SearchProvider.php:getAvailableSortOrders() but I never go through the overloaded function
if (!defined('PS_VERSION'))
exit;
class SearchProviderOverride extends SearchProvider
{
/**
* #return array
*/
public function getAvailableSortOrders()
{
$sortPosAsc = new SortOrder('product', 'position', 'asc');
$sortPriceAsc = new SortOrder('product', 'price', 'asc');
$sortPriceDesc = new SortOrder('product', 'price', 'desc');
$translator = $this->module->getTranslator();
die('hello not world!');
return [
$sortPosAsc->setLabel(
$translator->trans('Relevance', [], 'Modules.Facetedsearch.Shop')
),
$sortPriceAsc->setLabel(
$translator->trans('Price, low to high', [], 'Shop.Theme.Catalog')
),
$sortPriceDesc->setLabel(
$translator->trans('Price, high to low', [], 'Shop.Theme.Catalog')
),
];
}
}```
"getAvailableSortOrders" is a private method. You are probably only hidding the private method with your public one.
You should override the "runQuery" method since it's the only one that uses "getAvailableSortOrders". This way your overriden "runQuery" will call the appropriate "getAvailableSortOrders" method.
And finally, you can make your "getAvailableSortOrders" private since its only meant to be used in this class.
if (!defined('PS_VERSION'))
exit;
class SearchProviderOverride extends SearchProvider
{
/**
* #return array
*/
private function getAvailableSortOrders()
{
$sortPosAsc = new SortOrder('product', 'position', 'asc');
$sortPriceAsc = new SortOrder('product', 'price', 'asc');
$sortPriceDesc = new SortOrder('product', 'price', 'desc');
$translator = $this->module->getTranslator();
die('hello not world!');
return [
$sortPosAsc->setLabel(
$translator->trans('Relevance', [], 'Modules.Facetedsearch.Shop')
),
$sortPriceAsc->setLabel(
$translator->trans('Price, low to high', [], 'Shop.Theme.Catalog')
),
$sortPriceDesc->setLabel(
$translator->trans('Price, high to low', [], 'Shop.Theme.Catalog')
),
];
}
/**
* #param ProductSearchContext $context
* #param ProductSearchQuery $query
*
* #return ProductSearchResult
*/
public function runQuery(
ProductSearchContext $context,
ProductSearchQuery $query
) {
$result = new ProductSearchResult();
// extract the filter array from the Search query
$facetedSearchFilters = $this->filtersConverter->createFacetedSearchFiltersFromQuery($query);
$context = $this->module->getContext();
$facetedSearch = new Search($context);
// init the search with the initial population associated with the current filters
$facetedSearch->initSearch($facetedSearchFilters);
$orderBy = $query->getSortOrder()->toLegacyOrderBy(false);
$orderWay = $query->getSortOrder()->toLegacyOrderWay();
$filterProductSearch = new Filters\Products($facetedSearch);
// get the product associated with the current filter
$productsAndCount = $filterProductSearch->getProductByFilters(
$query->getResultsPerPage(),
$query->getPage(),
$orderBy,
$orderWay,
$facetedSearchFilters
);
$result
->setProducts($productsAndCount['products'])
->setTotalProductsCount($productsAndCount['count'])
->setAvailableSortOrders($this->getAvailableSortOrders());
// now get the filter blocks associated with the current search
$filterBlockSearch = new Filters\Block(
$facetedSearch->getSearchAdapter(),
$context,
$this->module->getDatabase()
);
$idShop = (int) $context->shop->id;
$idLang = (int) $context->language->id;
$idCurrency = (int) $context->currency->id;
$idCountry = (int) $context->country->id;
$idCategory = (int) $query->getIdCategory();
$filterHash = md5(
sprintf(
'%d-%d-%d-%d-%d-%s',
$idShop,
$idCurrency,
$idLang,
$idCategory,
$idCountry,
serialize($facetedSearchFilters)
)
);
$filterBlock = $filterBlockSearch->getFromCache($filterHash);
if (empty($filterBlock)) {
$filterBlock = $filterBlockSearch->getFilterBlock($productsAndCount['count'], $facetedSearchFilters);
$filterBlockSearch->insertIntoCache($filterHash, $filterBlock);
}
$facets = $this->filtersConverter->getFacetsFromFilterBlocks(
$filterBlock['filters']
);
$this->labelRangeFilters($facets);
$this->addEncodedFacetsToFilters($facets);
$this->hideUselessFacets($facets, (int) $result->getTotalProductsCount());
$facetCollection = new FacetCollection();
$nextMenu = $facetCollection->setFacets($facets);
$result->setFacetCollection($nextMenu);
$result->setEncodedFacets($this->facetsSerializer->serialize($facets));
return $result;
}
}

How to change the size of the pdf in prestashop using TPDF

I want the size of the paper to be increased to A3 OR OR C4 (width to be increased)
I tried below but no change is there anyway to change the size of the pdf generated?
public function generatePDF($object, $template)
{
switch($template) {
case PDF::TEMPLATE_ETICKET:
$format = 'C3'; // Replace with your desired size
break;
default:
$format = 'A4'; // Replace with normal size
}
$pdf = new PDF($object, $template, Context::getContext()->smarty,'P', $format);
//d($pdf);
$pdf->render();
}
Create a file PDFGenerator.php in override/classes/pdf.
in to PDFGenerator.php insert:
<?php
class PDFGenerator extends PDFGeneratorCore
{
public function __construct($use_cache = false, $orientation = 'P')
{
parent::__construct($orientation, 'mm', 'A3', true, 'UTF-8', $use_cache, false); /*Replace A3 with the size you prefer */
$this->setRTL(Context::getContext()->language->is_rtl);
}
}
delete cache/class_index.php

DataTables image (or at least image title) export to PDF

Using DataTables and Buttons (NOT TableTools, which is retired) extension. Some cells have progressbars and small icons. Is there a way to export these images (or at least their titles) to PDF? Found some possible hacks on this page, but all of them were for retired TableTools.
Checked https://datatables.net/reference/button/pdf and https://datatables.net/reference/api/buttons.exportData%28%29 but couldn't find any method to achieve this goal. Tested by adding this code:
stripHtml: false
but whole HTML code (like img src=...) was included in PDF file instead of images.
If exporting images isn't possible, is there a way to export at least alt or title attribute of each image? That would be enough.
I assume you are using pdfHtml5. dataTables is using pdfmake in order to export pdf files. When pdfmake is used from within a browser it needs images to be defined as base64 encoded dataurls.
Example : You have rendered a <img src="myglyph.png"> in the first column of some of the rows - those glyphs should be included in the PDF. First create an Image reference to the glyph :
var myGlyph = new Image();
myGlyph.src = 'myglyph.png';
In your customize function you must now
1) build a dictionary with all images that should be included in the PDF
2) replace text nodes with image nodes to reference images
buttons : [
{
extend : 'pdfHtml5',
customize: function(doc) {
//ensure doc.images exists
doc.images = doc.images || {};
//build dictionary
doc.images['myGlyph'] = getBase64Image(myGlyph);
//..add more images[xyz]=anotherDataUrl here
//when the content is <img src="myglyph.png">
//remove the text node and insert an image node
for (var i=1;i<doc.content[1].table.body.length;i++) {
if (doc.content[1].table.body[i][0].text == '<img src="myglyph.png">') {
delete doc.content[1].table.body[i][0].text;
doc.content[1].table.body[i][0].image = 'myGlyph';
}
}
},
exportOptions : {
stripHtml: false
}
}
Here is a an example of a getBase64Image function
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return canvas.toDataURL("image/png");
}
If you just want to show the title of images in the PDF - or in any other way want to manipulate the text content of the PDF - then it is a little bit easier. The content of each column in each row can be formatted through the exportOptions.format.body callback :
buttons : [
{
extend : 'pdfHtml5',
exportOptions : {
stripHtml: false
format: {
body: function(data, col, row) {
var isImg = ~data.toLowerCase().indexOf('img') ? $(data).is('img') : false;
if (isImg) {
return $(data).attr('title');
}
return data;
}
}
}
]
The reason format.body cannot be used along with images is that is only let us pass data back to the text node part of the PDF document.
See also
http://pdfmake.org/#/gettingstarted (look for Images section)
https://github.com/bpampuch/pdfmake/blob/master/examples/images.js
Since no suggestions received, I had to make a hack in order to get PDF file formatted the way I want.
In case someone has the same issue, you can use hidden span to display image alt/title near image itself. I'm sure it's not the best practice, but it will do the trick. So the code will look like:
<img src='image.png' alt='some_title'/><span class='hidden'>some_title</span>
This way datatables will show only the image, while PDF file will contain text you need.
This is my CODE!
HTML
<div class="dt-btn"></div>
<table>
<thead><tr><th>No</th><th>IMAGE</th><th>NOTE</th></tr></thead>
<tbody>
<tr>
<td>{{$NO}}</td>
<td>{{$imgSRC}}</td>
<td>{{$NAME}}<br />
{{$GRADE}}<br />
{{$PROFILE}}<br />
{{$CODE}}<br />
</td>
</tr>
</tbody>
</table>
JAVASCRIPT
$.extend( true, $.fn.dataTable.defaults, {
buttons: [{
text: '<i class="bx bx-download font-medium-1"></i><span class="align-middle ml-25">Download PDF</span>',
className: 'btn btn-light-secondary mb-1 mx-1 dnPDF',
extend: 'pdfHtml5',
pageSize: 'A4',
styles: {
fullWidth: { fontSize: 11, bold: true, alignment: 'left', margin: [0,0,0,0] }
},
action: function ( e, dt, node, config ) {
var that = this;
setTimeout( function () {
$.fn.dataTable.ext.buttons.pdfHtml5.action.call(that, e, dt, node, config);
$( ".donePDF" ).remove();
$( ".dnPDF" ).prop("disabled", false);
}, 50);
},
customize: function(doc) {
doc.defaultStyle.fontSize = 11;
doc.defaultStyle.alignment = 'left';
doc.content[1].table.dontBreakRows = true;
if (doc) {
for (var i = 1; i < doc.content[1].table.body.length; i++) {
// 1st Column - display IMAGE
var imgtext = doc.content[1].table.body[i][0].text;
delete doc.content[1].table.body[i][0].text;
jQuery.ajax({
type: "GET",
dataType: "json",
url: "{{route('base64')}}",
data: { src: imgtext },
async: false,
success: function(resp) {
//console.log(resp.data);
doc.content[1].table.body[i][0] = {
margin: [0, 0, 0, 3],
alignment: 'center',
image: resp.data,
width: 80,
height: 136
};
}
});
// 2nd Column - display NOTE(4 line)
var bodyhtml = doc.content[1].table.body[i][1].text;
var bodytext = bodyhtml.split("\n");
var bodystyle = []
for (var j = 0; j < bodytext.length; j++) {
switch(j) {
case 0:
// NAME
var _text = { margin:[0, 0, 0, 3], color:"#000000", fillColor:'#ffffff', bold:true, fontSize:13, alignment:'center', text:bodytext[j] };
break;
case 1:
// GRADE
var _text = { margin:[0, 0, 0, 3], color:"blue", fillColor:'#ffffff', bold:false, fontSize:11, alignment:'left', text:bodytext[j] };
break;
case 3:
// CODE
var _text = { margin:[0, 0, 0, 3], color:"#000000", fillColor:'#ffffff', bold:true, fontSize:11, alignment:'left', text:bodytext[j] };
break;
default:
// OTHERS
var _text = { margin:[0, 0, 0, 3], color:"#000000", fillColor:'#ffffff', bold:false, fontSize:11, alignment:'left', text:bodytext[j] };
break;
}
bodystyle[j] = _text;
};
doc.content[1].table.body[i][1] = bodystyle;
}
}
},
exportOptions: {
columns: [ 1, 2 ],
stripNewlines: false,
stripHtml: true,
modifier: {
page: 'all' // 'all', 'current'
},
}
}],
columns: [
{ className: 'iNo', orderable: true, visible: true},
{ className: 'iIMG', orderable: false, visible: false },
{ className: 'iPDF', orderable: false, visible: false, responsivePriority: 10001 } ]
});
var table = $('#table').DataTable();
table.buttons().container().appendTo('.dt-btn');
$('.dnPDF').on('click', function(){
$(this).append('<span class="spinner-border spinner-border-sm donePDF" role="status" aria-hidden="true"></span>').closest('button').attr('disabled','disabled');
});
$.fn.dataTable.Buttons.defaults.dom.container.className = '';
$.fn.dataTable.Buttons.defaults.dom.button.className = 'btn';
PHP
public function base64(Request $request)
{
$request->validate([
'src' => 'required|string'
]);
$fTYPE = pathinfo($request->src, PATHINFO_EXTENSION);
$fDATA = #file_get_contents($request->src);
$imgDATA = base64_encode($fDATA);
$imgSRC = 'data:image/' . $fTYPE . ';base64,'.$imgDATA;
$error = ($imgDATA!='') ? 0 : 1;
$msg = ($error) ? 'Error' : 'Success';
return response()->json([ 'msg' => $msg, 'error'=> $error, 'data' => $imgSRC]);
}
[Sample][1]: https://i.stack.imgur.com/35Wlm.jpg
In addition to davidkonrad's answer. I created dynamically all base64 images and used them in Datatables pdfmake like this:
for (var i = 1; i < doc.content[2].table.body.length; i++) {
if (doc.content[2].table.body[i][1].text.indexOf('<img src=') !== -1) {
html = doc.content[2].table.body[i][1].text;
var regex = /<img.*?src=['"](.*?)['"]/;
var src = regex.exec(html)[1];
var tempImage = new Image();
tempImage.src = src;
doc.images[src] = getBase64Image(tempImage)
delete doc.content[2].table.body[i][1].text;
doc.content[2].table.body[i][1].image = src;
doc.content[2].table.body[i][1].fit = [50, 50];
}
//here i am removing the html links so that i can use stripHtml: true,
if (doc.content[2].table.body[i][2].text.indexOf('<a href="details.php?') !== -1) {
html = $.parseHTML(doc.content[2].table.body[i][2].text);
delete doc.content[2].table.body[i][1].text;
doc.content[2].table.body[i][2].text = html[0].innerHTML;
}
}

Any way to select a line of text in browser screen by webdriver to emulate keyboard or mouse?

I want to use WebDriver to select a line of text in browser screen(actually in CKEditor editing area) then change its text style from CKEditor toolbar. Any method can do that?
For example, a line with html code like below:
this is a sample line.
I try to use Actions to build a mouse action chain but no success due to not familiar with that. Thanks for any hints or answer.
I'm not sure this is actually possible with WebDriver. What you would want to do is to clickAndHold(...).moveByOffset(...).release(...). Unforunately, WebDriver only allows a WebElement as a parameter to clickAndHold().
My best advice to you is to emulate JavaScript events for this. You can then do something like this in your test:
((JavascriptExecutor) driver).executeScript(...);
I wrote code for emulating mouse events which I use with some of my Selenium tests. Although it doesn't do exactly what you want, hopefully it will be useful (hopefully you can just set the x/y coords and perhaps that will get it working):
var f = function() {
var id = "ext-gen1116";
var top = document.querySelector( '#ext-gen1116:nthchild(0)' );
var bot = document.getElementById( id ).childNodes[3];
var getX = function( obj ) {
if( obj == null ) {
return 0;
} else {
return obj.offsetLeft + getX( obj.offsetParent );
}
}
var getY = function( obj ) {
if( obj == null ) {
return 0;
} else {
return obj.offsetTop + getY( obj.offsetParent );
}
}
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mousedown", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
bot.dispatchEvent(evt);
evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mousemove", true, true, window,
0, 0, 0, getX( top ) - getX( bot ), getY( top ) - getY( bot ),
false, false, false, false, 0, null);
bot.dispatchEvent(evt);
var mouseup = function( elem ) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mouseup", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent(evt);
}
setTimeout( mouseup, 500, bot );
};
f();
If it's possible for you to do what you want with the keyboard instead, this is by far the better solution. You can simply do driver.sendKeys(...). The Keys enum will be priceless for you in this case :-)
You can also try to do it with JavaScript:
let el = document.querySelectorAll("p")[0];
let range = document.createRange();
range.selectNodeContents(el);
window.getSelection().addRange(range);