How to generate PDF with current pageweb in vb.net? - asp.net

I want to to generate a PDF with all my tables, I searched on google and I found code above and work but for o image and some text:
Imports System.Web
Imports System.Web.UI
Imports System.Data
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub btnPDF_Click(sender As Object, e As EventArgs)
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Me.Page.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.[End]()
End Sub
End Class
This is page with code and in desgin mode is that:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="VBCode.aspx.vb" Inherits="VBCode" EnableEventValidation="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div><img src="https://lh5.googleusercontent.com/_B28NJpJ61hA/TdgnS7lh7mI/AAAAAAAAAi4/oLTicIRgEIw/FinalLogo.png" /></div>
<div><b>Export Webpage with images to pdf using itextsharp dll</b>
<br />
</div><br />
<div>
</div>
<asp:Button ID="btnPDF" runat="server" Text="Export to PDF" OnClick="btnPDF_Click"/>
</form>
</body>
</html>
I want to generate pdf withh my asp table and what i want in him but doesn't work, if you have an alternative please help me....
if i put my code with all codes give me that error:
Invalid URI: The hostname could not be parsed.
On line: htmlparser.Parse(sr)

Related

Create Chart using Fusionchart and get data from database in VB.NET

I want to create a bar chart using fusionchart, and get the data from database
This is my UI, if I click this link will go to the chart page
FRONT CODE FOR UI PAGE (Statistics.aspx)
<form id="form_statistics" runat="server">
<div>
<label for="name"></label>
<asp:DropDownList ID="ddlGender" runat="server"></asp:DropDownList>
<asp:Button ID="BtnSearch" runat="server" Text="Search" />
<br/><br/>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
<asp:Repeater ID="repGender" runat="server">
<HeaderTemplate>
<table cellspacing="0" rules="all" border="1">
<tr>
<th>Gender</th>
<th>Total</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("GENDER")%>
</td>
<td style="text-align: center">
<a href='<%# "Chart.aspx?GENDER_ID=" & Eval("GENDER") & ""%>'> <%# Eval("TOTAL")%></a>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr style="font-weight: bold">
<td>Grand Total</td>
<td style="text-align: center">
<asp:Label runat="server" ID="lblTotal"></asp:Label>
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
BEHIND CODE Statistics.aspx
Imports System.Data.SqlClient
Imports System.IO
Imports WebUserCtrl
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports FusionCharts.Charts
Imports System.Reflection
Partial Class Statistics
Inherits App.Main
Dim MyTotal As Integer
Dim MethodBase As Object
Private Property Label As Object
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindData()
ddlGender_Bind()
End If
End Sub
Sub BindData()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
dal.DB.Parameters.Clear()
dal.DB.AddParameter("#GENDER", ddlGender.SelectedValue)
If dal.DB.ExecuteProcedure(dt, "GENDER_BB") Then
repGender.DataSource = dt
repGender.DataBind()
End If
End Sub
Protected Sub repGender_ItemCommand(source As Object, e As RepeaterCommandEventArgs) Handles repGender.ItemCommand
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
End Sub
Protected Sub repGender_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles repGender.ItemDataBound
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
Dim gData As DataRowView = e.Item.DataItem
MyTotal = MyTotal + gData.Item("TOTAL")
End If
If e.Item.ItemType = ListItemType.Footer Then
' set the total value in footer
Dim lblTotal As Label = e.Item.FindControl("lblTotal")
lblTotal.Text = MyTotal
End If
End Sub
Public Sub ddlGender_Bind()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
If dal.DB.ExecuteProcedure(dt, "GENDER_R") Then
Share.LoadList(ddlGender, "GENDER", "GENDER_ID", dt, Enums.MsgCode.PleaseSelect.ToString, ListOrder.ByValue)
End If
End Sub
Protected Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
dal.DB.Parameters.Clear()
dal.DB.AddParameter("#GENDER", ddlGender.SelectedValue)
If dal.DB.ExecuteProcedure(dt, "GENDER_B") Then
repGender.DataSource = dt
repGender.DataBind()
End If
End Sub
End Class
FRONT CODE FOR Chart.aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Chart.aspx.vb" Inherits="Chart" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<!-- Include jQuery -->
<script type="text/javascript" src=" https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!-- Include fusioncharts core library file -->
<script type="text/javascript" src=" https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
<!-- Include fusion theme file -->
<script type="text/javascript" src=" https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
<!-- Include fusioncharts jquery plugin -->
<script type="text/javascript" src=" https://rawgit.com/fusioncharts/fusioncharts-jquery-plugin/develop/dist/fusioncharts.jqueryplugin.min.js"></script>
<title>Chart</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
BEHIND CODE Chart.aspx
Imports System.Data.SqlClient
Imports System.IO
Imports WebUserCtrl
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports FusionCharts.Charts
Imports System.Reflection
Partial Class Chart
Inherits App.Main
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
If Not IsPostBack Then
CreateChart()
End If
End Sub
Sub CreateChart()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
Dim jsonData As New StringBuilder()
Dim ReqComma As Boolean = False
jsonData.Append("{'chart': {")
jsonData.Append("'caption': 'Chart',")
jsonData.Append("'yAxisName': 'Number',")
jsonData.Append("'theme': 'fusion'")
jsonData.Append("},")
jsonData.Append("'data' : [")
For Each dr As DataRow In dt.Rows
If ReqComma Then
jsonData.Append(",")
Else
ReqComma = True
End If
jsonData.Append("{" + "'label': '" & Replace(dr("GENDER"), "'", "\'") & "', 'value': '" & dr("TOTAL") & "'" + "}")
Next
jsonData.Append("]")
jsonData.Append("}")
Dim ChartOutput As New FusionCharts.Charts.Chart("column2d", MethodBase.GetCurrentMethod().Name, "100%", "300", "json", jsonData.ToString())
Literal1.Text = ChartOutput.Render()
End Sub
End Class
I can go to the other page(Chart.aspx) but I did not get the output, the data is not display. I am not sure where should I put the
Sub CreateChart()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
Dim jsonData As New StringBuilder()
Dim ReqComma As Boolean = False
jsonData.Append("{'chart': {")
jsonData.Append("'caption': 'Chart',")
jsonData.Append("'yAxisName': 'Number',")
jsonData.Append("'theme': 'fusion'")
jsonData.Append("},")
jsonData.Append("'data' : [")
For Each dr As DataRow In dt.Rows
If ReqComma Then
jsonData.Append(",")
Else
ReqComma = True
End If
jsonData.Append("{" + "'label': '" & Replace(dr("GENDER"), "'", "\'") & "', 'value': '" & dr("TOTAL") & "'" + "}")
Next
jsonData.Append("]")
jsonData.Append("}")
Dim ChartOutput As New FusionCharts.Charts.Chart("column2d", MethodBase.GetCurrentMethod().Name, "100%", "300", "json", jsonData.ToString())
Literal1.Text = ChartOutput.Render()
End Sub
It is either at behind code at Statistics.aspx or Chart.aspx. Please help me, I am new with vb.net

