Create a PDF file with JavaScript. jsPDF.js library

In this post from the old Forum, @TIMAI2 shows us how we can create a PDF file with JavaScript using the jsPDF.js library.
Thank you TIM!

HOWTO: Create a PDF, offline, "within" AI2 using jsPDF and base64 extn by Juan Antonio

The code uses the jsPDF.js JavaScript library and an extension to work with Base64.

We will try to adapt the code without using the extension. [spoiler: currently not working]

I have used two methods, one with extension and the other without extension:

Method 1:

  • Image file to Base64 via JavaScript.
  • Convert content to PDF with jsPDF library.
  • Get a PDF in string Base64.
  • With extension KIO4_Base64 convert string Base64 to file pdf.
  • Works!

Method 2:

  • Image file to Base64 via JavaScript.
  • Convert content to PDF with jsPDF library.
  • Get a PDF in string Base64.
  • Using the JavaScript atob command we decode the Base64.
  • String to component File.Save
  • No Works!

The problem is that atob doesn't decode the image well.

1 Like

p70_Base64_Pdf.aia (166.2 KB)

genpdf.html

<script src="jspdf.min.js"></script>
<script>
var content = AppInventor.getWebViewString();
var doc = new jsPDF();
eval(content);
var returnOutput = doc.output('datauri');
 // .split("base64,")[1]) to remove data:*;base64,
    AppInventor.setWebViewString(returnOutput.split("base64,")[1]);
</script>

genpdf_atob.html

<script src="jspdf.min.js"></script>
<script>
var content = AppInventor.getWebViewString();
var doc = new jsPDF();
eval(content);
var returnOutput = doc.output('datauri');
 // .split("base64,")[1]) to remove data:*;base64,
    AppInventor.setWebViewString(atob(returnOutput.split("base64,")[1]));
</script>

ToBase64.htm

<script>
async function readTextFileAsBlob(file) {
    const response = await fetch(file);
    const blob = await response.blob();
    return blob;
}

const blobToBase64DataURL = blob => new Promise(  
    resolvePromise => {
        const reader = new FileReader();
        reader.onload = () => resolvePromise(reader.result);
        reader.readAsDataURL(blob);
    }
);

my_file = AppInventor.getWebViewString(); // INPUT
readTextFileAsBlob(my_file).then(
    async blob => {
        const base64URL = await blobToBase64DataURL(blob);
               // .split("base64,")[1]) to remove data:image/png;base64,
	     AppInventor.setWebViewString(base64URL.split("base64,")[1]); // OUTPUT    
    }
);
</script>
1 Like

- Documentation.

http://raw.githack.com/MrRio/jsPDF/master/docs/index.html

https://mrrio.github.io/

https://artskydj.github.io/jsPDF/docs/jsPDF.html

http://kio4.com/appinventor/277_extension_imagen_string.htm

With 4 MB size photo

p70_Base64_Pdf_v2.aia (5.0 MB)

Dear @Juan_Antonio , king of JS..

Can we print multiple pages by using this method?

Print? Do you mean create?

If you read the pdfs docs you will see how to build multiple pages.