.net pdf변환 다운로드 방법

일전에 프로젝트를 하면서 고객이 계산서나 학위증 같은 일련의 정규화된 화면들을 pdf문서로 다운로드 할 수 있게 요청을 하였다. 그래서 폭풍 구글 검색을 하여 찾아 구현을 했는데... '패널명은 runat=server구문과 함께 form태그 내부에 와야 합니다.'라는 에러를 발생하고 멘붕~


하여 오늘은 완벽하게 .net pdf변환 다운로드 방법에 대해서 알아보겠습니다.

첫번째로 해당하는 소스 화면에 pdf로 출력되는 부분을 panel로 씌웁니다.
두번째로 NReco.PdfGenerator 를 사용하여 pdf 다운로드를 cs에 구현 합니다.
세번째 "형식 'UpdatePanel'의 컨트롤 'ContentPage_페널명'은(는) runat=server 구문과 함께 form 태그 내부에 와야 합니다." 라는 에러를 발생합니다.
네번째 아래와 같이 코드를 aspx.cs 소스에 삽입합니다.

public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
        {
            // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
        }




aspx의 내용이 들어가는 부분은 아래와 같습니다.
<asp:Panel ID="pnCerti" runat="server" CssClass="certi_area">
            <table border="0" cellpadding="0" cellspacing="0" width="100%" class="inter_margin">
                <tr>
                    <td class="certi_tit3">
                        <h1>견 적 서</h1>
                    </td>
                </tr>
            </table>
            <hr />
            <table border="0" cellpadding="0" cellspacing="0" width="100%" class="tbl_certi">
                <colgroup>
                    <col width="130" />
                    <col width="280" />
                    <col width="" />
                </colgroup>
                <tr>
                    <th style="height:60px;">수&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;신 : </th>
                    <td style="font-weight:bold;">
                        &nbsp;<asp:Label ID="FLD_RECEIVE" runat="server" CssClass="certi_lb" style="font-weight:bold;"></asp:Label> 귀중
                    </td>
                    <td rowspan="6">
                        <table border="0" cellpadding="0" cellspacing="0" style="width:100%; vertical-align:top;">
                            <colgroup>
                                <col width="" />
                            </colgroup>
                            <tr>
                                <td><img src="<%=host%>/Pages__C013/Images/ensecurelogo_small.jpg" width="100" height="47" /></td>
<-- 이미지는 "http://도메인.사이트주소/경로" 요딴식으로 해야 적용됨. -->
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
            <asp:UpdatePanel ID="EstimateSubMaintenanceUpdatePanel" runat="server">
                <ContentTemplate>
                    <asp:GridView ID="gvListEstimateSubMaintenance" runat="server" AutoGenerateColumns="false" CssClass="table_content" Width="100%" AllowPaging="false"
                    ShowHeaderWhenEmpty="true" OnRowDataBound = "RowDataBound_EstimateSubMaintenance">
                        <AlternatingRowStyle BackColor="White" />
                        <Columns>
                            <asp:TemplateField HeaderText="No">
                                <ItemTemplate><span id="dataItemIndex"><%# Container.DataItemIndex + 1 %></span></ItemTemplate>
                                <ItemStyle CssClass="data_AC" />
                                <HeaderStyle CssClass="cell_center" Width="5%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="제품명">
                                <ItemTemplate>
                                    <asp:Label ID="PRODUCTNAME" runat="server" Text='<%# Eval("PRODUCTNAME") %>'></asp:Label>
                                </ItemTemplate>
                                <ItemStyle CssClass="data_AL" />
                                <HeaderStyle Width="15%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="상세내역">
                                <ItemTemplate>
                                    <div style="width: 225px;" title='<%# Eval("REMARK") %>'>
                                        <asp:Label ID="lblREMARK" runat="server" Text='<%# Eval("REMARK") %>'></asp:Label>
                                    </div>
                                </ItemTemplate>
                                <ItemStyle CssClass="data_AL" />
                                <HeaderStyle Width="29%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="수량" HeaderStyle-CssClass="cell_center" HeaderStyle-Width="7%">
                                <ItemTemplate>
                                    <asp:Label ID="VOLUME" runat="server" Text='<%# SetComma(Eval("VOLUME")) %>'></asp:Label>
                                </ItemTemplate>
                                <ItemStyle CssClass="data_AR" />
                            </asp:TemplateField>
                        </Columns>
                        <HeaderStyle CssClass="cell_center" />
                        <FooterStyle BackColor="#507CD1" ForeColor="White" Font-Bold="True" />
                        <RowStyle />
                        <EmptyDataRowStyle CssClass="data_AC row25" />
                        <EmptyDataTemplate>
                            데이터가 존재하지 않습니다.
                        </EmptyDataTemplate>
                    </asp:GridView>
                </ContentTemplate>
            </asp:UpdatePanel>
        </asp:Panel>




aspx.cs의 소스는 아래와 같습니다.

#region PDF 버튼 클릭 이벤트
        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = "Estimate_Maintenance_PDF.pdf";
                string TargetFile = Request.PhysicalApplicationPath + "\\Pages__C013\\files\\" + fileName;
                // pdf 파일 저장
                GetDetail(TargetFile);
                Response.ContentType = "application/x-download";
                Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", fileName));
                Response.WriteFile(TargetFile);
                Response.Flush();
                Response.End();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        #endregion

        #region html pdf 파일로 저장
        private void GetDetail(string TargetFile)
        {
            string strHtml = string.Empty;
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            pnCerti.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            strHtml = sr.ReadToEnd();
            sr.Close();
            var htmlContent = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>"
                + "<link href='" + host + "/Pages__C013/Styles/AddStyle.css' rel='stylesheet'>"
                + "<link href='" + host + "/Styles/CommonStyle.css' rel='stylesheet'>"
                + "<link href='" + host + "/Styles/layout.css' rel='stylesheet' type='text/css'>"
                + "<link href='" + host + "/Styles/topnavi.css' rel='stylesheet' type='text/css'>"
                + "<link href='" + host + "/Styles/topnavi_tenant.css' rel='stylesheet' type='text/css'>"
                + "<link href='" + host + "/Styles/common.css' rel='stylesheet' type='text/css'>"
                + "<body>" + strHtml + "</body>";
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
            var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);

            string ModifiedFileName = string.Empty;
            string FinalFileName = string.Empty;
            File.WriteAllBytes(TargetFile, pdfBytes);
        }
        public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
        {
              // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
        }
        #endregion




이상으로 .net pdf변환 다운로드 방법에 대해서 알아보았습니다.
해당 dll을 찾기 어려우신분이 계시면 아래에서 다운로드 받으실 수 있습니다.

pdf변환 dll 다운로드

댓글

이 블로그의 인기 게시물

껌 떼는 법 (완벽 제거)

인성검사 팁 (인성검사 합격)

석청 효능 및 석청 부작용 알아보기