Converting a doc to a pdf in a mvc c# environment - pdf

Hi I've got a c# MVC application running under a particular user (app.pool user).
I need to convert a doc or docx file to a pdf.
I thought a good option would be to use libreoffice to fire a process that would start this.
To make life easier for myself (and if libreoffice shouldn't work) I used a batch file.
echo on
SET var1=%2
IF "%var1:~-1%"=="\" SET var1=%var1:~0,-1%
cd %var1%
echo %1
echo %var1%
start /wait "" "C:\Program Files (x86)\LibreOffice 4\program\soffice" -headless -convert-to pdf %1 -outdir %var1%
My code for starting this is as follows.
var ba = #"C:\inetpub\wwwroot\apps\xxxxxxxxx\Services\convert.bat";
fullPath = #"C:\inetpub\wwwroot\apps\xxxxxxxxx\Files\Temp\636295920370843147.doc";
var tempPath = #"C:\inetpub\wwwroot\apps\xxxxxxxxx\Files\Temp";
string command = ba;
//Process.Start(command, fullPath + " " + tempPath);
var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command + " "+ fullPath+ " "+ tempPath);
processInfo.CreateNoWindow = false;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
var process = Process.Start(processInfo);
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
Trace.WriteLine("output>>" + e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
Trace.WriteLine("error>>" + e.Data);
process.BeginErrorReadLine();
process.WaitForExit();
Trace.WriteLine("ExitCode: {0}", process.ExitCode.ToString());
process.Close();
This does seem to work manually but when I run the code I can see the whole thing just stalls around the conversion. Looking at the threads and it seems to load the gdiplus.dll which I think is a graphics module which doesn't seem right.
The process though when I copy and paste that into my 'run' box in windows works fine and the pdf is made.
I've checked that the app.pool user has access to both libreoffice and also the folder with the files.
I've ran this as the app.pool user, in the c# it just stalls on the process.WaitForExit();
line. Until I kill the process.
Any ideas?
I've also tried many different ways of executing the soffice conversion. just straight from the c# - libreoffice 4,5.
I've seen some people use libreoffice as a service, is this an option? If so how?
Richard
EDIT
Ah, just changed the app Pool user to myself and now it works, so there is a permissions thing with the standard app pool user. How to find out what....

I added the user into the administrators group on the computer and restarted the machine, then it worked.
It might not be the best solution but after 2 days of trying to get this to work I'm not going to argue.
Richard

Related

i have trouble running a postscript file in java, using ghost4j api. btw i have very little knowledge of ghostscript initialization parameters

this is the code that i have copied from ghost4j official site.:
BasicConfigurator.configure();
Ghostscript gs = Ghostscript.getInstance();
String[] gsArgs = new String[7];
gsArgs[0] = "-dQUIET";
gsArgs[1] = "-dNOPAUSE";
gsArgs[2] = "-dBATCH";
gsArgs[3] = "-dSAFER";
gsArgs[4] = "-sDEVICE=display";
gsArgs[5] = "-sDisplayHandle=0";
gsArgs[6] = "-dDisplayFormat=16#804";
try {
gs.initialize(gsArgs);
gs.runFile("input.ps");
gs.exit();
} catch (GhostscriptException e) {
System.out.println("ERROR: " + e.getMessage());
}
}}
link to the official site:
enter link description here
and this is the console output:
This isn't a PostScript nor a Ghostscript question.
If I were you I would first try running Ghostscript from the command line with the same set of parameters and see if that works.
If it doesn't then you'll have more information to try and track down the problem.
The output in your question is not standard Ghostscript output and so must be produced from Ghost4j. You should drop the -dQUIET while you are trying to debug a problem, auppressing output won't help.
In fact I'd also drop the DisplayHandle and DisplayFormat, BATCH, NOPAUSE and SAFER switches. Finally you should put a fully qualified path in for "input.ps" in case the current directory is changed.