Add event onserverclick when a load usercontrol

So I searched but could not solve my problem.
please help.The user control is loaded. But onserverclick event does not work.
WebFormTest.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebFormTest.aspx.vb" Inherits="MS2.WebFormTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=MS2.CLoadUC.RenderUserControl("/Site/testUC.ascx")%>
</div>
</form>
</body>
</html>
testUC.ascx
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="~/testUC.ascx.vb" Inherits="MS2.testUC" %>
<script runat="server">
Protected Sub Button1_Click(sender As Object, e As EventArgs) 'Handles Button1.ServerClick
Dim a = "test"
End Sub
</script>
<button ID="Button1" runat="server" onserverclick="Button1_Click">Button</button>
CLoadUC.RenderUserControl("/Site/testUC.ascx")
Imports System.IO
Imports System.Reflection
Public Class CLoadUC
Public Shared Function RenderUserControl(path As String) As String
Dim pageHolder As New Page
Dim viewControl As UserControl = DirectCast(pageHolder.LoadControl(path), UserControl)
Dim viewControlType As System.Type = viewControl.GetType()
'Return viewControl
pageHolder.Controls.Add(viewControl)
Dim output As New StringWriter()
HttpContext.Current.Server.Execute(pageHolder, output, False)
Return output.ToString()
End Function
End Class

