Home > Back-end >  Generate PDF with PDFSharp from HTML template and send to browser
Generate PDF with PDFSharp from HTML template and send to browser

Time:12-04

I am currently writing an addition to a website that I made for work. It generates a PDF from an HTML template and then serves it to the browser so that it can be printed off.

I created a small test that works perfectly. The problem I am running into is when I coded a more complete test, nothing happens when I click the generate button. In the first page when the page loads the PDF is created and shows in the browser. On the second page I get nothing, and no error message which makes troubleshooting this difficult. The code is almost identical between the two pages, so I am really confused as to what is happening.

I will post both versions of my code. Hopefully you guys can figure out what is happening.

Working Page

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        string filePath = Server.MapPath("/test.pdf");
        string html = "<h1>Hello World</h1>";
        PdfSharp.Pdf.PdfDocument my_pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.Letter);
        my_pdf.Save(filePath);
        byte[] docStream = System.IO.File.ReadAllBytes(filePath);
        Response.ClearContent();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");
        Response.AddHeader("Content-Length", docStream.GetLength(0).ToString());
        Response.BinaryWrite(docStream);
        Response.End();
        System.IO.File.Delete(filePath);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
</body>
</html>

Non Working Page

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        frmMain.Style.Add(HtmlTextWriterStyle.Width, "900px");
        frmMain.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto");
        frmMain.Style.Add(HtmlTextWriterStyle.MarginRight, "auto");

        tblForm.Style.Add(HtmlTextWriterStyle.MarginRight, "auto");
        tblForm.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto");
    }
    protected void generate_pdf(object sender, EventArgs e)
    {
        string html_page = System.IO.File.ReadAllText(Server.MapPath("/nice_letter.html"));
        string filePath = Server.MapPath($"/{RandomString(10, true)}.pdf");
        html_page = html_page.Replace("{{letter_date}}", txtLetterDate.Text);
        html_page = html_page.Replace("{{recipient_name}}", txtRecipientName.Text);
        html_page = html_page.Replace("{{patient_name}}", txtPatientName.Text);
        html_page = html_page.Replace("{{appointment_date}}", txtAppointmentDate.Text);
        PdfSharp.Pdf.PdfDocument my_pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html_page, PdfSharp.PageSize.Letter);
        my_pdf.Save(filePath);
        byte[] docStream = System.IO.File.ReadAllBytes(filePath);
        Response.ClearContent();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "inline; filename=letter.pdf");
        Response.AddHeader("Content-Length", docStream.GetLength(0).ToString());
        Response.BinaryWrite(docStream);
        Response.End();
        System.IO.File.Delete(filePath);
    }
    public string RandomString(int size, bool lowerCase = false)  
    {
        Random _random = new Random();
        var builder = new StringBuilder(size);    
        char offset = lowerCase ? 'a' : 'A';  
        const int lettersOffset = 26;  
        for (var i = 0; i < size; i  )  
        {  
            var @char = (char)_random.Next(offset, offset   lettersOffset);  
            builder.Append(@char);  
        }
        return lowerCase ? builder.ToString().ToLower() : builder.ToString();  
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="frmMain" runat="server">
        <center><h1>Nice Letter</h1></center>
        <asp:ScriptManager ID="smMain" runat="server"></asp:ScriptManager>
            <asp:UpdatePanel ID="upMain" runat="server">
                <ContentTemplate>
                    <table id="tblForm" runat="server">
                        <tr>
                            <td><asp:Label ID="lblLetterDate" Text="Letter Date: " runat="server"></asp:Label></td>
                            <td><asp:TextBox ID="txtLetterDate" Width="150" runat="server"></asp:TextBox></td>
                        </tr>
                        <tr>
                            <td><asp:Label ID="lblRecipientName" Text="Recipient: " runat="server"></asp:Label></td>
                            <td><asp:TextBox ID="txtRecipientName" Width="300" runat="server"></asp:TextBox></td>
                        </tr>
                        <tr>
                            <td><asp:Label ID="lblPatientName" Text="Patient Name: " runat="server"></asp:Label></td>
                            <td><asp:TextBox ID="txtPatientName" Width="300" runat="server"></asp:TextBox></td>
                        </tr>
                        <tr>
                            <td><asp:Label ID="lblAppointmentDate" Text="Appointment Date: " runat="server"></asp:Label></td>
                            <td><asp:TextBox ID="txtAppointmentDate" Width="150" runat="server"></asp:TextBox></td>
                        </tr>
                        <tr>
                            <td></td>
                            <td><asp:Button ID="cmdCreatePDF" runat="server" Text="Create PDF" OnClick="generate_pdf" /></td>
                        </tr>
                    </table>
                </ContentTemplate>
            </asp:UpdatePanel>
    </form>
</body>
</html>

CodePudding user response:

I figured out the problem. Apparently it was because I was doing an ajax request via the update panels. It works fine without the ajax.

  • Related