Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Levente Kosa 136 posts 352 karma points
    Dec 03, 2019 @ 23:23
    Levente Kosa
    0

    Call wkhtmltopdf by button

    Hi,

    I need some help, I'm quite beginner yet. I'm using wkthmltopdf to generate pdfs from html. At the moment I just added this code into my view, so when I visit this page, the pdf automatically generates, which is not ideal obviously. The code:

    string PDF_CONVERTER = Server.MapPath("/App_data/wkhtmltopdf/bin/wkhtmltopdf.exe");
    
                var filename = Model.Name + ".pdf";
                var path = Server.MapPath("/App_Data/pdfs/" + filename);
                var url = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + Model.Url + "/floorplan";
    
                // Create directory if needed
                var di = new DirectoryInfo(Path.GetDirectoryName(path));
                if (!di.Exists) { di.Create(); }
    
                // Connect to process
                var process = new System.Diagnostics.Process();
                process.StartInfo.FileName = PDF_CONVERTER;
                process.StartInfo.Arguments = "-T 5 -R 5 -B 5 -L 5 --orientation Landscape --dpi 200 --no-outline --javascript-delay 1000 --disable-smart-shrinking " + url + " " + "\"" + path + "\"";
                process.Start();
                process.WaitForExit();
    
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment; filename=" + filename);
                Response.ContentType = "application/pdf";
                Response.WriteFile(path);
                Response.Flush();
                Response.End();
    

    What I want is to generate the pdf by pressing a "Download PDF" button on this page.

    Any advice?

  • Nathan Woulfe 447 posts 1664 karma points MVP 5x hq c-trib
    Dec 03, 2019 @ 23:43
    Nathan Woulfe
    0

    You could use the path variable that you're using to write the file as the href attribute on a button/link

    <a class="btn" href="@path" target="_blank">Download PDF</a>
    

    Like you said, not ideal to be doing this in the view or on every page load - could shift that logic off into a controller/service, and call it in response to the button/link click. Could also add some code to check the last updated date of the page against the pdf creation date, and only re-generate if the content has changed.

  • Levente Kosa 136 posts 352 karma points
    Dec 04, 2019 @ 09:37
    Levente Kosa
    0

    Thanks for the advice.

    Yes, a controller seems the best choice, but this is where my lack of knowledge :(

Please Sign in or register to post replies

Write your reply to:

Draft