Reportviewer print button in Google Chrome - asp.net

for what I've read, reportviewer print button doesn't work in Google Chrome and Firefox because it's made with an ActiveX control which only works in IE. So I was trying to make an asp.net button outside the report and print the report programatically, but it's being a pain and I was wondering if there is a simpler workaround to get the report to print in Google Chrome.
Edit/Update: I've found this reportviewer print button which is supposed to work for Firefox and Google Chrome, it seems to be working for Firefox but it prints me a blank page in Google Chrome. http://cafalse.blogspot.com/2011/04/reportviewer-print-button-for-firefox.html

If you don't mind adding your own button somewhere on the page. This only works if your way of generating the report looks similar to mine. Basically I take the Report, render it into bytes and send those bytes as a Response in pdf format. This will open up the file as PDF which most browser such as Chrome support. This requires the user to take the extra step and click print.
ServerReport sr = new ServerReport();
ReportViewer.ProcessingMode = ProcessingMode.Remote;
sr = ReportViewer.ServerReport;
sr.ReportServerUrl = new Uri("http://****/****");
sr.ReportPath = "/Report";
ReportParameter paramDateFrom = new ReportParameter();
ReportParameter paramDateTo = new ReportParameter();
ReportParameter paramState = new ReportParameter();
ReportParameter paramCounty = new ReportParameter();
string dateFrom = TB_Date_From.Text;
string dateTo = TB_Date_To.Text;
string state = DDL_State.SelectedValue;
string county = DDL_County.SelectedValue;
paramDateFrom.Name = "DateFrom";
paramDateFrom.Values.Add((dateFrom != "" ? dateFrom : null));
paramDateTo.Name = "DateTo";
paramDateTo.Values.Add((dateTo != "" ? dateTo : null));
paramState.Name = "State";
paramState.Values.Add((state != "" ? Common_Functions.resolveStateID(state) : null));
paramCounty.Name = "County";
paramCounty.Values.Add((county != "" ? Common_Functions.resolveCountyID(county) : null));
ReportViewer.ServerReport.SetParameters(new ReportParameter[] { paramDateFrom, paramDateTo, paramState, paramCounty });
// DUMP PDF TO BROWSER
Warning[] warnings;
string[] streamids;
string mimeType, encoding, extension;
byte[] bytes = ReportViewer.ServerReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "inline; filename=myfile." + extension);
Response.BinaryWrite(bytes);
string pdfPath = Server.MapPath("~") + "pdf." + extension;
FileStream pdfFile = new FileStream(pdfPath, FileMode.Create);
pdfFile.Write(bytes, 0, bytes.Length);
pdfFile.Close();
Response.Flush();
Response.End();

Related

Download PDF into Webapplication(.Net) from SSRS URL access method

