简体   繁体   中英

Generate PDF from HTML without buttons

I use to generate pdf from my web page wkhtmltopdf.

My project is on ASP.Net and on Bootstrap. So buttons on page has common classes btn btn-primary .

As i know if i set to some element .Visible = false; this element will be invisible on pdf. As there are many buttons on page it isn't too nice to set visibility to each button by Id .

So how can i get all buttons from page just by className?

What i found :

In some post on Stack user advice to add event OnPreRender and in this event set visibility to false. Example:

<asp:LinkButton ID="lnkContinue" runat="server" OnClick="lnkContinue_Click" CssClass="btn btn-primary" Text="Continue" OnPreRender="Button_PreRender"></asp:LinkButton>

protected void Button_PreRender(object sender, EventArgs e)
{
 var button = (HtmlGenericControl)sender;
            button.Visible = !button.Attributes.CssStyle.Value.Contains("btn btn-primary");

}

You should not directly use the HTML generated for your webpage as the HTML for the PDF. Your webpage will likely have navigation and other UI elements (like the mentioned buttons) that aren't appropriate for display in the PDF.

A better solution is to separately generate the HTML. This allows you to retain control over the exact markup used to create the PDF. You can manually build the HTML with StringBuilder or use other libraries to create it.

My favorite way of doing this is using the Razor PDF for MVC library. You use Razor syntax (which is very intuitive) to generate a PDF.

You can supply your own javascript function to wkhtmltopdf to iterate over each element and make them invisible:

http://wkhtmltopdf.org/usage/wkhtmltopdf.txt

--run-script js

var eles = document.getElementsByClassName('btn btn-primary');
for (var x = 0; x < eles.length; x++) {
    eles[x].style.visibility = false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM