/// <summary>
/// Generate the PDF invoice from the HTML template based on the current session data
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnGenerateInvoice_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
// save customer info on the session
// to make it available in the report page
SaveCustomerInfo();
// get the html string for the report
StringWriter htmlStringWriter = new StringWriter();
Server.Execute("InvoiceTemplate.aspx", htmlStringWriter);
string htmlCodeToConvert = htmlStringWriter.GetStringBuilder().ToString();
htmlStringWriter.Close();
//initialize the PdfConvert object
PdfConverter pdfConverter = new PdfConverter();
// set the license key - required
pdfConverter.LicenseKey = "R8nYyNnI2MjRxtjI29nG2drG0dHR0Q==";
pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
pdfConverter.PdfDocumentOptions.ShowHeader = false;
pdfConverter.PdfDocumentOptions.ShowFooter = false;
// get the base url for string conversion which is the url from where the html code was retrieved
// the base url is used by the converter to get the full URL of the external CSS and images referenced by relative URLs
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;
// get the pdf bytes from html string
byte[] pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlCodeToConvert, baseUrl);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "application/pdf");
response.AddHeader("Content-Disposition", String.Format("attachment; filename=PdfInvoice.pdf; size={0}",
pdfBytes.Length.ToString()));
response.BinaryWrite(pdfBytes);
// Note: it is important to end the response, otherwise the ASP.NET
// web page will render its content to PDF document stream
response.End();
}
|