I have a web method where I am converting HTML to PDF and saving it to a local folder. The goal is for the user to download the file without needing to reload the page. To achieve this, I am attempting to make an AJAX POST call to the web method to retrieve the byte array and convert it into a PDF. However, I keep encountering a 500 error:
{Message: "There was an error processing the request.", StackTrace: "", ExceptionType: ""}
Despite confirming that the web method is being triggered (as evidenced by breakpoints stopping there and observing the binary array before the return statement, as well as the file created in the folder), the error persists. Below is the code snippet:
C#:
[WebMethod]
public static byte[] getfile(string one, string two)
{
HttpContext context = HttpContext.Current;
HtmlToPdf converter = new HtmlToPdf();
converter.Options.MinPageLoadTime = 10;
converter.Options.MaxPageLoadTime = 30;
PdfDocument doc = converter.ConvertUrl("http://localhost/dashboard_pdf.aspx?one=" + one+ "&" + "two=" + two);
string appPath = HttpContext.Current.Request.ApplicationPath;
Random rnd = new Random();
int num = rnd.Next(1, 1000000);
string path = context.Server.MapPath(appPath + "/Web/" + num + ".pdf");
doc.Save(path);
doc.Close();
FileStream stream = File.OpenRead(path);
byte[] fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();
byte[] b1 = System.IO.File.ReadAllBytes(path);
return fileBytes;
}
JS:
$.ajax({
type: "POST",
url: "dashboard.aspx/getfile",
contentType: "application/json; charset=utf-8",
data: "{'one':\"" + one+ "\", 'two':\"" + two + "\" }",
dataType: "json",
processData: false,
success: function (data) {
data = data.d;
var byteArray = new Uint8Array(data);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/pdf' }));
a.download = "Dashboard";
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
}
});
Any suggestions on how to resolve this issue?
Thank you.