How to save a report directly to .doc? - c#

I have a report and i want to save it directly without a dialog.
Here is my code until now
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = #"C:\temp";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "Browse Text Files";
saveFileDialog.DefaultExt = "doc";
saveFileDialog.Filter = "Word Doc (*.doc)|*.doc|PDF (*.pdf)| *.pdf";
saveFileDialog.CheckFileExists = false;
saveFileDialog.CheckPathExists = true;
Warning[] warnings;
string[] streams;
string mimeType;
string encoding;
string extension;
byte[] bytes = reportTest.LocalReport.Render("Word", null, out mimeType, out encoding, out extension, out streams, out warnings);
//if (saveFileDialog.ShowDialog() == DialogResult.OK)
//{
saveFileDialog.FileName = "123.doc";
var filename = saveFileDialog.FileName;
System.IO.FileStream file = new FileStream(filename, FileMode.Create);
file.Write(bytes, 0, bytes.Length);
file.Close();
//}
Can someone help me how to save the file directly to c:\temp\123.doc (without dialog in the explorer).
Thanks a lot!

You can directly save this with path and file name
filename="PATH" + "test.doc";
System.IO.FileStream file = new FileStream(filename, FileMode.Create);

Related

C# - Trying to grab and save a pdf into my database

In my C# application, I am trying to make it able to pull a pdf and save it, so that end users can press a button and pull up that pdf while they are in the application. But when I copy the content to the filestream it makes the pdf but it is just blank with nothing from the original pdf. What am I doing wrong?
The pdf's could also have pictures on them, and I don't think the way I'm doing it would allow those to be brought over.
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
bool? response = openFileDialog.ShowDialog();
var fileContent = string.Empty;
var filestream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(filestream))
{
fileContent = reader.ReadToEnd();
}
// make folder path
string FolderPath = "ProjectPDFs\\";
string RootPath = "X:\\Vents-US Inventory";
DirectoryInfo FolderDir = new DirectoryInfo(Path.Combine(RootPath, FolderPath));
Directory.CreateDirectory(FolderDir.ToString());
string filePath = "";
string FileName = openFileDialog.SafeFileName;
if (fileContent.Length > 0)
{
filePath = Path.Combine(FolderDir.ToString(), FileName);
using (Stream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] bytestream = Encoding.UTF8.GetBytes(fileContent);
Stream stream = new MemoryStream(bytestream);
stream.CopyTo(fileStream);
}
}

Can't convert UTF8 to default encoding

I am trying to download a file over a RESTful Webservice and then save the file on the computer.
I am using an PDF-File to test the code. I found out the data is UTF-8 encoded so i tried encoding it back to default, because i found out by reading the pdf file locally and writing it back again that it works that way.
Here is my code:
IConsumerRequest getDocumentRequest = class.consumerSession
.Request()
.ForMethod("GET")
.ForUri(new Uri(class.apiEndpoint + "/1/documents/" + id))
.SignWithToken(class.accessToken);
string test = System.IO.File.ReadAllText("C:\\test.pdf", Encoding.Default);
byte[] bytes = Encoding.UTF8.GetBytes(getDocumentRequest.ToString());
string data = Encoding.Default.GetString(bytes);
MessageBox.Show(test.Substring(0, 120) + "\n\n" + data.Substring(0, 120));
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
System.IO.File.WriteAllBytes(saveFileDialog.FileName, bytes);
}
Comparing the string shows the following (second line):
Local String vs String from Webservice
I already tried several ways to convert the string without any difference.
You can use the Encoding.Convert method.
byte[] converted = Encoding.Convert(Encoding.UTF8, Encoding.Default, bytes);
Got it to work with HttpWebResponse:
HttpWebResponse webResponse = getDocumentRequest.ToWebResponse();
Stream stream = webResponse.GetResponseStream();
Encoding enc = System.Text.Encoding.GetEncoding(UTF8);
StreamReader loResponseStream = new StreamReader(webResponse.GetResponseStream(), enc);
string serverResponse = loResponseStream.ReadToEnd();
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
System.IO.File.WriteAllText(saveFileDialog.FileName, serverResponse, Encoding.Default);
}

How to append data in excel with another worksheet

