Membuat
//convert BASE64 string to Byte{} array
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
//save Byte[] array and download
function saveByteArray(reportName, byte) {
var blob = new Blob([byte]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = reportName + ".pdf";
link.download = fileName;
link.click();
}
//in this case we are exporting a post based on id
function export(id) {
$.ajax({
type: "POST",
url: "Default.aspx/ConvertToPdfAndDownload",
data: '{postId: "' + id + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d == '')
alert('There is a problem exporting the file');
else {
var sampleArr = base64ToArrayBuffer(response.d);
saveByteArray("File-" + id, sampleArr);
}
},
failure: function (response) {
alert("Cannot export thefile: Error in calling Ajax");
}
});
}
// using Pdf generator from https://www.nrecosite.com/pdf_generator_net.aspx
[WebMethod]
public static string ConvertToPdfAndDownload(string postId)
{
string result = "";
try
{
// convert HTML to PDF Byte[] array and return as Base64 string to AJAX
string post = "<h2>Here is a test</h2>";
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
result = Convert.ToBase64String(htmlToPdf.GeneratePdf(post));
}
catch (Exception e) { result = e.Message; }
return result;
}
Harshit Sysquare