0

I've Base64 string and want to convert into PDF. My function works for a small Base64 string like text, images, emojis and all, but when I add images more than 50 KB (not sure) to the Base64 string then my function can't convert the Base64 string to PDF.

I've tried many previous Stack Overflow solutions, but nothing seems to work.

const ConverToPdf = (b64) =>{
    const base64String = b64
    const byteCharacters = window.atob(base64String);
    const byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += 512) {
      const slice = byteCharacters.slice(offset, offset + 512);

      const byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      const byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }

    const pdfFile = new Blob(byteArrays, { type: 'application/pdf' });
    const pdfUrl = URL.createObjectURL(pdfFile);

    // Create a download link
    const downloadLink = document.createElement('a');
    downloadLink.href = pdfUrl;
    downloadLink.download = 'converted.pdf';

    // Simulate click to trigger the download
    downloadLink.click();

    // Cleanup
    URL.revokeObjectURL(pdfUrl);
    document.body.removeChild(downloadLink);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

0

Using the pdf-lib library, I can convert any size of Base64 to PDF, but I wanted to solve this without any library.

import { PDFDocument } from "pdf-lib";
export const makeDownloadToPDF = async (b64, height, width) => {

    try {
      const binaryString = window.atob(b64);

      const pdfDoc = await PDFDocument.create();
      const imageBytes = Uint8Array.from([...binaryString].map((char) => char.charCodeAt(0)));

      const image = await pdfDoc.embedPng(imageBytes);
      const page = pdfDoc.addPage([image.width, image.height]);
      page.drawImage(image, {
        x: 0,
        y: 0,
        width: image.width,
        height: image.height,
      });

      const pdfBytes = await pdfDoc.save();

      const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' });

      // Create a download link
      const downloadLink = document.createElement('a');
      downloadLink.href = URL.createObjectURL(pdfBlob);
      downloadLink.download = 'converted.pdf';

      // Simulate click to trigger the download
      document.body.appendChild(downloadLink);
      downloadLink.click();

      // Cleanup
      URL.revokeObjectURL(downloadLink.href);
      document.body.removeChild(downloadLink);
    } catch (error) {
      console.error('Error converting image to PDF:', error);
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131