Process.Start PDF in a folder

I can't get Process.Start to simply launch a PDF with default PDF viewer.
I tried so many combinations of shell execute, working folder etc etc. Keeps giving me either 'The system cannot find the file specified' or 'the directory name is invalid'
private void button1_Click(object sender, EventArgs e)
{
string filename = #"Milking and cooling software set 2018-39.pdf";
MessageBox.Show(currentpath + #"\Astronaut A5 v1.5(b7)\documentation\" + filename);
fullpath = currentpath + #"\Astronaut A5 v1.5(b7)\documentation";
fullfile = fullpath + filename;
ProcessStartInfo process = new ProcessStartInfo();
process.WorkingDirectory = fullpath;
process.UseShellExecute = false;
process.FileName = fullfile;
process.RedirectStandardOutput = true;
process.Verb = "run as";
Process.Start(process);
}
Why is this so hard, I have tried for hours to simply lauch Acrobat Reader to open a PDF file. I can double click it no problem in it's location but C# can't open it, either I get .NET errors or Adobe opens and says it can't find the file. Tried so many combinations of "\"", full path, hard coded path etc etc...unbelievable that this is so hard to code in this day and age.
You’ve told the system to not use ShellExecute. This means the path you’re giving should be an actual executable program. PDFs are not so if you want to open it with the default reader use ShellExecute.
process.UseShellExecute = true;
Also using “run as” as the verb doesn’t make any sense here, unless there is such a verb defined for PDFs which I’m pretty sure there isn’t. That should be removed.

Why VBA does not create file via external .exe file?

I have this testing program written in C#. It simply creates a text file in directory where this exe file is.
class Program
{
static void Main(string[] args)
{
string exactPath = Path.GetFullPath("test.txt");
File.Create(exactPath);
Console.ReadLine();
}
}
Now VBA is running it by Call Shell
strProgramName = ActiveWorkbook.path & "\test.exe"
Call Shell("" & strProgramName & "")
Everything seems fine. Except it does not create any file and it should. If I run it manually it does creates a file.
MS documentation for Shell states that :
The Shell function requires unmanaged code permission, which might
affect its execution in partial-trust situations. For more
information, see SecurityPermission and Code Access Permissions.
So I think that somehow my test.exe does not have permission to create a file.

How to backup and restore sessions on Fiddler startup and shutdown?

What I want is backup all sessions at Fiddler shutdown and when I turn it on again it needs to load that sessions again.
I managed to change the FiddlerScript by creating a save action and dump all sessions with this:
case "save":
FiddlerObject.UI.actSelectAll();
FiddlerObject.UI.actSaveSessionsToZip(CONFIG.GetPath("Captures") + "saved.saz");
FiddlerObject.StatusText = "Saved in " + CONFIG.GetPath("Captures") + "saved.saz";
break;
It works fine and all currently loaded sessions are saved.
I tried to create a action to restore them but it does nothing (I loaded the session but don't know how to get back in the grid):
case "restore":
//I don't know what I need to do with this
Utilities.ReadSessionArchive(CONFIG.GetPath("Captures") + "saved.saz", true);
break;
After that I want to do something similar do execute them with ExecAction at startup and shutdown but this is another part of my puzzle.
TL;DR
How to restore a previously saved dump using FiddlerScript on startup?
Rules > Customize Rules.
Update the OnBoot and OnShutdown functions thusly:
static function OnBoot() {
FiddlerApplication.UI.actLoadSessionArchive("_stored.saz");
}
static function OnShutdown() {
FiddlerApplication.UI.actSelectAll();
var sFilename = (CONFIG.GetPath("Captures") + "_stored.saz");
FiddlerApplication.UI.actSaveSessionsToZip(sFilename);
}

How can I use JScript to create a shortcut that uses "Run as Administrator"

I have a JScript script that runs using cscript.exe. It creates a shortcut on the desktop (and in the start menu) that runs cscript.exe with parameters to run another JScript script. It looks, in relevant part, like this:
function create_shortcut_at(folder, target_script_folder)
{
var shell = new ActiveXObject("WScript.Shell");
var shortcut = shell.CreateShortcut(folder + "\\Run The Script.lnk");
shortcut.TargetPath = "cscript";
shortcut.Arguments = "\""+target_script_folder+"\\script.js\" /aParam /orTwo";
shortcut.IconLocation = target_script_folder+"\\icon.ico";
shortcut.Save();
}
It gets called like create_shortcut_at(desktop_folder, script_folder).
And that works, as far as it goes. It creates the desktop icon, pointing properly to the script and runs it when double-clicked. The problem is that it really needs to run the script "as administrator".
And the script really does need to run "as administrator" -- it installs applications (for all users) and reboots the computer. (For those interested, the script is wpkg.js. Modifying it to self-elevate is undesirable.)
Since the target of the shortcut is actually "cscript.exe", I can't use a manifest for the escalation. I could probably theoretically install a cscript.exe.manifest in the windows directory, but even if that worked, it would be a terrible idea for reasons that are obvious.
I'd also prefer not to use a dummy script, since that is an extra file to deal with and there's another, seemingly reasonable, solution at hand: check the "Run as administrator" box on the shortcut.
Thirty-seconds of investigation reveals that the WScript.Shell ActiveX Object does not have the interfaces required for this. Additional investigation suggests that IShellLinkDataList does. However, IShellLinkDataList is a generic COM Interface. I see several examples around the Internet, most linking here. However, all the examples do it in compiled code (C++, C#, even JScript.NET). I significantly prefer to be able to do it directly in JScript, running from cscript.exe.
That said, I'm all for ideas I didn't contemplate or other solutions.
The official way to mark a shortcut file as requiring elevation is via IShellLinkDataList. It's difficult to use that interface from an automation environment.
But, if you are happy with a hack, you can do it in script, just by flipping a bit in the .lnk file.
When you tick the "run as administrator" box in the Advanced tab of the Shell Properties box, or when you use IShellLinkDataList to set the flags to include SLDF_RUNAS_USER, you're basically just setting one bit in the file.
You can do that "manually" without going through the COM interface. It's byte 21, and you need to set the 0x20 bit on.
(function(globalScope) {
'use strict';
var fso = new ActiveXObject("Scripting.FileSystemObject"),
path = "c:\\path\\goes\\here\\Shortcut2.lnk",
shortPath = path.split('\\').pop(),
newPath = "new-" + shortPath;
function readAllBytes(path) {
var ts = fso.OpenTextFile(path, 1), a = [];
while (!ts.AtEndOfStream)
a.push(ts.Read(1).charCodeAt(0));
ts.Close();
return a;
}
function writeBytes(path, data) {
var ts = fso.CreateTextFile(path, true),
i=0, L = data.length;
for (; i<L; i++) {
ts.Write(String.fromCharCode(data[i]));
}
ts.Close();
}
function makeLnkRunAs(path, newPath) {
var a = readAllBytes(path);
a[0x15] |= 0x20; // flip the bit.
writeBytes(newPath, a);
}
makeLnkRunAs(path, newPath);
}(this));
ps:
function createShortcut(targetFolder, sourceFolder){
var shell = new ActiveXObject("WScript.Shell"),
shortcut = shell.CreateShortcut(targetFolder + "\\Run The Script.lnk"),
fso = new ActiveXObject("Scripting.FileSystemObject"),
windir = fso.GetSpecialFolder(specialFolders.windowsFolder);
shortcut.TargetPath = fso.BuildPath(windir,"system32\\cscript.exe");
shortcut.Arguments = "\"" + sourceFolder + "\\script.js\" /aParam /orTwo";
shortcut.IconLocation = sourceFolder + "\\icon.ico";
shortcut.Save();
}