UPDATE2: I got it working completely now! Scroll way down to find out how...
UPDATE: I got it working! Well... partially. Scroll down for the answer...
I'm trying to get my FO file to show an external image upon transforming it to PDF (or RTF for that matter, but I'm not sure whether RTFs are even capable of displaying images (they are)) with FOP, but I can't seem to get it working. (The question asked here is different than mine.)
I am using IKVM 0.46.0.1 and have compiled a FOP 1.0 dll to put in .NET; this code worked fine when I didn't try to add images:
private void convertFoByMimetype(java.io.File fo, java.io.File outfile, string mimetype)
{
OutputStream output = null;
try
{
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
// configure foUserAgent as desired
// Setup outputput stream. Note: Using BufferedOutputStream
// for performance reasons (helpful with FileOutputStreams).
output = new FileOutputStream(outfile);
output = new BufferedOutputStream(output);
// Construct fop with desired output format
Fop fop = fopFactory.newFop(mimetype, foUserAgent, output);
// Setup JAXP using identity transformer
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); // identity transformer
// Setup input stream
Source src = new StreamSource(fo);
// Resulting SAX events (the generated FO) must be piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
// Start XSLT transformation and FOP processing
transformer.transform(src, res);
}
catch (Exception ex)
...
}
However, when I (or rather a DocBook2FO transformation) added the following code:
<fo:external-graphic src="url(images/interface.png)" width="auto" height="auto" content-width="auto" content-height="auto" content-type="content-type:image/png"></fo:external-graphic>
into the FO file, the image did not show. I read through a bit of the FAQ on Apache's site, which says:
3.3. Why is my graphic not rendered?
Most commonly, the external file is not being found by FOP. Check the
following:
Empty or wrong baseDir setting.
Spelling errors in the file name (including using the wrong case).
...
Other options did not seem to be my case (mainly for the reason below - "The Weird Part"). I tried this:
...
try
{
fopFactory.setBaseURL(fo.getParent());
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
foUserAgent.setBaseURL(fo.getParent());
FOURIResolver fourir = fopFactory.getFOURIResolver();
foUserAgent.setURIResolver(fourir);
// configure foUserAgent as desired
...
with no avail.
The Weird Part
When I use the command-line implementation of FOP, it works fine and displays my image with no problem. (I don't want to go the run-command-line-from-program route, because I don't want to force the users to install Java AND the .NET framework when they want to use my program.)
The png file is generated from GDI+ from within my application (using Bitmap.Save). I also tried different png files, but none of them worked for me.
Is there anything I might be missing?
Thanks a bunch for getting this far
UPDATE and possible answer
So I might have figured out why it didn't work. I put some time into studying the code (before I basically just copypasted it without thinking about it much). The problem is indeed in the wrong basedir setting.
The key is in this chunk of code:
// Setup JAXP using identity transformer
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); // identity transformer
// Setup input stream
Source src = new StreamSource(fo);
// Resulting SAX events (the generated FO) must be piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
// Start XSLT transformation and FOP processing
transformer.transform(src, res);
What happens here is an identity transformation, which routes its own result into an instance of FOP I've created before. This effectively changes the basedir of the routed FO into that of the application's executable. I have yet to figure out how to do this without a transformation and route my input directly into FOP, but for the moment I worked around this by copying my images into the executable's directory.
Which is where another problem came in. Now whenever I try to execute the code, I get an exception at the line that says transformer.transform(src, res);, which confuses the pants out of me, because it doesn't say anything. The ExceptionHelper says:
java.lang.ExceptionInInitializerError was caught
and there is no inner exception or exception message. I know this is hard to debug just from what I wrote, but I'm hoping there might be an easy fix.
Also, this e-mail seems vaguely related but there is no answer to it.
UPDATE2
Finally, after a few sleepless nights, I managed to get it working with one of the simplest ways possible.
I updated IKVM, compiled fop with the new version and replaced the IKVM references with the new dlls. The error no longer occurs and my image renders fine.
I hope this helps someone someday
I'm using very similar code, although without the FOUserAgent, Resolvers, etc. and it works perfectly.
Did you try setting the src attribute in the XSLT without the url() function?
What might help you diagnose the problem further are the following statements:
java.lang.System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog")
java.lang.System.setErr(New java.io.PrintStream(New TraceStream(TraceStream.Level.Error)))
java.lang.System.setOut(New java.io.PrintStream(New TraceStream(TraceStream.Level.Info)))
Where TraceStream is a .NET implementation of a java.io.OutputStream which writes to your favorite logger.
I posted a version for the Common.Logging package at http://pastebin.com/XH1Wg7jn.
Here's a post not to leave the question unanswered, see "Update 1" and "Update 2" in the original post for the solution.
Related
Recently, my application has crashed when trying to display a rather lengthy (but otherwise simple) HTML e-mail.
The crash was caused by mshtml.dll getting a stack overflow (exception code 0xc00000fd). Of note here is that this didn't throw an exception but it actually just crashed the program as a whole. The error was retrieved from the Windows event log.
In the process of debugging, I created a smaller sample solution to try and narrow down the issue. However, not only does it work fine in the sample solution, it behaves completely different from the main program despite running the same code even for the simplest of HTML strings.
The code is as follows:
var webBrowser1 = new System.Windows.Forms.WebBrowser();
webBrowser1.AllowNavigation = false;
webBrowser1.AllowWebBrowserDrop = false;
webBrowser1.Navigate("about:blank");
var doc = webBrowser1.Document.OpenNew(true);
doc.Write("<HTML><BODY>This is a new HTML document.</BODY></HTML>");
var count = doc.All.Count;
var html = doc.All[0].OuterHtml;
In the sample solution this evaluates to:
count = 4; // [HTML, HEAD, TITLE, BODY]
html = "<HTML><HEAD></HEAD>\r\n<BODY>This is a new HTML document.</BODY></HTML>";
Meanwhile in the main program it comes out to:
count = 3; // [HTML, HEAD, BODY]
html = "<html><head></head><body>This is a new HTML document.</body></html>";
These are small discrepancies but that is largely due to the simple HTML used. The one that causes the crash has rather significant differences.
I am absolutely stumped as to how the result can be so vastly different.
The documentation for HtmlDocument.Write(string) states that:
It is recommended that you write an entire valid HTML document using the Write method, including HTML and BODY tags. However, if you write just HTML elements, the Document Object Model (DOM) will supply these elements for you.
But I have no idea how the DomDocument is provided nor why they would be different in the first place. Both solutions are running in x64 Debug mode and Net-Framework 4.6.2.
Both load the module: C:\WINDOWS\assembly\GAC\Microsoft.mshtml\7.0.3300.0__b03f5f7f11d50a3a\Microsoft.mshtml.dll
How is it possible that these produce different results?!
Any and all help welcome.
Thanks in advance.
The difference in behavior stems from the registry entry as proposed by Jimi and linked here
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
To reiterate, in the above registry the main program had an entry "ApplicationFileName.exe"=dword:00002af9 while my new test-application didn't.
This, in and for itself, does not explain the crashing of mshtml.dll itself but since the question was about the difference in behavior I'll post this as the answer. The crash is most likely linked to the outdated version used by Visual Studio but I haven't yet had the chance to look into some of the proposed fixes for that.
My basic problem was converting a .docx file to .pdf. The problem would be solved incase I was allowed to use Microsoft.Office.Interop.Word.dll, which i am not since the server will not have MS Office installed. So I needed a free/open-source library that would allow me to do so. And i came across docx4j.NET.
http://www.docx4java.org/blog/2014/09/docx-to-pdf-in-c-net/
This worked fine as long as I ran it as a Console App. The following is the concerned code snippet:
string fileIN = #"C:\Users\...\Visual Studio 2013\Projects\HRDapp\HRDapp\Letter_Templates\AP.docx";
string fileOUT = #"C:\Users\...\Visual Studio 2013\Projects\HRDapp\HRDapp\Letter_Templates\AP.pdf";
log.Info("Hello from Common Logging");
// Necessary, if slf4j-api and slf4j-NetCommonLogging are separate DLLs
ikvm.runtime.Startup.addBootClassPathAssembly(
System.Reflection.Assembly.GetAssembly(
typeof(org.slf4j.impl.StaticLoggerBinder)));
// Configure to find docx4j.properties
// .. add as URL the dir containing docx4j.properties (not the file itself!)
Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + #"src\samples\resources\");
java.io.File file = new java.io.File(fileIN);
// OK, do it..
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file);
java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(fileOUT));
org.docx4j.Docx4J.toPDF(wordMLPackage, fos);
fos.close();
In case of using this in a Web App, the code runs fine till
java.io.File file = new java.io.File(fileIN);
and gets stuck at
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file);
Although the file path is correct and works fine in the console app, but there seems something else that I am missing here. The log also prints upto the following statement-
iisexpress.exe Information: 0 : [INFO] org.docx4j.jaxb.Context - Using Java 6/7 JAXB implementation
.. and stops. Any kind of reply directing me to the source of the error will be very helpful. Thanks.
As Jeroen (of IKVM fame) has explained, when there is no main assembly (eg in an ASP.NET application), the IKVM class loader can't find your assembly when the code is trying to dynamically load a class.
So you'll want to add not just:
ikvm.runtime.Startup.addBootClassPathAssembly(
System.Reflection.Assembly.GetAssembly(
typeof(org.slf4j.impl.StaticLoggerBinder)));
but also:
ikvm.runtime.Startup.addBootClassPathAssembly(
System.Reflection.Assembly.GetAssembly(
typeof(org.slf4j.LoggerFactory)));
ikvm.runtime.Startup.addBootClassPathAssembly(
System.Reflection.Assembly.GetAssembly(
typeof(org.docx4j.jaxb.Context)));
I am writing a Notepad++ plugin, and need to create a new tab, for a new file. I haven't been able to find anything covering this in the documentation.
The closest I have come is:
IntPtr curScintilla = PluginBase.GetCurrentScintilla();
IntPtr documentPtr = Win32.SendMessage(curScintilla, SciMsg.SCI_CREATEDOCUMENT, 1, 1);
Win32.SendMessage(curScintilla, SciMsg.SCI_SETDOCPOINTER, 0, documentPtr);
but this acts in the current tab (I think it's creating a new document and pointing the current tab at that).
I was reading the "Multiple views" section of http://www.scintilla.org/ScintillaDoc.html but am unable to get any further than the above. I don't normally work in C# or even Windows, so I might be missing something obvious. I tried looking at existing plugins for examples but most of them seem to be written in C++, rather than C#.
Any guidance appreciated.
Thanks.
I have not gone through scintilla. But I used simple approach. I used this for creating, you may need to look for more information for sending the message.
Create file if it doesn't exist in the directory before you start. Else it will ask for user confirmation.
Arguments for the process should differ from the first and next tabs:
File.Create(yourNewFile); //or yourNextNewFile in case of second, third, so on..
Process notepadPlus = new Process();
notepadPlus.StartInfo.FileName = "notepad++.exe";
For the first file use as (new instance with new session - without any old tabs):
notepadPlus.StartInfo.Arguments = #"-multiInst -nosession yourNewFile";
For next files use as (only new tabs will be created):
notepadPlus.StartInfo.Arguments = #"yourNextNewFile";
/* Start the process */
notepadPlus.Start();
You have to send a message not to the Scintilla control, but to Notepad itself.
Like this:
Win32.SendMessage(PluginBase.nppData._nppHandle, NppMsg.NPPM_MENUCOMMAND, 0, NppMenuCmd.IDM_FILE_NEW);
More informations here including the used constants.
I'm trying to do some simple DOM manipulation when a page is rendered as a PDF using ABCPdf. I followed what they document here: http://www.websupergoo.com/helppdf9net/source/5-abcpdf/xhtmloptions/2-properties/usescript.htm
But when I try something as simple as the following:
var doc = new Doc();
doc.HtmlOptions.UseScript = true;
doc.HtmlOptions.UseNoCache = true;
doc.HtmlOptions.PageCachePurge();
doc.HtmlOptions.OnLoadScript = #"var reportElms = document.getElementsByClassName(""report"");";
doc.Page = doc.AddPage();
doc.AddImageUrl(Url.Action("TestPdf", "Pdf", new { }, "http"));
I get the exception:
Unable to render HTML. Unable to apply JScript.
COM error 80020101.
Script 'var reportElms = document.getElementsByClassName("report");'.
Any thoughts as to what I'm doing wrong?
Not even the built in functions work
I'm even getting the same exception with the following script:
doc.HtmlOptions.OnLoadScript = #"
window.ABCpdf_RenderWait();
window.ABCpdf_RenderComplete();";
Btw, I'm using version 8 because that's what we have a licence for.
Edit:
I was missing the .external for the ABCpdf_RenderWait() and ABCpdf_RenderComplete() calls. It works if you reference them properly (imagine that):
doc.HtmlOptions.OnLoadScript = #"
window.external.ABCpdf_RenderWait();
window.external.ABCpdf_RenderComplete();";
Though as I mention in my answer, there are a lot of security hoops that need to be jumped through for IE also.
So I didn't actually get the IE engine to execute JavaScript the way I wanted but I was able to find a solution using the Gecko engine. The original NuGet install did not include the Gecko DLL, so I just downloaded the standalone install and added the DLLs manually.
After that everything worked exactly as expected.
I believe that the IE engine didn't work because it requires a lot of security configuration, because the FAQs spend a lot of time discussing debugging of security: http://www.websupergoo.com/support.htm#6.7
Back in .NET 1.0 days I wrote a method to return the target of a shortcut on MS Windows. It did this through using an interop to the Windows Script Hosting Object Model and brute forced through the COM interface:
private FileInfo GetFileFromShortcut(FileInfo shortcut)
{
FileInfo targetFile = null;
try
{
IWshRuntimeLibrary.WshShell wShell = new IWshRuntimeLibrary.WshShellClass();
IWshRuntimeLibrary.WshShortcut wShortcut = (IWshRuntimeLibrary.WshShortcut)wShell.CreateShortcut(shortcut.FullName);
// if the file wasn't a shortcut then the TargetPath comes back empty
string targetName = wShortcut.TargetPath;
if (targetName.Length > 0)
{
targetFile = new FileInfo(targetName);
}
}
catch (Exception)
{ // will return a null targetFile if anything goes wrong
}
return targetFile;
}
This still bugs me, and I was looking to replace this with something more elegant, but only if the replacement actually works at least as well. I still can't find a native C# way of finding the target of a shortcut. Is there one, or is this still the best way of doing this type of thing?
It looks like someone has written a class to manipulate shortcut files in C# called ShellLink, but it too uses COM.
Can't you just open the .lnk or .url file and parse it?
This talks about the same thing and shows what the files look like:
http://www.programmingtalk.com/showthread.php?t=7335
I got interested in this as well a while ago.
Here is the accepted response with a link to a (informal) description of the format of LNK files. Apparently, all available methods yet go through some API.