I am trying to download a pdf file from SSRS server to my .net application. I am using URL access method to get byte data from the SSRS-URL (http://SsrsDevServer/ReportServer/Pages/ReportViewer.aspx?%2fMainFolder%2fReports%2fInvoice&rs:Command=Render&). My .net application code is shown below.
Note : by making Client.UseDefaultCredentials = true; and without credentials part, it works as expected only in my local machine, but failing when I published it to DEV server.
WebClient Client = new WebClient();
// Client.UseDefaultCredentials = true;
string strReportUser = "USERNAME";
string strReportUserPW = "PAssword";
string strReportUserDomain = "Domain";
Client.Credentials = new System.Net.NetworkCredential(
strReportUser,
strReportUserPW,
strReportUserDomain);
byte[] myDataBuffer = Client.DownloadData(theURL);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
Response.BinaryWrite(myDataBuffer);
Response.Flush();
Response.End();
Appreciate any help.
Thanks!

How to avoid excel file format alert while opening an exported excel file?

Iam exporting html data to excel. I am getting an excel file as soon as i click on export button but when i try to open the excel file an alert is popping up saying that the file format is different from the extension specified. how can i get rid of this alert, please help me Iam using the following code
HttpContext.Current.Response.Buffer = True
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Server.ScriptTimeout = 600
EDIT: Try .csv format. It works for me.
protected void btnExport_Click(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
string filename = "testExportToCSV";
DataTable table1 = new DataTable("Customers");
DataRow row1, row2, row3;
DataColumn colName = new DataColumn("CustomerName", System.Type.GetType("System.String"));
DataColumn colCity = new DataColumn("City", System.Type.GetType("System.String"));
table1.Columns.Add(colName);
table1.Columns.Add(colCity);
row1 = table1.NewRow();
row1["CustomerName"] = "aa";
row1["City"] = "ss";
table1.Rows.Add(row1);
row2 = table1.NewRow();
row2["CustomerName"] = "bb";
row2["City"] = "sdd";
table1.Rows.Add(row2);
row3 = table1.NewRow();
row3["CustomerName"] = "cc";
row3["City"] = "dfgfgf";
table1.Rows.Add(row3);
//foreach (System.Data.DataColumn column in table1.Columns)
//{
for (int i = 0; i < table1.Columns.Count; i++)
{
context.Response.Write(table1.Columns[i].ColumnName.ToString().Replace(",", string.Empty) + ",");
}
context.Response.Write(Environment.NewLine);
//}
foreach (System.Data.DataRow row in table1.Rows)
{
for (int i = 0; i < table1.Columns.Count; i++)
{
context.Response.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
context.Response.End();
}
EDIT 1:
i had work on your issue but i have found that its security issue and its became bad impact on your system's security if we modify it.
Key: HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Security
Value: (DWORD)"ExtensionHardening" =
[0 = Disable check;
1 = Enable check and prompt;
2 = Enable check, no prompt deny open]
Default setting if value not present is 1 (enable and prompt).
You can refer whole article from this link: http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx
EDIT 2: Steps to Modify Registry...
Click Start Menu
In Search Program and files type run
Then type REGEDIT, press OK
HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Excel\Security
Hope, it will helps you. !! Thanks.
If it solves your problem then mark it as answer so that other can also refer it.

Displaying a web page as a pdf with click of a button

I have a new requirement to have a button in my web page, and upon clicking, it displays the web page as a PDF. On researching I found that iTextSharp is used for such purpose.
But I have many Telerik and ASP controls in my web page too. Can I get that also in the PDF using iTextSharp?
If yes then can anyone please provide me a basic link to start using iTextSharp as I haven't came across this tool yet.
According to the answer from #ahaliav I tried with the following code. However, I'm not getting the controls on the pdf.
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(HtmlContent);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
HTMLWorker worker = new HTMLWorker(document);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
// step 3: we create a worker parse the document
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
//Response.Write(document);
//Response.End();
}
protected override void Render(HtmlTextWriter writer)
{
// setup a TextWriter to capture the markup
TextWriter tw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(tw);
// render the markup into our surrogate TextWriter
base.Render(htw);
// get the captured markup as a string
string pageSource = tw.ToString();
// render the markup into the output stream verbatim
writer.Write(pageSource);
// remove the viewstate field from the captured markup
HtmlContent = Regex.Replace(pageSource,
"<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\".*?\" />",
"", RegexOptions.IgnoreCase);
// the page source, without the viewstate field, is in viewStateRemoved
// do what you like with it
}
Please help .
I have other option also,that is to display the image of the full web page when i click a button.Can anyone guide me to any possible directions for these two issues please.
I finally changed my code as:
Response.ContentType = "application/msword";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
MemoryStream msOutput = new MemoryStream();
With this i am able to get the msword document containing all my controls ,but i am also getting some unwanted texts,how can i remove that,if anyone encountered the same problem?
After some research i did not find any solution for showing the controls in the html this code below works fine but with out showing the controls,
in the past i used this http://www.winnovative-software.com/ and it works good for html pages including all controlls you can also test it onlie, the "only" problem is it you need to pay for the license
protected void btnExportToPdf_Click(object sender, EventArgs e)
{
renderPDF = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (renderPDF == true)
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
base.Render(myWriter);
myWriter.Flush();
myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
strmRdr.Dispose();
mem.Dispose();
writer.Write(pageContent);
CreatePDFDocument(pageContent);
}
else
{
StringBuilder sb = new StringBuilder();
HtmlTextWriter tw = new HtmlTextWriter(new System.IO.StringWriter(sb));
base.Render(tw);
// get the captured markup as a string
string pageSource = tw.ToString();
//Get the rendered content
string sContent = sb.ToString();
//Now output it to the page, if you want
writer.Write(sContent);
}
}
public void CreatePDFDocument(string strHtml)
{
string strHTMLpath = Server.MapPath("MyHTML.html");
StreamWriter strWriter = new StreamWriter(strHTMLpath, false, Encoding.UTF8);
strWriter.Write(strHtml);
strWriter.Close();
string strFileName = HttpContext.Current.Server.MapPath("map1.pdf"); // strFileName "C:\\Inetpub\\wwwroot\\Test\\map1.pdf"
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
TextReader tr = new StreamReader(Server.MapPath("MyHTML.html"));
//add the collection to the document
document.Open();
/////////
iTextSharp.text.html.simpleparser.HTMLWorker worker = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
worker.StartDocument();
//// step 5: parse the html into the document
worker.Parse(tr);
//// step 6: close the document and the worker
worker.EndDocument();
//worker.Parse(tr); // getting error "Illegal characters in path"
document.Close();
ShowPdf(strFileName);
}
public void ShowPdf(string strFileName)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.ContentType = "application/pdf";
Response.WriteFile(strFileName);
Response.Flush();
Response.Clear();
}
A very simple Google search brings us to the following forum thread which has your "sollution":
http://forums.asp.net/t/1039486.aspx/1
iTextSharp comes with a little companion : XML Worker
For a demo, have a look here
Even though the documentation refers to the Java API, the adaptation to C# should be straightforward.
As for Telerik/ASP tags, you can extend XMLWorker and define how to convert such tags into PDF elements.

