Converting A Current Web Page to PDF
The following example illustrates converting HTML to PDF by taking current content directly from a web page's content and then converting that content to a PDF. It then returns the PDF as an HTTP Response to the calling HTML Request.
Review the topic Simple Converting for more methods for converting documents to PDFs.
public partial class _Default : System.Web.UI.Page
{
private bool convertToPdf = false;
protected override void Render(HtmlTextWriter writer)
{
if (convertToPdf)
{
TextWriter textWriter = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(textWriter);
base.Render(hTextWriter);
string htmlContent = textWriter.ToString();
byte[] data = Converter.ConvertHtmlString(htmlContent);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.AddHeader("Content-Length", data.Length.ToString());
Response.AddHeader("Content-Disposition", "inline; filename=output.pdf");
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(data);
Response.Flush();
Response.End();
}
else
base.Render(writer);
}
protected void btnConvertToPDF_Click(object sender, EventArgs e)
{
convertToPdf = true;
}
}
Partial Public Class _Default
Inherits System.Web.UI.Page
Private ConvertToPDF As Boolean = False
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
If (ConvertToPDF) Then
Dim textWriter As System.IO.TextWriter = New System.IO.StringWriter()
Dim hTextWriter As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(textWriter)
MyBase.Render(hTextWriter)
Dim htmlContent As String = textWriter.ToString()
Dim data As Byte() = Converter.ConvertHtmlString(htmlContent)
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.AddHeader("Content-Length", data.Length.ToString())
Response.AddHeader("Content-Disposition", "inline; filename=output.pdf")
Response.ContentType = "application/pdf"
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.BinaryWrite(data)
Response.Flush()
Response.End()
End Sub
Else
MyBase.Render(writer)
End If
End Sub
Protected Sub btnConvertToPDF_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConvertToPDF.Click
ConvertToPDF = True
End Sub
End Class