I am converting a website from 1.1 framework to 4.0. The website has functionality to Generate Pdf of the content entered in TextEditor. this website has used "HTMLDoc Software" to convert content to pdf using the below code:
string url, pdfFile, exeFile;
string response = "";
url = GetWebUrl() + "/PDFSpeechDetails.aspx?ArticleId=" + ValueOfQueryString;
pdfFile = HttpContext.Current.Request.PhysicalApplicationPath + "pdfs\\articles\\" + ValueOfQueryString + ".pdf";
exeFile = HttpContext.Current.Request.PhysicalApplicationPath + "html2pdf\\htmldoc.exe";
response = gPDF.ShowPDF(url, pdfFile, exeFile);
and ShowPDF Method is:
public string ShowPDF(string url, string pdfFile, string exeFile)
{
try
{
Process p = new Process();
p.StartInfo.FileName = exeFile;
pdfFile = "\"" + pdfFile + "\"";
string args = " --webpage -f " + pdfFile + " " + url;
p.StartInfo.Arguments = args;
p.Start();
p.WaitForExit();
return "1";
}
catch (Exception ex)
{
return (ex.ToString());
}
}
What the above code is doing:(as the previous developer used)
I have placed a folder named HTML2PDf has an exe file. i am just passing it to argument and running this exe file.
This code is working fine on my local machine as well as on server(I took remote of the server and checked there.), but when i tried to generate the PDF from Outer world means using website's domain name, it does not work. I am not getting any clue why it is not working.
please help me how can i make it working on website.
Related
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 am using the below method to extract an image from a uploaded video and placing the image into a folder.
private string GeneratePreviewImageMP4(string FileName, HttpPostedFile file, string ProperPath)
{
string inputfile = System.IO.Path.Combine(Server.MapPath(ProperPath), file.FileName);
string ext = System.IO.Path.GetExtension(FileName);
string thumbpath = AppDomain.CurrentDomain.BaseDirectory + "Reports\\TrainingLibrary\\Videothumbnails\\";
string thumbname = thumbpath + FileName.Replace(ext, "") + ".jpg";
string thumbargs = "-i " + inputfile + " -ss 00:00:25.435 -qscale:v 2 -vframes 1 " + thumbname;
Process thumbproc = new Process();
thumbproc.StartInfo.FileName = "C:\\FFMPEG\\Bin\\ffmpeg.exe";
thumbproc.StartInfo.Arguments = thumbargs;
thumbproc.StartInfo.UseShellExecute = false;
thumbproc.StartInfo.CreateNoWindow = false;
thumbproc.StartInfo.RedirectStandardOutput = false;
try
{
thumbproc.Start();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
thumbproc.WaitForExit();
thumbproc.Close();
return FileName.Replace(ext, ".jpg");
}
The issue, is that once the image is extracted, I get locked out of the folder. No body has admin rights to that folder. We have to restart the Server just to restore access to that folder.
This is only at certain times, most of the time it works great, but one out of ten times there will be an issue.
Anyone now why this is happening? Does it play the video to extract the image, but does not stop the video?
Try calling Dispose on thumbproc after you are done using it
Try using a lock:
lock (_aStaticObject)
{
//All the code above
}
A word of warning, it can be bad for performance to use a lock inside of a http request (thou shall not mess with thy server's threads), which is why this type of thing belongs in a job.
I am putting together a training site for my company and we need to extract an image from each mp4 video we upload. I have searched lots and decided to try FFMPEG.
Here is what I have so far. I'm not getting errors, but no image in the specified folder.
Any help would be appreciated.
string inputfile = Server.MapPath("/Report/TrainingLibrary/Material/Videos/RMSIMAILSignature.mp4");
//string withouttext;
string thumbpath;
string thumbname;
string thumbargs;
//string thumbre;
thumbpath = AppDomain.CurrentDomain.BaseDirectory + "Reports\\ TrainingLibrary\\Material\\Videos\\";
thumbname = thumbpath + "Image" + "%d" + ".jpg";
thumbargs = "-i " + inputfile + " -vframes 1 -ss 00:00:07 -s 150x150 " + thumbname;
Process thumbproc = new Process();
thumbproc = new Process();
thumbproc.StartInfo.FileName = "C:\\FFMPEG\\Bin\\ffmpeg.exe";
thumbproc.StartInfo.Arguments = thumbargs;
thumbproc.StartInfo.UseShellExecute = false;
thumbproc.StartInfo.CreateNoWindow = false;
thumbproc.StartInfo.RedirectStandardOutput = false;
try
{
thumbproc.Start();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
thumbproc.WaitForExit();
thumbproc.Close();
The situation:
I want to modify the folder quotas on my FileServer through a process executing dirquota.exe
The Problem:
The Process being executed gives no result at all
So Far:
I've redirected the process and arguments being executed on my FileServer to take a closer look what's happening exactly on the serverside.
The executed process gave no exception and everything went just fine, it seemed..
When looking at the current folder quota's on my FileServer nothing has changed..I decided to copy paste my arguments in a CMD.exe on the server, then it all went fine...
I cannot figure why it is not working on my FileServer, probably somthing simple but I need some help here
Important Info:
I'm installing a Windows Service on my FileServer and calling the Method through SOUPUI (This is all working fine).
The installed service is running as a Domain admin and has all the required rights to perform these actions
The Class
public class Quota
{
public string FolderLocation;
public int SizeInMB;
public string FileServerName;
}
The Method
public string SetFolderQuota(Quota quota)
{
Process QuotaProcess = new Process();
QuotaProcess.StartInfo.RedirectStandardOutput = false;
QuotaProcess.StartInfo.FileName = #"cmd.exe";
QuotaProcess.StartInfo.UseShellExecute = true;
QuotaProcess.StartInfo.Arguments = "/C " + "dirquota Quota Add /PATH:" + '"' + quota.FolderLocation + '"' + " /Limit:" + quota.SizeInMB + "mb" + " /remote:" + quota.FileServerName;
try
{
QuotaProcess.Start();
}
catch(Exception Ex)
{
return Ex.Message;
}
return "Correctly Executed: " + QuotaProcess.StartInfo.FileName + QuotaProcess.StartInfo.Arguments;
}
Found The Problem
dirquota.exe is redirected using Windows-on Windows 64-bit redirection. What's happening is that my launch request (from a 32-bit process) is being redirected to %windir%\SysWOW64\dirquota.exe. Since there's no 32-bit version of this particular executable on 64-bit installs, the launch fails. To bypass this process and allow my 32-bit process to access the native (64-bit) path, I have to reference %windir%\sysnative instead
The Code
public string SetFolderQuota(Quota quota)
{
string FileLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),#"sysnative\dirquota.exe");
Process QuotaProcess = new Process();
QuotaProcess.StartInfo.RedirectStandardOutput = false;
QuotaProcess.StartInfo.FileName = FileLocation;
QuotaProcess.StartInfo.UseShellExecute = true;
QuotaProcess.StartInfo.Arguments = " Quota Add /PATH:" + '"' + quota.FolderLocation + '"' + " /Limit:" + quota.SizeInMB + "mb" + " /remote:" + quota.FileServerName;
try
{
QuotaProcess.Start();
}
catch(Exception Ex)
{
return Ex.Message + Environment.NewLine + "FileLocation: " + FileLocation;
}
return "Correctly Executed: " + QuotaProcess.StartInfo.FileName + QuotaProcess.StartInfo.Arguments;
}
Best if you can redirect the output of Process to a log file and see what is the actual exception..
ProcessStartInfo process = new ProcessStartInfo
{
CreateNoWindow = false,
UseShellExecute = false,
RedirectStandardOutput = true,
FileName = #"cmd.exe",
Arguments = "/C " + "dirquota Quota Add /PATH:" + '"' + quota.FolderLocation + '"' + " /Limit:" + quota.SizeInMB + "mb" + " /remote:" + quota.FileServerName
};
Process p = Process.Start(process);
string output = p.StandardOutput.ReadToEnd();
Log the value of output to get the exact exception caused by execution of this command
I have a strange requirement. User can upload their video of any format (or a limited format). We have to store them and convert them to .mp4 format so we can play that in our site.
Same requirement also for audio files.
I have googled but I can't get any proper idea. Any help or suggestions....??
Thanks in advance
You can convert almost any video/audio user files to mp4/mp3 with FFMpeg command line utility. From .NET it can be called using wrapper library like Video Converter for .NET (this one is nice because everything is packed into one DLL):
(new NReco.VideoConverter.FFMpegConverter()).ConvertMedia(pathToVideoFile, pathToOutputMp4File, Formats.mp4)
Note that video conversion requires significant CPU resources; it's good idea to run it in background.
Your Answer
please Replace .flv to .mp4 you will get your answer
private bool ReturnVideo(string fileName)
{
string html = string.Empty;
//rename if file already exists
int j = 0;
string AppPath;
string inputPath;
string outputPath;
string imgpath;
AppPath = Request.PhysicalApplicationPath;
//Get the application path
inputPath = AppPath + "OriginalVideo";
//Path of the original file
outputPath = AppPath + "ConvertVideo";
//Path of the converted file
imgpath = AppPath + "Thumbs";
//Path of the preview file
string filepath = Server.MapPath("~/OriginalVideo/" + fileName);
while (File.Exists(filepath))
{
j = j + 1;
int dotPos = fileName.LastIndexOf(".");
string namewithoutext = fileName.Substring(0, dotPos);
string ext = fileName.Substring(dotPos + 1);
fileName = namewithoutext + j + "." + ext;
filepath = Server.MapPath("~/OriginalVideo/" + fileName);
}
try
{
this.fileuploadImageVideo.SaveAs(filepath);
}
catch
{
return false;
}
string outPutFile;
outPutFile = "~/OriginalVideo/" + fileName;
int i = this.fileuploadImageVideo.PostedFile.ContentLength;
System.IO.FileInfo a = new System.IO.FileInfo(Server.MapPath(outPutFile));
while (a.Exists == false)
{
}
long b = a.Length;
while (i != b)
{
}
string cmd = " -i \"" + inputPath + "\\" + fileName + "\" \"" + outputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".flv" + "\"";
ConvertNow(cmd);
string imgargs = " -i \"" + outputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".flv" + "\" -f image2 -ss 1 -vframes 1 -s 280x200 -an \"" + imgpath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".jpg" + "\"";
ConvertNow(imgargs);
return true;
}
private void ConvertNow(string cmd)
{
string exepath;
string AppPath = Request.PhysicalApplicationPath;
//Get the application path
exepath = AppPath + "ffmpeg.exe";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = exepath;
//Path of exe that will be executed, only for "filebuffer" it will be "flvtool2.exe"
proc.StartInfo.Arguments = cmd;
//The command which will be executed
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
while (proc.HasExited == false)
{
}
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
ReturnVideo(this.fileuploadImageVideo.FileName.ToString());
}
I know it's a bit old thread but if I get here other people see this too. You shoudn't use it process info to start ffmpeg. It is a lot to do with it. Xabe.FFmpeg you could do this by running just
await Conversion.Convert("inputfile.mkv", "file.mp4").Start()
This is one of easiest usage. This library provide fluent API to FFmpeg.