I have created an existing excel with two worksheet. For my first worksheet it consist of data and I would like to add another data into same excel but second worksheet. Can I know why my code doesn't work?
public byte[] ExportToExcel()
{
Warning[] warnings = null;
string[] streamids = null;
string mimeType = null;
string encoding = null;
string extension = null;
byte[] content;
content = this.ReportViewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamids, out warnings);
return content;
}
ReportContent = ExportToExcel();
var path = ScheduledService.gstrReportPath;
var fullpath = Path.Combine(path, "ServerReport" + "_" + "_" + DateTime.Now.ToString("yyMMdd") + ".xls");
bool exists = System.IO.Directory.Exists(path);
if (!exists)
System.IO.Directory.CreateDirectory(path);
//Problem --------------------------------------------------------------------
FileStream file = File.Open(fullpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
file.Write(ReportContent, 0, ReportContent.Length);
file.Flush();
file.Close();
Perhaps this post helps. I found similar comments on StackOverflow too. Set a property PageBreakAtEnd = true on appropriate object such as a rectangle or tablix. This will create a new Worksheet.

Prompt for Saving File to Disk

Actually, I have saved a file in BinaryData in Sql and now I am able to download that file by converting the BinaryData into Bytes.
My code is :
object value = (sender as DevExpress.Web.ASPxGridView.ASPxGridView).GetRowValues(e.VisibleIndex, "ID");
Int64 FileID = Convert.ToInt64(value);
var filedata = (from xx in VDC.SURVEY_QUESTION_REPLIES
where xx.ID == FileID
select xx).FirstOrDefault();
string fileextension = filedata.FILE_EXTENSION.ToString();
string fileName = filedata.ANSWER_TEXT.ToString() + fileextension;
string DocumentName = null;
FileStream FStream = null;
BinaryWriter BWriter = null;
byte[] Binary = null;
const int ChunkSize = 100;
int SizeToWrite = 0;
MemoryStream MStream = null;
DocumentName = fileName;
FStream = new FileStream(#"c:\\" + DocumentName, FileMode.OpenOrCreate, FileAccess.Write);
BWriter = new BinaryWriter(FStream);
Binary = (filedata.FILE_DATA) as byte[];
SizeToWrite = ChunkSize;
MStream = new MemoryStream(Binary);
for (int i = 0; i < Binary.GetUpperBound(0) - 1; i = i + ChunkSize)
{
if (i + ChunkSize >= Binary.Length) SizeToWrite = Binary.Length - i;
byte[] Chunk = new byte[SizeToWrite];
MStream.Read(Chunk, 0, SizeToWrite);
BWriter.Write(Chunk);
BWriter.Flush();
}
BWriter.Close();
FStream.Close();
FStream.Dispose();
System.Diagnostics.Process.Start(#"c:\" + DocumentName);
and it is directly saving the file to the location C Drive.
Now,My Requirement is that,I need to get a Prompt for saving that file and user need to select the location of saving.
Is that Possible ?
You create a filestream with a fixed location here:
FStream = new FileStream(#"c:\\" + DocumentName, FileMode.OpenOrCreate, FileAccess.Write);
What you would have to do is something like this:
var dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
FStream = new FileStream(dialog.FileName, FileMode.OpenOrCreate, FileAccess.Write);
// put the rest of your file saving code here
}
Remember to import the Forms namespace
using System.Windows.Forms;
If its Forms app You can use SaveFileDialog class
it is possible,
you can use a saveFileDialog that you create in your designer and call the "show" method to open that dialog :
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
Source : http://msdn.microsoft.com/en-gb/library/system.windows.forms.savefiledialog.aspx
I see that you use web components of DevExpress, so assuming that you want to send the stream to response for the client to save the file.
If it is an ASP.NET MVC application, you can return FileContentResult as action result directly. Otherwise, you might use the following sample adapting into your code
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + DocumentName);
MStream.WriteTo(Response.OutputStream);
Depending on user's browser settings, save file dialog might be shown to the user.

Creating a PDF from a RDLC Report in the Background

I am running a month-end process and want to have it automatically create some of the reports that need to be created at that time. I am using rdlc reports. Is there a way to automatically create a PDF from a RDLC report in the background?
This is easy to do, you can render the report as a PDF, and save the resulting byte array as a PDF file on disk. To do this in the background, that's more a question of how your app is written. You can just spin up a new thread, or use a BackgroundWorker (if this is a WinForms app), etc. There, of course, may be multithreading issues to be aware of.
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
byte[] bytes = reportViewer.LocalReport.Render(
"PDF", null, out mimeType, out encoding, out filenameExtension,
out streamids, out warnings);
using (FileStream fs = new FileStream("output.pdf", FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}
You can use following code which generate pdf file in background as like on button click and then would popup in brwoser with SaveAs and cancel option.
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;`enter code here`
string extension = string.Empty;
DataSet dsGrpSum, dsActPlan, dsProfitDetails,
dsProfitSum, dsSumHeader, dsDetailsHeader, dsBudCom = null;
enter code here
//This is optional if you have parameter then you can add parameters as much as you want
ReportParameter[] param = new ReportParameter[5];
param[0] = new ReportParameter("Report_Parameter_0", "1st Para", true);
param[1] = new ReportParameter("Report_Parameter_1", "2nd Para", true);
param[2] = new ReportParameter("Report_Parameter_2", "3rd Para", true);
param[3] = new ReportParameter("Report_Parameter_3", "4th Para", true);
param[4] = new ReportParameter("Report_Parameter_4", "5th Para");
DataSet dsData= "Fill this dataset with your data";
ReportDataSource rdsAct = new ReportDataSource("RptActDataSet_usp_GroupAccntDetails", dsActPlan.Tables[0]);
ReportViewer viewer = new ReportViewer();
viewer.LocalReport.Refresh();
viewer.LocalReport.ReportPath = "Reports/AcctPlan.rdlc"; //This is your rdlc name.
viewer.LocalReport.SetParameters(param);
viewer.LocalReport.DataSources.Add(rdsAct); // Add datasource here
byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
// System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename= filename" + "." + extension);
Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
Response.Flush(); // send it to the client to download
Response.End();
You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:
var lr = new LocalReport
{
ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? #"C:\", "Reports", "PathOfMyReport.rdlc"),
EnableExternalImages = true
};
lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));
string mimeType, encoding, extension;
Warning[] warnings;
string[] streams;
var renderedBytes = lr.Render
(
"PDF",
#"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
out mimeType,
out encoding,
out extension,
out streams,
out warnings
);
var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));
var idx = 0;
while (File.Exists(saveAs))
{
idx++;
saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
}
using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
{
stream.Write(renderedBytes, 0, renderedBytes.Length);
stream.Close();
}
lr.Dispose();
You can also add parameters: (lr.SetParameter()), handle subreports: (lr.SubreportProcessing+=YourHandler), or pretty much anything you can think of.
The below code work fine with me of sure thanks for the above comments. You can add report viewer and change the visible=false and use the below code on submit button:
protected void Button1_Click(object sender, EventArgs e)
{
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string HIJRA_TODAY = "01/10/1435";
ReportParameter[] param = new ReportParameter[3];
param[0] = new ReportParameter("CUSTOMER_NUM", CUSTOMER_NUMTBX.Text);
param[1] = new ReportParameter("REF_CD", REF_CDTB.Text);
param[2] = new ReportParameter("HIJRA_TODAY", HIJRA_TODAY);
byte[] bytes = ReportViewer1.LocalReport.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",
"attachment; filename= filename" + "." + extension);
Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
Response.Flush(); // send it to the client to download
Response.End();
}
private void PDFExport(LocalReport report)
{
string[] streamids;
string minetype;
string encod;
string fextension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.25in</MarginTop>" +
" <MarginLeft>0.25in</MarginLeft>" +
" <MarginRight>0.25in</MarginRight>" +
" <MarginBottom>0.25in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
byte[] rpbybe = report.Render("PDF", deviceInfo, out minetype, out encod, out fextension, out streamids,
out warnings);
using(FileStream fs=new FileStream("E:\\newwwfg.pdf",FileMode.Create))
{
fs.Write(rpbybe , 0, rpbybe .Length);
}
}
You can instanciate LocalReport
FicheInscriptionBean fiche = new FicheInscriptionBean();
fiche.ToFicheInscriptionBean(inscription);List<FicheInscriptionBean> list = new List<FicheInscriptionBean>();
list.Add(fiche);
ReportDataSource rds = new ReportDataSource();
rds = new ReportDataSource("InscriptionDataSet", list);
// attachement du QrCode.
string stringToCode = numinscription + "," + inscription.Nom + "," + inscription.Prenom + "," + inscription.Cin;
Bitmap BitmapCaptcha = PostulerFiche.GenerateQrCode(fiche.NumInscription + ":" + fiche.Cin, Brushes.Black, Brushes.White, 200);
MemoryStream ms = new MemoryStream();
BitmapCaptcha.Save(ms, ImageFormat.Gif);
var base64Data = Convert.ToBase64String(ms.ToArray());
string QR_IMG = base64Data;
ReportParameter parameter = new ReportParameter("QR_IMG", QR_IMG, true);
LocalReport report = new LocalReport();
report.ReportPath = Page.Server.MapPath("~/rdlc/FicheInscription.rdlc");
report.DataSources.Clear();
report.SetParameters(new ReportParameter[] { parameter });
report.DataSources.Add(rds);
report.Refresh();
string FileName = "FichePreinscription_" + numinscription + ".pdf";
string extension;
string encoding;
string mimeType;
string[] streams;
Warning[] warnings;
Byte[] mybytes = report.Render("PDF", null,
out extension, out encoding,
out mimeType, out streams, out warnings);
using (FileStream fs = File.Create(Server.MapPath("~/rdlc/Reports/" + FileName)))
{
fs.Write(mybytes, 0, mybytes.Length);
}
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.Clear();
Response.Charset = "";
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + FileName + "\"");
Response.WriteFile(Server.MapPath("~/rdlc/Reports/" + FileName));
Response.Flush();
File.Delete(Server.MapPath("~/rdlc/Reports/" + FileName));
Response.Close();
Response.End();

Categories

Resources