Search code examples
angulartypescriptblob

How to convert a string (not a File) to a PDF Blob and then open said file in browser in TypeScript (Angular)


I want to take a regular string, let's say, 'hello world!' and convert that into a PDF Blob and then open that pdf in the browser. There are numerous similar posts on here but none of them resolves my specific issue. My function looks like this:

  openPdf(data: string): void {
    const base64String = btoa(data);
    const bufferArray = Uint8Array.from(atob(base64String), c => c.charCodeAt(0));
    const pdfBlob = new Blob([bufferArray], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(pdfBlob);
    const link = document.createElement('a');
    link.href = url;
    link.target = '_blank';
    link.click();
    window.URL.revokeObjectURL(url);
  }

This is working fine in that no console errors are thrown and it does indeed open a new browser window but the problem is that the content is missing. Here is a screenshot of what it looks like in Chrome. Could it be because I'm simply converting a regular string and trying to convert that into a PDF? enter image description here


Solution

  • Yes, if you use base64 to convert a regular string into a PDF, it may not work because a pdf document has a proper structure and a format you need to follow base64 might not follow it.

    You can rather use jsPDF or pdfmake to create a pdf document from your own data, then use the same method to create a Blob and open it to a new window. This is an example using jsPDF

    import jsPDF from 'jspdf';
    
    function openPdf(data: string): void {
      const doc = new jsPDF();
      doc.text(data, 10, 10);
      const pdfBlob = doc.output('blob');
      const url = window.URL.createObjectURL(pdfBlob);
      const link = document.createElement('a');
      link.href = url;
      link.target = '_blank';
      link.click();
      window.URL.revokeObjectURL(url);
    }