简体   繁体   中英

Convert panel HTML to PDF using C# ASP.NET

I have a basic form with mostly textboxes and a few checkboxes and radio buttons. Pretty much when a user fills it out and hits submit, I need it to convert and display a PDF with the same structure and offer a print option. I have searched online and I have tried most of the options but nothing works.

I don't expect this to be too difficult, but I am fairly new to C# and can't figure out how to make an HTML panel into a PDF and print it. Any help would be appreciated, thanks in advance!

Here is the HTML for one of the labels and textboxes and the submit button:

        <div>
            <asp:Label ID="lblDate" runat="server" Text="Date:"></asp:Label>
            <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
        </div>

    <asp:Button ID="SubmitButton" runat="server" Text="Button" OnClick="btnSubmit"/>

Once clicked, the .cs page will go through this:

    litDate.Text = "Date: " + txtDate.Text + "<br />";

and update the panel to display the value:

<asp:Panel ID="PDFPanel" runat="server" Visible="false">
            <asp:Literal ID="litDate" runat="server"></asp:Literal>
</asp:Panel>

I am not sure if the panel is needed, but this is how I was able to be sure I was getting the value back. Is there a way to go straight from submit to PDF and print?

Use something like http://code.google.com/p/wkhtmltopdf/

This roughly outlines how to do it: https://stackoverflow.com/a/18767473/181771

I made an asp.net website demo taking the contents of a panel or div and generating a pdf from the html. This is using NReco.PdfGenerator (another wkhtmltopdf wrapper):

https://github.com/jay8anks/Asp.net-HtmlToPdf_NReco.PdfGenerator

Yeah, it's a webform, but anyone sharp enough to do mvc should be able to adapt it fairly easily.

Basically, it is using javascript to get the html between a panel (div) tag and store it in a hiddenfield. Pretty straight forward, except if you want to have css or images, you can't use a relative url for them. I actually just embedded the css inline as a string, but there are other ways of doing it.

Then in the codebehind, this gets the html and generates a pdf from it:

  protected void SaveHtmlToPdf()
{
   
    string htmlOutput = Server.UrlDecode(HiddenField1.Value);     
    
    htmlOutput = string.Join(" ", System.Text.RegularExpressions.Regex.Split(htmlOutput, @"(?:\r\n|\n|\r|\t)"));
    htmlOutput = htmlOutput.Replace("\"", "'");

    string headerStyle = HeaderStyle();

    string finalHtml = headerStyle + htmlOutput;

    var strWr = new StringWriter();
    var htmlWr = new HtmlTextWriter(strWr);
    // base.Render(htmlWr);
    var htmlToPdf = new HtmlToPdfConverter();

    string filename = (orderId + ".pdf");
    string filepath = "~/sales_pdfs";
    string combinedFilePath = Path.Combine(Server.MapPath(filepath), filename).ToString();

    for (int i = 1; i <= NumberOfRetries; ++i)
    {
        try
        {
            htmlToPdf.GeneratePdf(finalHtml, null, combinedFilePath);
            
            break; // When done we can break loop
        }
        catch (IOException e)
        {
            // You may check error code to filter some exceptions, not every error
            // can be recovered.
            if (i <= NumberOfRetries)
            {
                Thread.Sleep(DelayOnRetry);
            }

            ltMsg.Text = "There was a problem creating the PDF";

        }

    }

}

This puts a pdf in a directory so it can be downloaded, but there are other ways that could be handled, as well. We actually wanted a copy of the PDF that someone was generating, so this was the direction we went in.

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