简体   繁体   English

从HTML生成PDF而无需按钮

[英]Generate PDF from HTML without buttons

I use to generate pdf from my web page wkhtmltopdf. 我用来从我的网页wkhtmltopdf生成pdf。

My project is on ASP.Net and on Bootstrap. 我的项目在ASP.Net和Bootstrap上。 So buttons on page has common classes btn btn-primary . 因此页面上的按钮具有常见的类btn btn-primary

As i know if i set to some element .Visible = false; 据我所知,如果我设置一些元素。 .Visible = false; this element will be invisible on pdf. 此元素将在pdf上不可见。 As there are many buttons on page it isn't too nice to set visibility to each button by Id . 由于页面上有许多按钮,因此不能通过Id为每个按钮设置可见性。

So how can i get all buttons from page just by className? 那么,如何仅通过className从页面获取所有按钮?

What i found : 我发现了什么:

In some post on Stack user advice to add event OnPreRender and in this event set visibility to false. 在Stack上的一些帖子中,用户建议添加事件OnPreRender并在此事件中将可见性设置为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. 您不应直接将为网页生成的HTML用作PDF的HTML。 Your webpage will likely have navigation and other UI elements (like the mentioned buttons) that aren't appropriate for display in the PDF. 您的网页可能包含不适合在PDF中显示的导航和其他UI元素(如上述按钮)。

A better solution is to separately generate the HTML. 更好的解决方案是单独生成HTML。 This allows you to retain control over the exact markup used to create the PDF. 这使您可以保留对用于创建PDF的确切标记的控制。 You can manually build the HTML with StringBuilder or use other libraries to create it. 您可以使用StringBuilder手动构建HTML或使用其他库来创建HTML。

My favorite way of doing this is using the Razor PDF for MVC library. 我最喜欢的方法是使用Razor PDF for MVC库。 You use Razor syntax (which is very intuitive) to generate a PDF. 您使用Razor语法(非常直观)来生成PDF。

You can supply your own javascript function to wkhtmltopdf to iterate over each element and make them invisible: 您可以向wkhtmltopdf提供您自己的javascript函数,以遍历每个元素并使它们不可见:

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

--run-script js --run-script js

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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