Prepare the Base64 Strings: Collect your PDF files as base64 strings. Each PDF file should be represented as a string in the format
data:application/pdf;base64,<base64_data>
.Create a Download Function: Use JavaScript to create links for downloading each PDF.
Example Code
Here's a simple HTML and JavaScript example to demonstrate how to download multiple base64-encoded PDF
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Download Bulk PDFs</title>
</head>
<body>
<button id="download">Download PDFs</button>
<script>
const pdfs = [
{
name: 'file1.pdf',
base64: 'JVBERi0xLjQKJcfs... (rest of your base64 string)'
},
{
name: 'file2.pdf',
base64: 'JVBERi0xLjQKJcfs... (rest of your base64 string)'
}
// Add more PDFs as needed
];
document.getElementById('download').addEventListener('click', () => {
pdfs.forEach(pdf => {
const link = document.createElement('a');
link.href = `data:application/pdf;base64,${pdf.base64}`;
link.download = pdf.name;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
});
</script>
</body>
</html>
How It Works
- HTML Structure: A simple button triggers the download.
- JavaScript Logic:
- An array of objects (
pdfs
) contains the name and base64 string of each PDF. - When the button is clicked, it loops through the
pdfs
array. - For each PDF, a temporary link element is created, set with the base64 URL, and clicked programmatically to trigger the download.
- An array of objects (
Notes
- Ensure that the base64 string is properly formatted.
- This method works in most modern browsers but may not function in some older ones due to security restrictions.
- Consider file size limitations when using base64 encoding, as larger files can lead to performance issues.
No comments:
Post a Comment