Skip to content

Instantly share code, notes, and snippets.

@swapnilshrikhande
Last active January 6, 2020 13:19
Show Gist options
  • Save swapnilshrikhande/47ab54e789cd36c2f3a9872301e44b9f to your computer and use it in GitHub Desktop.
Save swapnilshrikhande/47ab54e789cd36c2f3a9872301e44b9f to your computer and use it in GitHub Desktop.
Generating and zipping pdf from a visualforce page (salesforce)
<apex:page renderAs="pdf">
PDF Content Goes Here...
</apex:page>
<apex:page >
<apex:includeScript value="{!URLFOR($Resource.zip_js,'gildas-lormeau-zip.js-563fe1d/WebContent/zip.js')}"/>
<a id="download-button" style="display:none;" href="#">Download</a>
<script>
//set base path for libraries to static resource
zip.workerScriptsPath = "{!URLFOR($Resource.zip_js,'gildas-lormeau-zip.js-563fe1d/WebContent/')}";
//fetch pdf as blob
var xhr = new XMLHttpRequest();
xhr.open('GET', '/apex/PdfGenerator', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
console.log("Ajax Respons=",e);
console.log("Status=",this);
if (this.status == 200) {
var pdfData = this.response;
var blob = new Blob([pdfData], {
type : "application/pdf"
});
zipBlob("file.pdf", blob, function(zippedBlob) {
console.log("Zip Created");
downloadFile(zippedBlob);
});
}
};
xhr.send();
//download zipped file
function downloadFile(blob){
var filenameInput = "zippedPDF.zip";
var downloadButton = document.getElementById("download-button");
if (typeof navigator.msSaveBlob == "function") {
navigator.msSaveBlob(blob, filenameInput);
} else {
var clickEvent;
var blobURL = URL.createObjectURL(blob);
clickEvent = document.createEvent("MouseEvent");
clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
downloadButton.href = blobURL;
downloadButton.download = filenameInput;
downloadButton.dispatchEvent(clickEvent);
}
}
function zipBlob(filename, blob, callback) {
// use a zip.BlobWriter object to write zipped data into a Blob object
zip.createWriter(new zip.BlobWriter("application/zip"), function(zipWriter) {
// use a BlobReader object to read the data stored into blob variable
zipWriter.add(filename, new zip.BlobReader(blob), function() {
// close the writer and calls callback function
zipWriter.close(callback);
});
}, onerror);
}
function onerror(message) {
//error handling code goes here
console.error(message);
}
</script>
</apex:page>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment