I need to convert a pdf file into jpeg using c#.
The solution (dll library) have to be free.
I have searched a lot of information on the web but seems that the library pdfiumviewer might be helpful here. It is also available as nuget.
I have tried this code without success, because the new file in jpg format is not saved.
How to do resolve this?
using PdfiumViewer;
using System;
using System.Drawing.Imaging;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
try
{
using (var document = PdfDocument.Load(#"sample.pdf"))
{
var image = document.Render(0, 300, 300, true);
image.Save(#"output.png", ImageFormat.Png);
}
}
catch (Exception ex)
{
// handle exception here;
}
}
}
}
Edit #01
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
try
{
using (var document = PdfDocument.Load(#"C:\\Users\\aaa\\Documents\\Visual Studio 2013\\WebSites\\GroupDocsConversion\\sample.pdf"))
{
var image = document.Render(0, 300, 300, true);
image.Save(#"C:\\Users\\aaa\\Documents\\Visual Studio 2013\\WebSites\\GroupDocsConversion\\output.png", ImageFormat.Png);
}
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
}
Try this combined solution with iTextSharp and Ghostscript.NET ( available on Nuget ).
If necessary install Ghostscript 9.52 for Windows (32 bit)
I hope I was helpful.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="flupload" runat="server" />
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
using Ghostscript.NET;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default4 : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
String PdfFolderPath = HostingEnvironment.MapPath("~/PdfFolder/" + flupload.FileName);
HttpPostedFile file = HttpContext.Current.Request.Files[0];
file.SaveAs(PdfFolderPath);
Pdf2ImageConversion(flupload.FileName, PdfFolderPath);
}
private void Pdf2ImageConversion(string FileName, string PdfFolderPath)
{
String FileNameWithoutExtension = Path.GetFileNameWithoutExtension(FileName);
String ImgFolderPath = HostingEnvironment.MapPath("~/ImgFolder/"
+ FileNameWithoutExtension + ".jpeg");
var info = new System.IO.FileInfo(ImgFolderPath);
if (info.Exists.Equals(false))
{
GhostscriptPngDevice img = new GhostscriptPngDevice(GhostscriptPngDeviceType.Png16m);
img.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
img.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
img.ResolutionXY = new GhostscriptImageDeviceResolution(200, 200);
img.InputFiles.Add(PdfFolderPath);
img.Pdf.FirstPage = 1;
img.Pdf.LastPage = 1;
img.PostScript = string.Empty;
img.OutputPath = ImgFolderPath;
img.Process();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
Related
I'm new to ASP.NET and I'm trying to make a chat application on web.
I used System.Net.Sockets for communication between server and client. With the current version of application I can send data from client to server, and send data from server to client. Client gets the data with a thread and thread has a loop in it to get the data continuously. The problem is I get the data from server to client and it is being added to the listbox items but its not showing the data in the listbox. I am thinking that the problem is because of using thread or loop.
Code of Client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Windows.Forms;
namespace Client_s__Web_2
{
public partial class WebForm1 : System.Web.UI.Page
{
static int port = 13000;
static string IpaAddress = "127.0.0.1";
static Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpaAddress), port);
static string client_ismi = "";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
ClientSocket.Connect(ep);
ListBox1.Items.Add("Client is connected.");
byte[] isim = new byte[1024];
int size = ClientSocket.Receive(isim);
client_ismi = System.Text.Encoding.ASCII.GetString(isim, 0, size);
Response.Redirect("WebForm1.aspx");
ListBox1.Items.Add("The name that server has given: " + client_ismi);
System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false;
ThreadStart st = new ThreadStart(get_data);
Thread thread = new Thread(st);
thread.Start();
}
public void get_data()
{
while (true)
{
byte[] MsgFromServer = new byte[1024];
int size1 = ClientSocket.Receive(MsgFromServer);
ListBox1.Items.Add("Server: " + System.Text.Encoding.ASCII.GetString(MsgFromServer, 0, size1));
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string messageFromClient = null;
messageFromClient = client_ismi + ": " + TextBox1.Text;
TextBox1.Text = "";
ClientSocket.Send(System.Text.Encoding.ASCII.GetBytes(messageFromClient), 0, messageFromClient.Length, SocketFlags.None);
}
}
}
Code of Clients Aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Client_s__Web_2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" DefaultButton = "Button2">
<table>
<tr>
<td>
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="Start" OnClick="Button1_Click" />
</td>
</tr>
<tr>
<td>
<asp:ListBox ID="ListBox1" runat="server" Width ="700px" Height="500px"></asp:ListBox>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server" Width ="700px" Height="50px"></asp:TextBox>
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="Send" OnClick="Button2_Click" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="Button3" runat="server" Text="Refresh" OnClick="Button3_Click" />
</td>
</tr>
</table>
</asp:Panel>
</div>
</form>
</body>
</html>
Code of Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace Main_Server
{
class Program
{
static List<string> names = new List<string>();
static List<Socket> clients = new List<Socket>();
static Program p = new Program();
static int counter = 0;
static void Main(string[] args)
{
int port = 13000;
string IpAddress = "127.0.0.1";
Socket ServerListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpAddress), port);
ServerListener.Bind(ep);
ServerListener.Listen(100);
Console.WriteLine("Server is listening");
Socket ClientSocket = default(Socket);
while(true)
{
counter++;
ClientSocket = ServerListener.Accept();
clients.Add(ClientSocket);
string msgstr = "Guest_" + Convert.ToString(counter);
names.Add(msgstr);
byte[] msg = Encoding.ASCII.GetBytes(msgstr);
int size = msg.Length;
ClientSocket.Send(msg, 0, size, SocketFlags.None);
Console.WriteLine(msgstr + " has connected");
Thread UserThread = new Thread(new ThreadStart(() => p.User(counter - 2, msgstr)));
UserThread.Start();
}
}
public void User(int bulunan_client,string username)
{
while (true)
{
byte[] msg = new byte[1024];
int size = clients[bulunan_client].Receive(msg);
try
{
if (System.Text.Encoding.ASCII.GetString(msg, 0, size).Substring(System.Text.Encoding.ASCII.GetString(msg, 0, size).Length - 10) == "disconnect")
{
names.Remove(names[bulunan_client]);
clients.Remove(clients[bulunan_client]);
Console.WriteLine(username + " has disconnected.");
counter--;
break;
}
else if (System.Text.Encoding.ASCII.GetString(msg, 0, size).Substring(System.Text.Encoding.ASCII.GetString(msg, 0, size).Length - 7) == "connect")
{
string sending_names = "";
for (int i = 0; i < names.Count; i++)
{
sending_names += (names[i] + " ");
}
clients[bulunan_client].Send(System.Text.Encoding.ASCII.GetBytes(sending_names), 0, (System.Text.Encoding.ASCII.GetBytes(sending_names)).Length, SocketFlags.None);
continue;
}
}
catch
{
break;
}
Console.WriteLine(System.Text.Encoding.ASCII.GetString(msg,0,size));
}
}
}
}
Note: When i send "connect" from client i should be getting names of the connected clients. I get them to the listbox items but they are not showing. I did this program with windows form application and i didnt have any problems with listbox at all.
Thank you guys for helping :)
Τhe problem here is that you start a thread and return...in a console this have a point to not block the ui, but in a web application you can't do the same.
So here in this lines, the program returns and render the page.
ThreadStart st = new ThreadStart(get_data);
Thread thread = new Thread(st);
thread.Start();
Later and if the thread call the get_data there is no page to render anything any more...
So the solution is to remove the thread - just include the function of the thread to fill the data.
I also notice on the code this while (true) that is block in a dead loop as it is. Fix this also.
UPDATE: Added Default.aspx.cs if it helps
I'm new in ASP.Net and I'm having trouble making a website. I'm having an error saying Could not load type 'wsclient._Default'. What is my error?
<%# Page Language="C#"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="wsclient._Default" %>
Default.aspx.cs
using localhost;
namespace wsclient
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
lblmessage.Text = "First Loading Time: " +
DateTime.Now.ToLongTimeString();
else
lblmessage.Text = "PostBack at: " +
DateTime.Now.ToLongTimeString();
}
protected void btnservice_Click(object sender, EventArgs e)
{
StockService proxy = new StockService();
lblmessage.Text = String.Format("Current SATYAM Price:{0}",
proxy.GetPrice("SATYAM").ToString());
}
}
}
Default.aspx
Try modifying your code like this:
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="wsclient_Default" %>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class wsclient_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
lblmessage.Text = "First Loading Time: " +
DateTime.Now.ToLongTimeString();
else
lblmessage.Text = "PostBack at: " +
DateTime.Now.ToLongTimeString();
}
protected void btnservice_Click(object sender, EventArgs e)
{
StockService proxy = new StockService();
lblmessage.Text = String.Format("Current SATYAM Price:{0}",
proxy.GetPrice("SATYAM").ToString());
}
}
Simply change "CodeBehind" to "CodeFile" in your Defualt.aspx page "Line 1"
<asp:Repeater ID="rpt_slider" runat="server" OnItemDataBound="rpt_slider_ItemDataBound">
<ItemTemplate>
<cc:HtmlEditor ID="Htmleditor1" runat="server" Height="300px" Width="550px" DialogButtonBarColor="Gray" DialogHeadingColor="Gray" DialogUnselectedTabColor="Gray" TabBackColor="Gray" Text='<%# Eval("banner_text")%>' DialogSelectedTabColor="Gray" EditorBorderColor="Gray" SelectedTabBackColor="Maroon" ToolbarColor="Silver" ToolstripBackgroundImage="Default" ButtonMouseOverColor="Gray" SelectedTabTextColor="WhiteSmoke" TabbarBackColor="Gainsboro" TabMouseOverColor="Gray" DialogSelectedTabTextColor="White" />
</ItemTemplate>
</asp:Repeater>
how to get here text of html editor from Repeater...
here Text='<%# Eval("banner_text")%>' are bound on repeater and how to get text on my c# code??
Try this... I 've tested your tool.. It works..
Add using Winthusiasm.HtmlEditor; as shown below.
Then you can access your editor from server side. You can use below method to find the Editor from your repeater.
By using editor.Text, You can get Editor's Text
If you did't add the Reference DLL Please add it to your references. Otherwise you 'll get errors when you put using Winthusiasm.HtmlEditor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Winthusiasm.HtmlEditor;
namespace ListDrop
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
{
Editor editor= (Editor)item.FindControl("Editor1");
lblMessage.Text = editor.Text;
}
}
}
}
}
FINNAY I GOT MY SOLLUTION.
protected void btnUpdate2_click(object sender, EventArgs e)
{
try
{
Button ib = (Button)sender;
// string index = (ib.CommandName);
RepeaterItem gr = (RepeaterItem)ib.NamingContainer;
int index = gr.ItemIndex;
property.banner_type = "Primary";
property.active = Convert.ToBoolean(((CheckBox)rpt_slider.Items[index].FindControl("checkActive")).Checked);
property.banner_index = Convert.ToInt32(((DropDownList)rpt_slider.Items[index].FindControl("drop_IndexNo")).SelectedValue);
property.banner_id = Convert.ToInt32(ib.CommandArgument);
property.bottom_pos = Convert.ToInt32(((TextBox)rpt_slider.Items[index].FindControl("txtBPOS")).Text);
property.right_pos = Convert.ToInt32(((TextBox)rpt_slider.Items[index].FindControl("txtRPOS")).Text);
property.cr_user = Convert.ToInt32(Session["admin_id"]);
property.cr_date = Convert.ToDateTime(DateTime.Now.ToString());
property.banner_text = Convert.ToString(((HtmlEditor)rpt_slider.Items[index].FindControl("Htmleditor1")).Text);
property.tag = 2;
try
{
int result = 0;
result = balss.banner_insert(property.banner_id, property.banner_type, "", "", property.active, property.banner_index, property.cr_user, property.cr_date, property.banner_text, property.bottom_pos, property.right_pos, property.tag);
if (result > 0)
{
ClientScript.RegisterStartupScript(this.up1.GetType(), "Script", "<script type='text/javascript'>alert('Record Updated successfully.');</script>");
}
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "script", "<script text='text/javascript'> alert('" + ex.Message + "')</script>");
}
finally
{
}
getdata();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "script", "<script type='text/javascript'>alert(' " + ex.Message + "');</script>", false);
}
finally
{
}
Response.Redirect("edit_banner");
}
on button submit click i am used
property.banner_text = Convert.ToString(((HtmlEditor)rpt_slider.Items[index].FindControl("Htmleditor1")).Text);
for get value of html editor for repeater.
i have an aspx, aspx.cs file, in the aspx file i m using javascript functions,
in the javascript code i use the getter (<%=getSize%>) method defined in the aspx.cs file,
but the page returns: "The Controls collection cannot be modified because the control contains code blocks" why?
<!-- language-all:lang-js -->
<%# Page Language="C#" AutoEventWireup="true" CodeFile="uploadFile.aspx.cs"
Inherits="UploadControl_CustomProgressPanel" Title="Untitled Page" %>
<!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 id="Head1" runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
var size = <%=getSize%>;
var id= 0;
function ProgressBar()
{
if(document.getElementById("FileUpload1").value != "")
{
document.getElementById("divProgress").style.display = "block";
document.getElementById("divUpload").style.display = "block";
id = setInterval("progress()",20);
return true;
}
else
{
alert("Select a file to upload");
return false;
}
}
function progress()
{
//size = size + 1;
if(size > 299)
{
clearTimeout(id);
}
document.getElementById("divProgress").style.width = size + "pt";
document.getElementById("lblPercentage").firstChild.data = parseInt(size / 3) + "%";
}
aspx.cs file:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class UploadControl_CustomProgressPanel : System.Web.UI.Page
{
protected int size = 2;
protected int getSize{ get { return this.size; }}
protected void Page_Load(object sender, EventArgs e)
{
string UpPath;
UpPath = "C:\\";
if (! Directory.Exists(UpPath))
{
Directory.CreateDirectory("C:\\");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//StatusLabel.Text = "File scelto, Upload in corso..";
if(FileUpload1.HasFile)
{
try
{
string filePath = Request.PhysicalApplicationPath;
filePath += "classic/hub/csv/";
filePath += FileUpload1.FileName;
this.size = 50;
FileUpload1.SaveAs(filePath);
//StatusLabel.Text = "Upload status: File uploaded!";
Label1.Text = "Upload successfull!";
}
catch(Exception ex)
{
//StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
You haven't posted the full HTML but try to move your script out of the <head> tag.
Is getSize a property or a function? If its a property size will take the value that it is at page load, if the its a function then you need to look at page methods as you cannot call it in this way, heres an example
I want my code to refresh the page once its shown the success label for 3 seconds.
How can i do this in c# code?
i have this following:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.IO;
public partial class CAPTCHA_Contact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//ImageVerification
if (!IsPostBack)
{
SetVerificationText();
}
imCaptcha.ImageUrl = "captcha.ashx?d=" + DateTime.Now.Ticks;
}
public void SetVerificationText()
{
Random ran = new Random();
int no = ran.Next();
Session["Captcha"] = no.ToString();
}
protected void CAPTCHAValidate(object source, ServerValidateEventArgs args)
{
if (Session["Captcha"] != null)
{
if (txtVerify.Text != Session["Captcha"].ToString())
{
SetVerificationText();
args.IsValid = false;
return;
}
}
else
{
SetVerificationText();
args.IsValid = false;
return;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
return;
}
SetVerificationText();
//Save the content
MailMessage mail = new MailMessage();
mail.From = new MailAddress(EmailTB.Text);
mail.To.Add("name#company.co.uk");
mail.Bcc.Add("test#test.co.uk");
mail.Subject = "Web Quote";
mail.IsBodyHtml = true;
mail.Body = "First Name: " + FNameTB.Text + "<br />";
mail.Body += "Email: " + EmailTB.Text + "<br />";
mail.Body += "Telephone: " + TelephoneTB.Text + "<br />";
mail.Body += "Query: " + QueryDD.Text + "<br />";
mail.Body += "Comments: " + CommentsTB.Text + "<br />";
SmtpClient smtp = new SmtpClient();
smtp.Host = "localhost";
smtp.Send(mail);
sucessPH.Visible = true;
}
protected void Reset(object s, EventArgs e)
{
FNameTB.Text = "";
QueryDD.Text = "";
EmailTB.Text = "";
TelephoneTB.Text = "";
CommentsTB.Text = "";
txtVerify.Text = "";
}
}
So after sucessPH.Visible = true; i need to count 3 seconds and then refresh the page. This will then clear the form data and the user will also get 3 seconds to see the message to say the message was successfull.
Any ideas?
Since this is a client-side concern and not a server-side concern, you'll want to do this with JavaScript. Keep in mind that by the time the page is sent to the client all of the server-side code has completed and disposed. Trying to do this with server-side code will result in a lot of unnecessary complexity in this case.
In JavaScript you can reload the page with a delay with something like this:
setTimeout("window.location.reload()", 3000);
Well, if you're using webforms, you could use an update panel, and then use the timer component, just like this guy've done
Tutorial: How to refresh an UpdatePanel control at a timed interval
Right after sucessPH.Visible = true; add following line: ClientScript.RegisterClientScriptBlock(this.GetType(), "refresh", "setTimeout('window.location.href=window.location.href', 3000);", true);
Well.. you are in a web..
So your server can count 3, but you need the client to count 3 and then postback it to the server...
If your server only counts, then the user will not view anything..
Just make your application ajax enable, and use a timer ;)
This is the code for the page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="3000" ontick="Timer1_Tick">
</asp:Timer>
</div>
</form>
</body>
</html>
and in the code behind you have this:
protected void Timer1_Tick(object sender, EventArgs e)
{
//do your thing when reach this tick
}
This page will refresh exactly every 3 seconds.
This is .net 4.