DataTables PDF Export - How to display images

By default, DataTables does not include images on a PDF export. With the help of the code snippet below, you'll be able to display images on your PDFs.


document.addEventListener("DOMContentLoaded",function(){wp.hooks.addFilter("gk.datatables.options","dt-custom-code",function(t){return t.buttons=t.buttons.map(t=>{if("pdf"!==t.extend)return t;t.action=function(t,e,n,o){let a=[];e.rows({search:"applied"}).every(function(){jQuery(this.node()).find("img").each(function(){let t=this,e=fetch(t.src).then(t=>t.blob()).then(e=>new Promise(n=>{let o=new FileReader;o.onload=()=>{t.src=o.result,n()},o.onerror=t=>{n()},o.readAsDataURL(e)}));a.push(e)})}),Promise.all(a).then(()=>jQuery.fn.dataTable.ext.buttons.pdfHtml5.action.call(this,t,e,n,o))};let e=t.exportOptions?.format?.body;return t.exportOptions=t.exportOptions||{},t.exportOptions.format=t.exportOptions.format||{},t.exportOptions.format.body=function(t,n,o,a){let r=jQuery(a).find("img");if(r.length>0){let i=[];return r.each(function(){let t=jQuery(this).attr("src");t&&i.push("__LINK__"+t)}),i.join("||")}return e?e(t,n,o,a):t},t.customize=function(t){t.content.forEach(t=>{t.table&&t.table.body.forEach(t=>{t.forEach(t=>{if("string"!=typeof t.text||!t.text.includes("__LINK__"))return;let e=t.text.split("||");t.text=void 0,t.stack=[],e.forEach(e=>{let n=e.match(/__LINK__(data:image\/[^;]+;base64,[^\"]+)/);n&&n[1]&&t.stack.push({image:n[1],width:100})})})})})},t}),t})});

This code has been minified to make it easy to be copied. Here's a link to the full code.

This JavaScript code should be copied and pasted, as it is, on the Custom JavaScript editor that sits inside View Editor > View Settings metabox > Custom Code tab.

A screenshot showing the JavaScript code pasted inside the Custom Code tab of the View Settings metabox.

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us