I have converted a rpt file to pdf and saved it in a local system path via web.config and trying to open the pdf file after saving it , from the saved location. I am able to save it in the required folder and able to redirect the folder path to the new windows , but the folder path is appearing with out the '\' and with drive letter as small case
this is my code
var clsPrepareFile = new clsPrepareFile(General.ConnString());
dsUserMatrixReport = clsPrepareFile.UserGroupReport(sValue);
if (dsUserMatrixReport != null && dsUserMatrixReport.Tables.Count > 1 && dsUserMatrixReport.Tables[0].Rows.Count > 0 && dsUserMatrixReport.Tables[1].Rows.Count > 0)
// if (dsUserMatrixReport != null )
{
dsUserMatrixReport.Tables[0].TableName = "Inward_Report1";
dsUserMatrixReport.Tables[1].TableName = "UserStatus";
var rptDocument = new ReportDocument();
//rptDocument.SummaryInfo.ReportTitle = "Inward_Report_" + txtFromDate.Text.Replace("/", "") + "_" + txtToDate.Text.Replace("/", "");
CrystalReportViewer1.Visible = true;
//CrystalReportViewer1.ID = "Inward_Report_" + txtFromDate.Text.Replace("/", "") + "_" + txtToDate.Text.Replace("/", "");
rptDocument.Load(Server.MapPath("~\\Report\\UserGroupReport.rpt"));
rptDocument.SetDataSource(dsUserMatrixReport);
Session.Add("CR_Session", rptDocument);
CrystalReportViewer1.ReportSource = rptDocument;
string filePath = ConfigurationManager.AppSettings["ReportPdfPath"].ToString();
string filename = "UserGroupReport" + DateTime.Now.ToString("yyyyMMdd") + ".pdf";
string pdfname = filePath + filename;
rptDocument.ExportToDisk(ExportFormatType.PortableDocFormat, pdfname);
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(string), "newwindow", "window.open('" + pdfname + "', '_blank')", true);
the script manager is redirecting to anew page and the url appears like this
"c:GeneratedPDFUserGroupReport20200415.pdf"
Related
I am looking to allow a person to to export journal entries into a text file. I can create a file with all the data but rather strictly saving the file somewhere specific I want to allow a user to download and save the file where they want on their computer. How to I force a download of a file after I create it with StreamWriter. I currently have the following code:
string fileName = "Journal.txt";
using (StreamWriter journalExport = new StreamWriter(fileName))
{
foreach (JournalEntryView entry in journalEnteries)
{
//write each journal entery to file/document
journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")");
journalExport.WriteLine(entry.text);
journalExport.WriteLine("");
journalExport.WriteLine("");
}
}
I am also trying to put this into an ActionResult and return the file.
EDIT:
The following code is my new current code and the direction I am looking to go in, but when I use an ActionLink to call this method, i just get redirected to a new page rather than downloading the file.
string fileName = "Journal.txt";
string filepath = ConfigurationManager.AppSettings["DocumentRoot"] + "\\" + id + "\\" + fileName;
using (StreamWriter journalExport = new StreamWriter(filepath))
{
foreach (JournalEntryView entry in journalEnteries)
{
//write each journal entery to file/document
journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")");
journalExport.WriteLine(entry.text);
journalExport.WriteLine("");
journalExport.WriteLine("");
}
}
byte[] fileData = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileData, contentType);
This might be what you are looking for:
public ActionResult GetFile()
{
...processing stuff...
return File("/files/file.pdf", "application/pdf");
//or
return File("/files/file.pdf", "application/force-download", "donwloadname.pdf");
}
I found many solution for Text editing in web pages, But one of most handy and light weight Text Editor is NiEditor . I was burning my head to upload image by editor to my own server. By default editor uploads images on [IMGUR] server.
My question is how to upload image(s) to my own server instead of IMGUR server? Image Link
Here I found nice solution for image uploading in .net. Generic Handlers are the best option for image uploading.
Please follow the steps below to integrate NicEditor with asp.net using C#.
Download latest nicEdit.js from nicedit.com.
Modify line no 1888 with the below code
nicURI: "images.ashx"
Create a generic handler to upload image named images.ashx.
Write the below code in yourhandler.ashx file inside public void ProcessRequest(HttpContext context) .
string baseImageLocation = HttpContext.Current.Server.MapPath("~/Admin/imgs/");
HttpPostedFile Files;
Files = context.Request.Files[0]; // Load File collection into HttpFileCollection variable.
//Files.ContentLength;
//Files.ContentType;
if (Files != null && Files.ContentLength > 0)
{
System.IO.Stream fileStream = Files.InputStream;
fileStream.Position = 0;
byte[] fileContents = new byte[Files.ContentLength];
fileStream.Read(fileContents, 0, Files.ContentLength);
string fileExt = System.IO.Path.GetExtension(Files.FileName).ToLower();
string fileName = Path.GetFileName(Files.FileName);
System.Drawing.Image image = null;
if (fileName != null)
{
if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".jpg" || fileExt == ".png" || fileExt == ".jpeg")
{
image = System.Drawing.Image.FromStream(new System.IO.MemoryStream(fileContents));
if (System.IO.File.Exists(baseImageLocation + "/" + fileName))
fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;
Files.SaveAs(baseImageLocation + fileName);
}
}
string link = VirtualPathUtility.ToAbsolute("~/Admin/imgs/") + fileName;
string imageHeight = image.Height.ToString();
string imageWidth = image.Width.ToString();
string json = "";
json += "{" +
"\"links\": \"" + link + "\"," +
"\"width\": \"" + imageWidth + "\"," +
"\"height\": \"" + imageHeight + "\"" +
"}";
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
Please be noted , place your nicEdit.js file and yourhandler.ashx file in the same folder so that it can be easily accessed path of the handler.
Create image folder to upload images (uploaded by editor) in solution directory.
Back few days i'm trying to make a web application that convert url to pdf. Finally i have done this with the help of wkhtmltopdf.exe
My class code is given below
public class PDFGenerator
{
public static string HtmlToPdf(string pdfOutputLocation, string outputFilenamePrefix, string[] urls,
string[] options = null,
string pdfHtmlToPdfExePath = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe")
{
string urlsSeparatedBySpaces = string.Empty;
try
{
//Determine inputs
if ((urls == null) || (urls.Length == 0))
throw new Exception("No input URLs provided for HtmlToPdf");
else
urlsSeparatedBySpaces = String.Join(" ", urls); //Concatenate URLs
string outputFolder = pdfOutputLocation;
string outputFilename = outputFilenamePrefix + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fff") + ".PDF"; // assemble destination PDF file name
var p = new System.Diagnostics.Process()
{
StartInfo =
{
FileName = pdfHtmlToPdfExePath,
Arguments = ((options == null) ? "" : String.Join(" ", options)) + " " + urlsSeparatedBySpaces + " " + outputFilename,
UseShellExecute = false, // needs to be false in order to redirect output
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true, // redirect all 3, as it should be all 3 or none
WorkingDirectory = HttpContext.Current.Server.MapPath(outputFolder)
}
};
p.Start();
// read the output here...
var output = p.StandardOutput.ReadToEnd();
var errorOutput = p.StandardError.ReadToEnd();
// ...then wait n milliseconds for exit (as after exit, it can't read the output)
p.WaitForExit(60000);
// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();
// if 0 or 2, it worked so return path of pdf
if ((returnCode == 0) || (returnCode == 2))
return outputFolder + outputFilename;
else
throw new Exception(errorOutput);
}
catch (Exception exc)
{
throw new Exception("Problem generating PDF from HTML, URLs: " + urlsSeparatedBySpaces + ", outputFilename: " + outputFilenamePrefix, exc);
}
}
}
and my button click event code is given below
//Create PDF from a single URL
var pdfUrl = PdfGenerator.PDFGenerator.HtmlToPdf(pdfOutputLocation: "~/PDFs/",
outputFilenamePrefix: "GeneratedPDF",
urls: new string[] { "http://news.bbc.co.uk" });
//Create PDF from multiple URLs
pdfUrl = PdfGenerator.PDFGenerator.HtmlToPdf(pdfOutputLocation: "~/PDFs/",
outputFilenamePrefix: "GeneratedPDF",
urls: new string[] { "http://www.google.co.uk", "http://news.bbc.co.uk" });
all code is working properly and saving pdf in my PDFs code. But i have 2 questions:
This code is not working when i host my website because C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe executing error. Is any dll library avail for wkhtmltopdf?
When i run this code pdf saved in silent mode. I want to know that is this possible to save pdf with save dialog or ask user to folder location where they want to save pdf?
Sorry for my bad english.
Place your "wkhtmltopdf.exe" in your project folder, so that it can be easily accessible to your application. There might be some access related issues if you have your .exe file in 'C' folder. Try this, it worked for me.
I have a web service that locates files in a folder (C:\Incoming) and emails them to a specified email address. I want to be able to move that folder, once it has been mailed to another folder (C:\Processed).
I tried using this code below, but it does not work.
string SourceFile = "C:\\Incoming\\" + "" + Year + "" + Month + "" + Day + "";
string destinationFile = "C:\\Processed" + "" + Year + "" + Month + "" + Day + "";
System.IO.File.Move(SourceFile , destinationFile);
I get an error saying that the sourcefile could not be found. I have verified that it does exist and I have access to it.
You are moving folders not file you will need to iterate over files to copy one by one.
string Source = "C:\\Incoming\\" + "" + Year + "" + Month + "" + Day + "";
string destination = "C:\\Processed" + "" + Year + "" + Month + "" + Day + "";
DirectoryInfo di = new DirectoryInfo(Source);
FileInfo[] fileList = di.GetFiles(".*.");
int count = 0;
foreach (FileInfo fi in fileList)
{
System.IO.File.Move(Source+"\\"+fi.Name , destinationFile+"\\"+fi.Name);
}
Use String.Format for one, second use System.IO.File.Exists() to make sure the file is there.
string SourceFile = String.Format("C:\\Incoming\\{0}{1}{2}",Year,Month,Day);
string destinationFile = String.Format("C:\\Processed\\{0}{1}{2}",Year,Month,Day);
if (System.IO.File.Exists(SourceFile) {
System.IO.File.Move(SourceFile , destinationFile);
}
I am using the HTML5 canvas element and the new HTML5 file i\o function to drop multiple files on it and have them upload. It works fine, but now I need to generate a new filename if no files are in the destination directory (It's a 7 digit integer) or get the name of the last uploaded file, convert it to int32 and increment that by one for every new file being uploaded to the same directory. This is where the GetFileName(dir); comes in. The first image always uploads fine but the problem begins once the second file is saved and the process hits ImageJob.Build(), I presume this is because once the new file is starting to write, the GetFile() method runs for second file in line simultaneously and is checking for last written file, which is still being written and this creates the conflict. How can I fix this, maybe I can somehow itterate with a foreach over the Request.InputStream data or implement some kind process watch that waits for the process to finish?
Update: I tried using TempData to store the generated filename, and just increment on the int value in TempData for all the next file names and it appears to do better, gets more images in but still errors at some point. But TempData is not for that as it gets erased after each read, reassigning to it again does not help. Maybe I'll try storing it in session.
The process cannot access the file 'C:\Users\Admin\Documents\Visual Studio
2010\Projects\myproj\myproj\Content\photoAlbums\59\31\9337822.jpg'
because it is being used by another process.
public PartialViewResult Upload()
{
string fileName = Request.Headers["filename"];
string catid = Request.Headers["catid"];
string pageid = Request.Headers["pageid"];
string albumname = Request.Headers["albumname"];
var dir = "~/Content/photoAlbums/" + catid + "/" + pageid + "/" + (albumname ?? null);
var noex = GetFileName(dir);
var extension = ".jpg";
string thumbFile = noex + "_t" + extension;
fileName = noex + extension;
byte[] file = new byte[Request.ContentLength];
Request.InputStream.Read(file, 0, Request.ContentLength);
string imgdir;
string thumbimgdir;
string imageurl;
if (albumname != null)
{
imgdir = Server.MapPath("~/Content/photoAlbums/" + catid + "/" + pageid + "/" + albumname + "/" + fileName);
thumbimgdir = Server.MapPath("~/Content/photoAlbums/" + catid + "/" + pageid + "/" + albumname + "/" + thumbFile);
imageurl = "/Content/photoAlbums/" + catid + "/" + pageid + "/" + albumname + "/" + thumbFile;
}
else
{
imgdir = Server.MapPath("~/Content/photoAlbums/" + catid + "/" + pageid + "/" + fileName);
thumbimgdir = Server.MapPath("~/Content/photoAlbums/" + catid + "/" + pageid + "/" + thumbFile);
imageurl = "/Content/photoAlbums/" + catid + "/" + pageid + "/" + thumbFile;
}
ImageJob b = new ImageJob(file, imgdir, new ResizeSettings("maxwidth=1024&maxheight=768&format=jpg")); b.CreateParentDirectory = true; b.Build();
ImageJob a = new ImageJob(file, thumbimgdir, new ResizeSettings("w=100&h=100&mode=crop&format=jpg")); a.CreateParentDirectory = true; a.Build();
ViewBag.CatID = catid;
ViewBag.PageID = pageid;
ViewBag.FileName = fileName;
return PartialView("AlbumImage", imageurl);
}
public string GetFileName(string dir)
{
var FullPath = Server.MapPath(dir);
var dinfo = new DirectoryInfo(FullPath);
string FileName;
if (dinfo.Exists)
{
var Filex = dinfo.EnumerateFiles().OrderBy(x => x.Name).LastOrDefault();
FileName = Filex != null ? Path.GetFileNameWithoutExtension(Filex.Name) : null;
if (FileName != null)
{
FileName = FileName.Contains("_t") ? FileName.Substring(0, FileName.Length - 2) : FileName;
int fnum;
Int32.TryParse(FileName, out fnum);
FileName = (fnum + 1).ToString();
if (fnum > 999999) { return FileName; } //Check that TryParse produced valid int
else
{
var random = new Random();
FileName = random.Next(1000000, 9999000).ToString();
}
}
else
{
var random = new Random();
FileName = random.Next(1000000, 9999000).ToString();
}
}
else
{
var random = new Random();
FileName = random.Next(1000000, 9999000).ToString();
}
return FileName;
}
You simply cannot use the Random class if you want to generate unique filenames. It uses the current time as the seed, so two exactly concurrent requests will always produce the same 'random' number.
You could use a cryptographic random number generator,
but you would still have to ensure that (a) only one thread would generate it at a time, and (b) you used a sufficiently long identifier to prevent the Birthday paradox.
Thus, I suggest that everyone use GUID identifiers for their uploads, as they solve all of the above issues inherently (I believe an OS-level lock is used to prevent duplicates).
Your method also doesn't handle multiple file uploads per-request, although that may be intentional. You can support those by looping through Request.Files and passing each HttpPostedFile instance directly into the ImageJob.
Here's a simplified version of your code that uses GUIDs and won't encounter concurrency issues.
public PartialViewResult Upload()
{
string albumname = Request.Headers["albumname"];
string baseDir = "~/Content/photoAlbums/" + Request.Headers["catid"] + "/" + Request.Headers["pageid"] + "/" (albumname != null ? albumname + "/" : "");
byte[] file = new byte[Request.ContentLength];
Request.InputStream.Read(file, 0, Request.ContentLength);
ImageJob b = new ImageJob(file, baseDir + "<guid>.<ext>", new ResizeSettings("maxwidth=1024&maxheight=768&format=jpg")); b.CreateParentDirectory = true; b.Build();
ImageJob a = new ImageJob(file, baseDir + "<guid>_t.<ext>", new ResizeSettings("w=100&h=100&mode=crop&format=jpg")); a.CreateParentDirectory = true; a.Build();
//Want both the have the same GUID? Pull it from the previous job.
//string ext = PathUtils.GetExtension(b.FinalPath);
//ImageJob a = new ImageJob(file, PathUtils.RemoveExtension(a.FinalPath) + "_t." + ext, new ResizeSettings("w=100&h=100&mode=crop&format=jpg")); a.CreateParentDirectory = true; a.Build();
ViewBag.CatID = Request.Headers["catid"];
ViewBag.PageID = Request.Headers["pageid"];
ViewBag.FileName = Request.Headers["filename"];
return PartialView("AlbumImage", PathUtils.GuessVirtualPath(a.FinalPath));
}
If the process is relatively quick (small files) you could go in a loop, check for that exception, sleep the thread for a couple of seconds, and try again (up to a maximum number of iterations). One caveat is that if the upload is asynchronous you might miss a file.
A couple of other suggestions:
Make the GetFileName to be a private method so that it doesn't get triggered from the web.
The OrderBy in the Filex query might not do what you expect once the it goes to 8 digits (possible if the first Random() is a very high number).
The Random() should probably be seeded to produce better randomness.