Skip to content

Instantly share code, notes, and snippets.

@rafaehlers
Last active April 17, 2024 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaehlers/3e5f5745c18bf0804a1b123bdeee920d to your computer and use it in GitHub Desktop.
Save rafaehlers/3e5f5745c18bf0804a1b123bdeee920d to your computer and use it in GitHub Desktop.
DataTables > Buttons > PDF > Include images on export
document.addEventListener('DOMContentLoaded', function() {
wp.hooks.addFilter( 'gk.datatables.options', 'dt-custom-code', function ( options ) {
options.buttons = options.buttons.map( button => {
if ( button.extend !== 'pdf' ) {
return button;
}
button.action = function ( e, dt, button, config ) {
const promises = [];
dt.rows( { search: 'applied' } ).every( function () {
jQuery( this.node() ).find( 'img' ).each( function () {
const imageElement = this;
const promise = fetch( imageElement.src )
.then( response => response.blob() )
.then( blob => new Promise( resolve => {
const reader = new FileReader();
reader.onload = () => {
imageElement.src = reader.result;
resolve();
};
reader.onerror = error => {
resolve();
};
reader.readAsDataURL( blob );
} ) );
promises.push( promise );
} );
} );
Promise.all( promises ).then( () => jQuery.fn.dataTable.ext.buttons.pdfHtml5.action.call( this, e, dt, button, config ) );
};
const originalBodyFunction = button.exportOptions?.format?.body;
button.exportOptions = button.exportOptions || {};
button.exportOptions.format = button.exportOptions.format || {};
button.exportOptions.format.body = function ( data, row, column, node ) {
const images = jQuery( node ).find( 'img' );
if ( images.length > 0 ) {
const imageLinks = [];
images.each( function () {
const src = jQuery( this ).attr( 'src' );
if ( src ) {
imageLinks.push( '__LINK__' + src );
}
} );
return imageLinks.join( '||' );
}
return originalBodyFunction ? originalBodyFunction( data, row, column, node ) : data;
};
button.customize = function ( doc ) {
doc.content.forEach( item => {
if ( !item.table ) {
return;
}
item.table.body.forEach( row => {
row.forEach( cell => {
if ( typeof cell.text !== 'string' || !cell.text.includes( '__LINK__' ) ) {
return;
}
const imageLinks = cell.text.split( '||' );
cell.text = undefined;
cell.stack = [];
imageLinks.forEach( link => {
const imgData = link.match( /__LINK__(data:image\/[^;]+;base64,[^\"]+)/ );
if ( imgData && imgData[ 1 ] ) {
cell.stack.push( {
image: imgData[ 1 ],
width: 100,
} );
}
} );
} );
} );
} );
};
return button;
} );
return options;
} );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment