如何将当前 ASPX 页面导出为 PDF

发布于 2024-08-22 20:09:02 字数 249 浏览 13 评论 0原文

我有一个网页,它使用 gridviews 和 html 元素的组合来创建报告。我想给用户一个点击选项,它将导出为 pdf。我不想在服务器上创建 pdf,因为这需要我编写另一个进程来清理文件。

最理想的是,我希望当前页面打开一个新页面,该页面呈现 pdf 并提示用户保存/打开它。

我研究过 iTextSharp,并且如果不必指定每个元素,我有兴趣使用它。如果有一种方法可以指定一个面板及其所有内容或替代方案,我也对此持开放态度。

谢谢!

I have a web page that uses a combination of gridviews and html elements to create a report. I would like to give the user an option to click and it will export to a pdf. I would prefer not to create the pdf on the server as that requires me to write another process to clean up files.

Optimally, I'd like the current page to open a new page that renders the pdf and prompts the user to save it/open it.

I've looked at iTextSharp and am interested in using it if I don't have to specify every element. If there is a way to specify a panel and all of it's contents or an alternative, I'm open to that too.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷月断魂刀 2024-08-29 20:09:02

如果你能说服用户安装一个 PDF 打印机,比如 CutePDf< /a> 或 Foxit PDF Creator

This would be way way easy if you could convince the user to install a PDF Printer like CutePDf or Foxit PDF Creator

财迷小姐 2024-08-29 20:09:02

我知道这是一个老问题,但我的公司做了与您需要的非常相似的事情。我们使用 ExpertPDF 将 html 转换为 pdf 并执行以下操作获取html。务必启用 EnableEventValidation="false",因为将 html 发送回服务器存在安全风险。

ASPX

<%@ Page Language="C#" **EnableEventValidation="false"** Inherits="MyProject.Default"
        Title="PDF Generation" CodeBehind="~/Default.aspx.cs" %>
<html>
<head>
</head>
<body>
<script type="text/javascript" language="JavaScript">
function getHtml() {
var theHtml = document.getElementById('ReportContent').innerHTML;
document.getElementById('<%=hdnHtml.ClientID %>').value = theHtml;
return true;
        }

    </script>
<div id='ReportContent'>    
...Some html content you want turned into a pdf
</div>    
<asp:Button ID="btnSend" OnClick="btnSend_Click" OnClientClick="return getHtml();"
                                                        runat="server" Text="Send" />

</body>
</html>

您还必须发送对 css 样式表和

CS 的引用

protected void BtnExport_Click(object sender, EventArgs e)<br/>
{
     CreateAndDownloadPDF(this.Request, hdnHtml.Value, Page.ResolveUrl("~/css/MAIN.css"), "NameOfTheFile", "Name of the Report");<br/>
}

public static void CreateAndDownloadPDF(System.Web.HttpRequest ServerRequest, string HTML, string cssfile, string FileName, string Footer)
{
string downloadName = FileName + ".pdf";<br/>
try
{
PdfConverter pdfConverter = new PdfConverter();</br>
pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter;
pdfConverter.PdfDocumentOptions.FitWidth = false;
pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
pdfConverter.PdfDocumentOptions.ShowFooter = true;
pdfConverter.PdfDocumentOptions.LeftMargin = 25;
pdfConverter.PdfDocumentOptions.RightMargin = 25;
pdfConverter.PdfDocumentOptions.TopMargin = 25;
pdfConverter.PdfDocumentOptions.BottomMargin = 15;
pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true;
pdfConverter.AvoidImageBreak = true;

pdfConverter.PdfDocumentOptions.ShowHeader = false;

pdfConverter.PdfFooterOptions.FooterText = Footer;
pdfConverter.PdfFooterOptions.FooterTextColor = Color.Black;
pdfConverter.PdfFooterOptions.DrawFooterLine = true;
pdfConverter.PdfFooterOptions.PageNumberText = "Page";
pdfConverter.PdfFooterOptions.ShowPageNumber = true;

pdfConverter.LicenseKey = "LICENSE_KEY_HERE";
string strHTML = "<html><head><link href='" + cssfile + "' rel='stylesheet' type='text/css' /></head><body>" + HTML + "</body></html>";


//set page url
string url = "http://" + ServerRequest.ServerVariables["SERVER_NAME"] + port + ServerRequest.ServerVariables["SCRIPT_NAME"];
//end set page url   
byte[] downloadBytes = pdfConverter.GetPdfBytesFromHtmlString(strHTML, rmsPath);

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString());
response.BinaryWrite(downloadBytes);
response.End();
}
catch (System.Threading.ThreadAbortException) { }  //for response.End()
catch (Exception ex)
{
//Error handling
}
finally
{
if (File.Exists(ServerRequest.MapPath(downloadName)))
     File.Delete(ServerRequest.MapPath(downloadName));
}
}

I know this is an old question but my company does something very similar to what you need. We use ExpertPDF to convert the html to pdf and do the following to get the html. It is important that you turn EnableEventValidation="false" as sending back html to the server is a security risk.

ASPX

<%@ Page Language="C#" **EnableEventValidation="false"** Inherits="MyProject.Default"
        Title="PDF Generation" CodeBehind="~/Default.aspx.cs" %>
<html>
<head>
</head>
<body>
<script type="text/javascript" language="JavaScript">
function getHtml() {
var theHtml = document.getElementById('ReportContent').innerHTML;
document.getElementById('<%=hdnHtml.ClientID %>').value = theHtml;
return true;
        }

    </script>
<div id='ReportContent'>    
...Some html content you want turned into a pdf
</div>    
<asp:Button ID="btnSend" OnClick="btnSend_Click" OnClientClick="return getHtml();"
                                                        runat="server" Text="Send" />

</body>
</html>

You will also have to send a reference to your css style sheet as well

CS

protected void BtnExport_Click(object sender, EventArgs e)<br/>
{
     CreateAndDownloadPDF(this.Request, hdnHtml.Value, Page.ResolveUrl("~/css/MAIN.css"), "NameOfTheFile", "Name of the Report");<br/>
}

public static void CreateAndDownloadPDF(System.Web.HttpRequest ServerRequest, string HTML, string cssfile, string FileName, string Footer)
{
string downloadName = FileName + ".pdf";<br/>
try
{
PdfConverter pdfConverter = new PdfConverter();</br>
pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter;
pdfConverter.PdfDocumentOptions.FitWidth = false;
pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
pdfConverter.PdfDocumentOptions.ShowFooter = true;
pdfConverter.PdfDocumentOptions.LeftMargin = 25;
pdfConverter.PdfDocumentOptions.RightMargin = 25;
pdfConverter.PdfDocumentOptions.TopMargin = 25;
pdfConverter.PdfDocumentOptions.BottomMargin = 15;
pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true;
pdfConverter.AvoidImageBreak = true;

pdfConverter.PdfDocumentOptions.ShowHeader = false;

pdfConverter.PdfFooterOptions.FooterText = Footer;
pdfConverter.PdfFooterOptions.FooterTextColor = Color.Black;
pdfConverter.PdfFooterOptions.DrawFooterLine = true;
pdfConverter.PdfFooterOptions.PageNumberText = "Page";
pdfConverter.PdfFooterOptions.ShowPageNumber = true;

pdfConverter.LicenseKey = "LICENSE_KEY_HERE";
string strHTML = "<html><head><link href='" + cssfile + "' rel='stylesheet' type='text/css' /></head><body>" + HTML + "</body></html>";


//set page url
string url = "http://" + ServerRequest.ServerVariables["SERVER_NAME"] + port + ServerRequest.ServerVariables["SCRIPT_NAME"];
//end set page url   
byte[] downloadBytes = pdfConverter.GetPdfBytesFromHtmlString(strHTML, rmsPath);

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString());
response.BinaryWrite(downloadBytes);
response.End();
}
catch (System.Threading.ThreadAbortException) { }  //for response.End()
catch (Exception ex)
{
//Error handling
}
finally
{
if (File.Exists(ServerRequest.MapPath(downloadName)))
     File.Delete(ServerRequest.MapPath(downloadName));
}
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文