Forum How do I...?

Run a JavaScript file in C# / .NET before rendering the PDF

frankg2694
Hello, I am running Prince using the C#/.NET Wrapper in an .NET MVC project.

While my program does generate a PDF with the line "Hello World!" as expected, I have not been able to run JavaScript files before the PDF is generated. Thus, the PDF does not contain the string "It is all good World!". I have attached my output PDF

My goal is to run JavaScript files that will allow me to modify the html before it is rendered to the output PDF

Here is my code:

cshtml file:
    <button id="PrintPDF" type="button">Print PDF</button>


js file (containing event handler):
    $(document).on("click", "#PrintPDF", function () {
        window.location.href = "/Prince/PrintPDF";
    });


c# controller:
    public ActionResult PrintPDF()
        {
            Prince prn = new Prince("C:\\Program Files (x86)\\Prince\\Engine\\bin\\prince.exe");

            prn.AddScript("~/Scripts/jquery-3.3.1.min.js");
            prn.AddScript("~/Scripts/prince-formatter.js");

            string test = "<html><body>Hello World!</body></html>";
            MemoryStream ms = new MemoryStream();
            bool converted = prn.ConvertString(test, ms);

            ms.Flush();
            ms.Position = 0;

            return File(ms, "application/pdf", "Test.pdf");
        }


prince-formatter.js (file that is attached to Prince object in C# controller)
    $(document).ready(function () {
        $('body').append('<br><p>It is all good World!</p>');
    });

  1. Test.pdf15.2 kB
    The generated PDF of my code
mikeday
You will need to check the Prince output log to see if there are any errors or warning messages from the scripts.
frankg2694
I read the logs and was able to solve the issue, by locating my path as follows:

string strPathAndQuery = HttpContext.Request.Url.PathAndQuery;
string baseUrl = HttpContext.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");

Prince prn = new Prince("C:\\Program Files (x86)\\Prince\\Engine\\bin\\prince.exe");
prn.AddScript(baseUrl + "\\Scripts\\jquery-3.3.1.min.js");
prn.SetJavaScript(true);
prn.AddScript(baseUrl + "\\Scripts\\prince-formatter.js");
prn.SetJavaScript(true);


Thanks!

Edited by frankg2694