Unable to get the Content of the text file saved in the Database(My-Sql)

In my MySql i am having my data field as longblob i would like to get the content in that file so i have written my code as follows
This is what i am doing before inserting
string filePath = Server.MapPath("AchTemplates/genACH.txt");
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
string strQuery = "insert into tblFiles(FName,FData) values (#_FName, #_FData)";
MySqlCommand cmd = new MySqlCommand(strQuery);
cmd.Parameters.Add("#_FName", MySqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#_FData", MySqlDbType.LongBlob).Value = bytes;
InsertUpdateData(cmd);
//Get Data
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["FData"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
But i am getting the content as system.string[] why it is happening can any one tell
if dt.Rows[0]["FData"] is coming as a string (it is just plain text), use
byte[] bytes = Encoding.UTF8.GetBytes(dt.Rows[0]["FData"]);
If the data is not plain text and binary stored as string (and not base64 encoded), you are in trouble my friend.
UPDATE
According to MySql documentation, it seems you should be using LONGBLOB and not LONGTEXT.

How can I prompt a user to open or save a PDF file returned by a .aspx file?

I have a Flex application that calls a .aspx page on our webserver, which builds a PDF or Excel File. Right now, I am using navigateToURL() to call the file, and this works fine when the output file is built successfully. However, if there is an error, or timeout, there is no way of knowing this in the Flash movie.
I am trying to use URLLoader instead, so that I can listen for an HTTP Status Code, and know when the load is complete, however, the URLLoader simply returns the bitmap data, with nothing prompting the user to open or save the output file. Is there anyway to do this?
Here are both versions of my ActionScript code:
private function buildFile():void
{
var variables:URLVariables = new URLVariables();
variables.rptName = "report1";
variables.rptFormat = "PDF";
var request:URLRequest = new URLRequest();
request.url = "/buildFile.aspx";
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,
httpStatusHandler);
loader.load(request);
}
private function buildFile():void
{
var variables:URLVariables = new URLVariables();
variables.rptName = "report1";
variables.rptFormat = "PDF";
var request:URLRequest = new URLRequest();
request.url = "/buildFile.aspx";
request.method = URLRequestMethod.POST;
request.data = variables;
navigateToURL(request, "_self");
}
FYI, here is the block of code that currently outputs the PDF or Excel file:
System.Web.HttpContext httpC;
httpC = System.Web.HttpContext.Current;
httpC.Response.Clear();
httpC.Response.ClearHeaders();
httpC.Response.Expires = 0;
switch (ReportFormat)
{
case "Excel": Response.ContentType = "application/vnd.ms-excel"; break;
case "PDF": Response.ContentType = "application/pdf"; ; break;
}
Response.AddHeader("Content-disposition", "attachment;filename=" + fileName);
BinaryWriter binaryWriter = new BinaryWriter(httpC.Response.OutputStream);
binaryWriter.Write(result);
You server should send "application/octet-stream" header when user requests that PSD file.
With ASP.NET it could look like this:
Response.ClearContent();
Response.ClearHeaders();
// with this header user will be promted to open or download file
Response.ContentType = "application/octet-stream";
// with this header, you will suggest to save file with "test.pdf" name
Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");
Response.WriteFile(Server.MapPath("~/test.pdf"));
Response.Flush();
Response.Close();
Also take a look here: Downloading files in Flex using the FileReference class
Also set the content-disposition to "attachment" in the aspx page.

Resources