I’m using jsPDF with the AutoTable plugin to generate PDFs that include a large number of images. However, when there’s too much data (specifically, images), I encounter the error:
Error generating PDF: RangeError: Invalid string length at Array.join
I’ve narrowed the issue down to the following code block where images are added:
doc.addImage(imgSrc,
textPos.x + (data.cell.padding('horizontal') / 2),
textPos.y + (data.cell.padding('vertical') / 2),
dim_width,
dim,
imgAlias,
'FAST');
It seems that when the total concatenated imgSrc (which contains all the image URLs) becomes too long, the PDF fails to generate or save correctly.
If I remove the imgAlias parameter from addImage(), the PDF generates successfully without the "string is too long"
issue, but the problem is that all the rows in the table display the same image, rather than the relevant image for each row.
How can I solve this issue in a manner where it wouldn’t occur again? Even if the image src URL were to be further shortened, it will still eventually reach the maximum string length resulting in this issue occuring again.
<table id="image-table">
<thead>
<tr>
<th>Index</th>
<th>Image</th>
</tr>
</thead>
<tbody>
@foreach($cvData as $index => $data)
<tr>
<td>{{ $index }} - {{ $data->id }}</td>
<td>
<img
src="{{ env('IMG_URL') . '/' . $data->image_url }}"
class="lazyload"
alt="Image"
crossorigin="anonymous">
</td>
</tr>
@endforeach
</tbody>
</table>
doc.autoTable({
html: table,
theme: 'grid',
startY: 15,
rowPageBreak: 'avoid',
styles: { cellPadding: 2, fontSize: 10, rowPageBreak:'avoid', minCellHeight:10},
didParseCell: async function(cell, opts) {
console.log("Parsing");
if (cell.cell.section === 'body') {
var td = cell.cell.raw;
if (td !== undefined) {
var img = td.getElementsByTagName('img');
if (img.length > 0) {
cell.cell.styles.minCellHeight = 30;
cell.cell.contentHeight = 30;
}
}
}
},
didDrawCell: function(data) {
console.log("Drawing");
if (data.cell.section === 'body') {
var td = data.cell.raw;
if (td !== undefined) {
var img = td.getElementsByTagName('img');
if (img.length > 0) {
var dim = data.cell.height - data.cell.padding('vertical');
var dim_width = data.cell.width - data.cell.padding('horizontal');
var textPos = data.cell;
var imgSrc = img[0].src;
var imgAlias = "img-"+imageIndex
console.log("imgSrc = " +imgSrc);
console.log("imgAlias = " +imgAlias);
doc.addImage(imgSrc,
textPos.x + (data.cell.padding('horizontal')/2),
textPos.y + (data.cell.padding('vertical')/2),
dim_width,
dim,
imgAlias,
'FAST');
imageIndex ++;
}
}
}
}
});