HTML To PDF Using

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 10

Winnovative HTML to PDF Converter for .

NET
--------------------------------------------------------------------------------
The best one for its price the HTML to PDF Converter Library for .NET 2.0 from h
ttp://www.dotnet-reporting.com or the HTML to PDF Converter from http://www.winn
ovative-software.com . You can convert a HTML string or a web page URL to PDF in
only a few lines of code:
PdfConverter pdfConverter = new PdfConverter();
pdfConverter.LicenseKey = "P38cBx6AWW7b9c81TjEGxnrazP+J7rOjs+9omJ3TUycauK+cLWdrI
TM5T59hdW5r";
// set the converter options
pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal
;
pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait
;
pdfConverter.PdfDocumentOptions.ShowHeader = false;
pdfConverter.PdfDocumentOptions.ShowFooter = false;
pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = selectablePDF;
// Performs the conversion and get the pdf document bytes that you can further
// save to a file or send as a browser response
byte[] pdfBytes = pdfConverter.GetPdfFromUrlBytes(urlToConvert);
// send the PDF document as a response to the browser for download
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition",
"attachment; filename=ConversionResult.pdf; size=" + pdfBytes.Length.ToString())
;
response.Flush();
response.BinaryWrite(pdfBytes);
response.Flush();
response.End();

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-------
Dim attach As String = "attachment;filename =export.xls"
Response.ClearContent()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("content-disposition", attach)
Dim str As New StringWriter
Dim htr As New HtmlTextWriter(str)
dg1.RenderControl(htr)
Response.Write(str.ToString())
'Response.Output.GetType()

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
----------------

I am exporting a gridview results to excel.


gvOrganizations.AllowSorting = False
gvOrganizations.AllowPaging = False
gvOrganizations.Visible = True
Response.ContentType = "application/vnd.ms-excel"

--------------------------------------------------------------------------------
-------------------

using System.IO;
using System.Diagnostics;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
Document myDocument;
myDocument = new Document(PageSize.A4.Rotate());
PdfWriter.GetInstance(myDocument, new FileStream("c:\\zz.pdf", FileMode.Create))
;
myDocument.Open();
// myDocument.Add(new Paragraph(tmp));
//myDocument.Close();

--------------------------------------------------------------------------------
-----------------------------------
the only way I could get my datagrid to excel was to surround it with table tags
.
<form>
<table id="gridtable">
<tr>
<td>
<datagrid>
</td>
</tr>
</table>
</form>
then in button click event
Dim attach As String = "attachment;filename =export.xls"
Response.Clear()
Response.Buffer = True '
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Response.AddHeader("content-disposition", attach)
Dim strWriter As New StringWriter()
Dim htmlWriter As New HtmlTextWriter(strWriter)
Me.gridtable.RenderControl(htmlWriter)
Response.Write(strWriter.ToString())
Response.End()
--------------------------------------------------------------------------------
----------------------------------------------

try this code to copy gridview to pdf file. Its working code !
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Han
dles Me.Load
Dim connect As String = "Data Source=com20;Initial Catalog=Test;Integrated Secur
ity=True"
Dim con As New SqlConnection(connect)
con.Open()
Dim str As String = "SELECT * from login"
Dim cmd As New SqlCommand(str, con)
Dim rd As SqlDataReader = cmd.ExecuteReader
gridview1.DataSource = rd
gridview1.DataBind()
End Sub

Protected Sub btn1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Ha


ndles btn1.Click
form1.Controls.Clear()
form1.Controls.Add(gridview1)
Dim sw As New System.Text.StringBuilder()
Dim htw As New HtmlTextWriter(New System.IO.StringWriter(sw))
form1.RenderControl(htw)
Dim html As String = "<html><body><form runat=""server"">" + sw.ToString() + "</
form></body></html>"
Response.Clear()
Response.ContentType = "application/pdf"
Dim document As New iTextSharp.text.Document(PageSize.A4, 80, 50, 30, 65)
Dim writer As iTextSharp.text.pdf.PdfWriter = PdfWriter.GetInstance(document, Re
sponse.OutputStream)
document.Open()
Dim tempFile As String = Path.GetTempFileName()
Using tempwriter As New IO.StreamWriter(tempFile, False)
tempwriter.Write(html)
End Using
HtmlParser.Parse(document, tempFile)
document.Close()
writer.Close()
File.Delete(tempFile)
writer = Nothing
document = Nothing
Response.[End]()
End Sub

--------------------------------------------------------------------------------
--------------------------------------------

Hi,
My code does not shows a SaveAs dialogue box to download the datagrid into Excel
file. My code has no errors. It Doesn't do anything.
I am using this code:
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=Sample.xls");
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.DataSource = dmpset;
dg.DataBind();
dg.RenderControl(htw);

//GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
Please anyone knows helps me.
Thanks in advance...
--------------------------------------------------------------------------------
--------------------------------------------------------------

you guys can try this code its working


one problem is in this can u rectify it ...
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=" & lblExportname
.Text & ".pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Dim dt As New System.Data.DataTable
dt = CType(Session("ExportDt"), DataTable).Copy
Dim Gridview1 As New GridView
Gridview1.DataSource = dt
Gridview1.DataBind()

Gridview1.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim htmlparser As HTMLWorker
Dim pdfDoc As Document
pdfDoc = New Document(PageSize.A0, 10.0F, 10.0F, 10.0F, 0.0F)
htmlparser = New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Output.Write(pdfDoc)
Response.End()
Reagrds
SAJID
--------------------------------------------------------------------------------
-------------------------------------
I am using the below code to export the Grid View data to Excel.
Imports System.IO
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Han
dles Me.Load
If Not Page.IsPostBack Then
gv.AllowPaging = False
gv.DataSource = oDv
gv.DataBind()
GridViewExportUtil.Export("Export.xls", Me.gv)
End If
End Sub
Thanks