vbCode is autocomplete is not working

I am new to VB.net I want get list of names from my DB with auto complete. I am trying to follow the following example.
But My problem is it not working and I was not getting any error can any one tell me where I am doing wrong.
My home.aspx
<%# Page Title="Home Page" Language="VB" CodeFile="~/home.aspx.vb" AutoEventWireup="true" Inherits="_home"%>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ScripManager1" runat="server"/>
<asp:UpdatePanel ID="autoupdate" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server"
TargetControlID="txtSearch" ServiceMethod="GetList" MinimumPrefixLength="3"
UseContextKey="True" >
</asp:AutoCompleteExtender>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
This is my home.aspx.vb
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Threading
Imports System.Web.Services
Partial Class _Default
Inherits System.Web.UI.Page
<WebMethod()> _
Public Shared Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer, ByVal contextKey As String) As String()
Try
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Test").ConnectionString)
con.Open()
Dim cmd As New SqlCommand("select LoginName from users where LoginName like '#Name' +'%' ", con)
cmd.Parameters.AddWithValue("#Name", prefixText)
'Dim da As New SqlDataAdapter(cmd)
'Dim dt As New DataTable()
'da.Fill(dt)
'Dim InviteSearchListresult As New List(Of String)()
'For i As Integer = 1 To dt.Rows.Count
' InviteSearchListresult.Add(dt.Rows(i)(1).ToString())
' Next
Dim result As New List(Of String)()
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
result.Add(dr("LoginName").ToString())
End While
Return (
From m In result
Where m.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase)
Select m).Take(count).ToArray()
Catch ex As Exception
End Try
End Function
End Class
Please help how to solve this issuse.
Your service method is GetList but your actual method name is GetCompletionList.
Try getting the method names to match up and see if that's the problem. You're trying to call a method that doesn't exist.

'RatingControlChanged' is not a member of 'ASP.default_aspx'.