--------------------------------------------------------------------------------
---
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();

}
--------------------------------------------------------------------------------
----------------------------
Add reference ABCpdf.dll
Render web page in pdf in landscape or portrait format
Write pdf to browser or save to disk
Save HTML as pdf or save the whole web page as pdf by given URL

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inhe


rits="PrintToPDF._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or


g/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnWriteToBrowserByHTML" runat="server" Text="Write To Browser B
y HTML"/>
<asp:Button ID="btnWriteToDiskByHTML" runat="server" Text="Write To Disk By HTML
"/>
<asp:Button ID="btnWriteToBrowserByURL" runat="server" Text="Write To Browser By
URL"/>
<asp:Button ID="btnWriteToDiskByURL" runat="server" Text="Write To Disk By URL"/
>
</div>
</form>
</body>
</html>

Imports WebSupergoo.ABCpdf6
Imports System.Text
Imports System.IO

Partial Public Class _Default


Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Han


dles Me.Load

End Sub

Private Function GenerateQuoteInHTML() As String

Dim sb As StringBuilder = New StringBuilder


Dim sw As StringWriter = New StringWriter(sb)
Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)

Dim litTop As New Literal


Dim litTopText As New StringBuilder()
'the width on div makes the table readable in landscape format
litTopText.AppendLine("<div style='width:1300px'><b>Title</b><br /><br />")
litTop.Text = litTopText.ToString()

Dim litBottom As New Literal


Dim litBottomText As New StringBuilder()
litBottomText.AppendFormat("</div>")
litBottom.Text = litBottomText.ToString()

litTop.RenderControl(hw)
litBottom.RenderControl(hw)
Return sb.ToString

End Function

Private Sub GeneratePDF(ByVal source As String, ByVal exportType As ExportType,


ByVal sourceType As SourceType)

'set properties
Dim theDoc As New Doc
theDoc.HtmlOptions.PageCacheEnabled = False
theDoc.HtmlOptions.BrowserWidth = 0
theDoc.HtmlOptions.ImageQuality = 101
theDoc.MediaBox.Width = 1000
theDoc.Rect.Width = 1000

Dim theID As Integer


If sourceType = PrintToPDF.SourceType.HTML Then
'Renders a web page specified as HTML.
theID = theDoc.AddImageHtml(source)
ElseIf sourceType = PrintToPDF.SourceType.URL Then
'Renders a web page specified by URL.
theID = theDoc.AddImageUrl(source)
End If

'paging
'http://www.websupergoo.com/helppdf5/default.html?page=source%2F4-examples%2F08-
landscape.htm
Do While True
theDoc.FrameRect()
If (theDoc.Chainable(theID) = False) Then
Exit Do
End If

theDoc.Page = theDoc.AddPage()
theID = theDoc.AddImageToChain(theID)
Loop
theDoc.HtmlOptions.LinkPages()
For x As Integer = 1 To theDoc.PageCount
theDoc.PageNumber = x
theDoc.Flatten()
Next

If exportType = PrintToPDF.ExportType.Browser Then


'write to browser
Dim theData As Byte() = theDoc.GetData()
Response.Expires = -1000
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", theData.Length.ToString())
Dim timestamp As String = String.Format("{0}_{1}_{2}_{3}_{4}_{5}", Date.Now.Year
.ToString, Date.Now.Month.ToString, Date.Now.Day.ToString, Date.Now.Hour.ToStrin
g, Date.Now.Minute.ToString, Date.Now.Second.ToString)
Response.AddHeader("content-disposition", "attachment; filename=MyPDF" + timesta
mp + ".PDF")
Response.BinaryWrite(theData)
theDoc.Clear()
ElseIf exportType = PrintToPDF.ExportType.Disk Then
'write to disk
Dim file As String = Path.Combine(Server.MapPath("CSVUploaded"), "test.pdf")
theDoc.Save(file)
End If

End Sub

Private Sub btnWriteToBrowserByHTML_Click(ByVal sender As Object, ByVal e As Sys


tem.EventArgs) Handles btnWriteToBrowserByHTML.Click
Dim strHTML As String = GenerateQuoteInHTML()
GeneratePDF(strHTML, ExportType.Browser, SourceType.HTML)
End Sub

Private Sub btnWriteToBrowserByURL_Click(ByVal sender As Object, ByVal e As Syst


em.EventArgs) Handles btnWriteToBrowserByURL.Click
GeneratePDF("http://www.google.com.au", ExportType.Browser, SourceType.URL)
End Sub

Private Sub btnWriteToDiskByHTML_Click(ByVal sender As Object, ByVal e As System


.EventArgs) Handles btnWriteToDiskByHTML.Click
Dim strHTML As String = GenerateQuoteInHTML()
GeneratePDF(strHTML, ExportType.Disk, SourceType.HTML)
End Sub

Private Sub btnWriteToDiskByURL_Click(ByVal sender As Object, ByVal e As System.


EventArgs) Handles btnWriteToDiskByURL.Click
GeneratePDF("http://www.google.com.au", ExportType.Disk, SourceType.URL)
End Sub
End Class

Enum SourceType

URL
HTML

End Enum

Enum ExportType

Browser
Disk

End Enum

Reference:
--------------------------------------------------------------------------------
---------------------------------------------------

You might also like