net using VB. I followed this tutorial for doing my ratings controller
But I am getting the following error
Error 1 'RatingControlChanged' is not a member of 'ASP.default_aspx'. C:\Users\raj\Documents\Visual Studio 2013\WebSites\WebSite13\Default.aspx 46
Error 2 'ratingControl' is not declared. It may be inaccessible due to its protection level. C:\Users\raj\Documents\Visual Studio 2013\WebSites\WebSite13\Default.aspx.vb 16 48 WebSite13
Error 3 'ratingControl' is not declared. It may be inaccessible due to its protection level. C:\Users\raj\Documents\Visual Studio 2013\WebSites\WebSite13\Default.aspx.vb 33 13 WebSite13
Error 4 'lbltxt' is not declared. It may be inaccessible due to its protection level. C:\Users\raj\Documents\Visual Studio 2013\WebSites\WebSite13\Default.aspx.vb 34 13 WebSite13
I have no idea which one is causing the error My DB name is Test and Table name is ratings
This is my default.aspx
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub Page_Load(sender As Object, e As EventArgs)
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax Rating Sample</title>
<style type="text/css">
.ratingEmpty
{
background-image: url(ratingStarEmpty.gif);
width:18px;
height:18px;
}
.ratingFilled
{
background-image: url(ratingStarFilled.gif);
width:18px;
height:18px;
}
.ratingSaved
{
background-image: url(ratingStarSaved.gif);
width:18px;
height:18px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="ScripManager1" runat="server"/>
<div>
<asp:UpdatePanel ID="pnlRating" runat="server">
<ContentTemplate>
<table style="width:35%">
<tr>
<td style="width:20%">
<b>Average Rating:</b>
</td>
<td>
<ajax:Rating ID="ratingControl" AutoPostBack="true" OnChanged="RatingControlChanged" runat="server" StarCssClass="ratingEmpty" WaitingStarCssClass="ratingSaved" EmptyStarCssClass="ratingEmpty" FilledStarCssClass="ratingFilled">
</ajax:Rating>
<b> <asp:label ID="lbltxt" runat="server"/> </b>
</td>
</tr>
<tr>
<td colspan="2">
Testing
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
This is default.aspx.vb code
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("test").ConnectionString)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindRatingControl()
End If
End Sub
Protected Sub RatingControlChanged(ByVal sender As Object, ByVal e As AjaxControlToolkit.RatingEventArgs)
con.Open()
Dim cmd As New SqlCommand("insert into rating(rate)values(#Rating)", con)
cmd.Parameters.AddWithValue("#Rating", ratingControl.CurrentRating)
cmd.ExecuteNonQuery()
con.Close()
BindRatingControl()
End Sub
Protected Sub BindRatingControl()
Dim total As Integer = 0
Dim dt As New DataTable()
con.Open()
Dim cmd As New SqlCommand("Select Rate from rating", con)
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
total += Convert.ToInt32(dt.Rows(i)(0).ToString())
Next
Dim average As Integer = total \ (dt.Rows.Count)
ratingControl.CurrentRating = average
lbltxt.Text = dt.Rows.Count & "user(s) have rated this article"
End If
End Sub
End Class
So can any Help me how to solve this issuse.
Your default.aspx page (front end) appears to be missing the needed page declaration - this is what tells it which codebehind to use.
It should be at the very top line of the default.aspx file.
An example default page declaration:
<%# Page Title="Home Page" Language="VB.net" MasterPageFile="~/Site.Master"
AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTest._Default" %>
The important pieces are:
CodeBehind="Default.aspx.cs"
Inherits="WebTest._Default"
This tells the ASP.net engine which file and class name to associate with the page.
Are you sure you didn't accidentally erase that line and save the file?
This should be easy to restore, just copy from another file and fix the CodeBehind and Inherits (and Title) attributes to have the proper values.

display uploded image in image control

i want to upload an image to a folder which is in my website's folder and then save it's path to database and display the uploaded image in control image.
when i executed my page the image is uploaded succefully and it's saved to database but it dosent displayed on the image control.
this is my view :
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/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>
</div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Image ID="Image1" runat="server" Height="91px" Width="145px" />
</form>
<p>
</p>
</body>
</html>
and this is my code :
Imports System.Data.SqlClient
Imports System.IO
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Dim cn As SqlConnection
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If FileUpload1.PostedFile IsNot Nothing Then
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
'Save files to disk
FileUpload1.SaveAs(Server.MapPath("~/im/" & FileName))
'Add Entry to DataBase
Dim strQuery As String = "insert into dbo.images" & " values(#FileName, #FilePath)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#FileName", FileName)
cmd.Parameters.AddWithValue("#FilePath", "~/im/" & FileName)
cmd.CommandType = CommandType.Text
cmd.Connection = cn
Try
cn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cn.Close()
cn.Dispose()
End Try
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cn = New SqlConnection("server=SEVO-PC;initial catalog=controle;integrated security=true")
End Sub
Protected Sub FileUpload1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles FileUpload1.Load
Image1.ImageUrl = "im/" & FileUpload1.FileName
End Sub
End Class
Try the following edit
Protected Sub FileUpload1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles FileUpload1.Load
Image1.ImageUrl = Server.MapPath("/im/") & FileUpload1.FileName
End Sub

Resources