Link in swt browser to file inside jar file [duplicate] - html

I want to implement a help system for my tiny SWT desktop application.
I've thought about a SWT browser widget containing a single html markup page and a set of anchors to navigate (there are only very few things to explain).
Everything works fine, but how do I load the html file from a jar?
I know aboutgetClass().getClassLoader().getResourceAsStream("foo");, but what is the best practice when reading from the input stream? The answer to Load a resource contained in a jar dissuades using a FileInputStream.
Thanks in advance

Well, I found a rather simple solution that obviously just works:
InputStream in = getClass().getClassLoader().getResourceAsStream("html/index.html");
Scanner scanner = new Scanner(in);
StringBuffer buffer = new StringBuffer();
while(scanner.hasNextLine()) {
buffer.append(scanner.nextLine());
}
browser.setText(buffer.toString());

i tend to use commons-io for such a task giving me simple abstraction methods like IOUtils.toString(InputStream in); and leaving the choice of best implementations to the able people at apache ;)
commons-io: http://commons.apache.org/io/
apidocs: http://commons.apache.org/io/api-release/index.html

Related

What language to use?

What language should I use if i were to write a script to for example download every video from a specific youtube channel as a mp3 file via http://www.youtube-mp3.org/ ? This has been on my mind for a very long time and it would be nice if anyone could answer this question. I know it should be possible with html to use the tag and do some things with JS but i want a simpler and more reliable way. Thnx. PS. examples appreciated
you can easily use c# with webclient class
using (WebClient Client = new WebClient ())
{
Client.DownloadFile("http://google.com", "a.mpeg");
}

How to handle HTML content in Windows 8 Metro App

I'm designing a Windows 8 Reader App, and I have to use a control to show the HTML content, which is fetched from some website feeds. Cause those HTML content may contains images or some other formatted text, now I'm using a richtextblock to show the HTML content, but it costs a lot of time to parse the HTML content.
So I'm wondering if there is any controls that can handle the HTML content except the WebView.
Thanks.
Updated:
The reason I can't use WebView is that I need to implement pagination, like the image belowed:
As JP Alioto mentioned you should use the WebView control.
You can use the NavigateToString method to load the HTML. Or use Navigate to request a URI.
There are issues however with using the WebView control, specifically it is rendered differently and is not a standard control, this means things like your app bar or settings pane will not render on top of the WebView, there is a workaround by using the WebViewBrush to "paint" the WebView to standard control such as a rectangle when needed.
Also you can make a screenshot of the webpage you want to display. But to make a screenshot of webpage it's also not easy to do, but I offer you to make it with some special sites wich are created to take screenshot of other websites. Then you can download an image this sites return and open and display it in your windows 8 app. I show You some example how to I did that:
StorageFolder screens = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFolderAsync(#"Screens\" + folderName, CreationCollisionOption.GenerateUniqueName);
var downloader = new BackgroundDownloader();
IStorageFile file = await screens.CreateFileAsync(fname, CreationCollisionOption.GenerateUniqueName);
string my_uri = "http://api.snapito.com/web/e3c351d5994134eb1aea855ce78e296c3292d48a/lc/" + url + "?type=jpeg";
DownloadOperation download = downloader.CreateDownload(new System.Uri(my_uri), file);
await download.StartAsync();
I think there are only two options but none of them are really good:
Use WebView and transform your HTML with CSS and other techniques to look native. Use the ScriptNotify and NavigationStarting and other events to navigate to another page. In W8.1 the WebView is much better (eg. treated as regular control not floating over all other controls,...)
Parse your HTML and generate native elements. I started such an implementation and created a XAML control to display HTML with native controls (see https://mytoolkit.codeplex.com/wikipage?title=HtmlTextBlock). However if you have complex HTML (eg iframes, etc.) this may not work and you have no other choice than to use the WebView control.

Open generated Web Page with WebBrowser object in VB

I'd like to know if it possible to show HTML page created in VB using WebBrowser object without using files on disk.
That is, create HTML file in memory and show it within WebBrowser object.
Thanks!
Using Visual Basic in .Net Framework...
webBrowser1.DocumentText = "<html><body><a href='http://www.mywebsite.com'>My Web Site</a></body></html>"
In old Visual Basic 6, try...
WebBrowser1.Document.Open
WebBrowser1.Document.Write "<html><body><a href='http://www.mywebsite.com'>My Web Site</a></body></html>"
WebBrowser1.Document.Close
First wait for the DocumentComplete event (navigate to about:blank if you start from scratch), then use the document's IPersistMoniker (recommended if you want to provide a base url) or IPersistStreamInit interface to load HTML content.
You can find an example (the LoadHtmlIntoBrowser method) in the csexwb project.
Well, I've found the solution. It's not so complicated.
The solution is to run from the VB:
*
WebBrowserObject.Navigate "about:HTML TEXT"
It works, I've checked it.

ASP.NET MVC: render view to generate PDF: use iTextSharp or better solution?

I display receipt in both HTML and printer-friendly version. HTML version does jQuery tabs, etc, while printer-friendly has zero scripts and external dependencies, no master layout, no additional buttons, inline CSS, and can be saved as HTML without problems.
Since I use Spark View Engine, I though maybe it's a good idea to generate PDF using iTextSharp engine. But after few paragraphs I decided it's too cumbersome, because a) I would have to rewrite entire receipt (source Spark view is about 5 pages long) b) I had problems with iTextSharp from beginning - for example, numbered lists kept bulleted, with no indentation, and indentationLeft="20" didn't work - maybe because of lack of documentation, but see (a).
So, my requirements for PDF are very simple: I want to keep the same HTML but insert page breaks between individual receipts (yes I have several ones in a single document).
Is there a simple way to generate PDF from view/HTML without rewriting the view using a strange half-documented engine?
UPDATE: tried community HTMLDoc version; didn't use my inline CSS styles, incorrectly displayed Unicode symbols for currencies. wkhtmltopdf did pick the CSS but failed for currency symbol; I suppose there's problem with encoding solved by setting charset to utf-8. wkhtmltopdf seems to be nice but I'm yet to figure out how to set page breaks...
If you can have the HTML in memory then you can convert it to PDF. I've once did something similar using xhtmlrenderer. It is a JAVA framework that bundles iText and that is capable of converting an HTML stream into PDF. As it is written in JAVA I've used the ikvmc.exe to convert the jar file into a .NET assembly and use it directly from managed code.
public class Pdf : IPdf
{
public FileStreamResult Make(string s)
{
using (var ms = new MemoryStream())
{
using (var document = new Document())
{
PdfWriter.GetInstance(document, ms);
document.Open();
using (var str = new StringReader(s))
{
var htmlWorker = new HTMLWorker(document);
htmlWorker.Parse(str);
}
document.Close();
}
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=MyPdfName.pdf");
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
HttpContext.Current.Response.OutputStream.Flush();
HttpContext.Current.Response.End();
return new FileStreamResult(HttpContext.Current.Response.OutputStream, "application/pdf");
}
}
}
Finally used wkhtmltopdf which works fine when I set encoding, I found out how to setup page breaks, and it processes my CSS very nice. On issue is that it can't correctly process stdin/out in Windows version (don't remember if it's in or out that doesn't work) - may be fixed in recent versions, but I'm ok with temp files.

Using iText to convert HTML to PDF

Does anyone know if it is possible to convert a HTML page (url) to a PDF using iText?
If the answer is 'no' than that is OK as well since I will stop wasting my time trying to work it out and just spend some money on one of a number of components which I know can :)
I think this is exactly what you were looking for
http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
http://code.google.com/p/flying-saucer
Flying Saucer's primary purpose is to render spec-compliant XHTML and CSS 2.1 to the screen as a Swing component. Though it was originally intended for embedding markup into desktop applications (things like the iTunes Music Store), Flying Saucer has been extended work with iText as well. This makes it very easy to render XHTML to PDFs, as well as to images and to the screen. Flying Saucer requires Java 1.4 or higher.
I have ended up using ABCPdf from webSupergoo.
It works really well and for about $350 it has saved me hours and hours based on your comments above.
The easiest way of doing this is using pdfHTML.
It's an iText7 add-on that converts HTML5 (+CSS3) into pdf syntax.
The code is pretty straightforward:
HtmlConverter.convertToPdf(
"<b>This text should be written in bold.</b>", // html to be converted
new PdfWriter(
new File("C://users/mark/documents/output.pdf") // destination file
)
);
To learn more, go to http://itextpdf.com/itext7/pdfHTML
The answer to your question is actually two-fold. First of all you need to specify what you intend to do with the rendered HTML: save it to a new PDF file, or use it within another rendering context (i.e. add it to some other document you are generating).
The former is relatively easily accomplished using the Flying Saucer framework, which can be found here: https://github.com/flyingsaucerproject/flyingsaucer
The latter is actually a much more comprehensive problem that needs to be categorized further.
Using iText you won't be able to (trivially, at least) combine iText elements (i.e. Paragraph, Phrase, Chunk and so on) with the generated HTML. You can hack your way out of this by using the ContentByte's addTemplate method and generating the HTML to this template.
If you on the other hand want to stamp the generated HTML with something like watermarks, dates or the like, you can do this using iText.
So bottom line: You can't trivially integrate the rendered HTML in other pdf generating contexts, but you can render HTML directly to a blank PDF document.
Use itext libray:
Here is the sample code. It is working perfectly fine:
String htmlFilePath = filePath + ".html";
String pdfFilePath = filePath + ".pdf";
// create an html file on given file path
Writer unicodeFileWriter = new OutputStreamWriter(new FileOutputStream(htmlFilePath), "UTF-8");
unicodeFileWriter.write(document.toString());
unicodeFileWriter.close();
ConverterProperties properties = new ConverterProperties();
properties.setCharset("UTF-8");
if (url.contains(".kr") || url.contains(".tw") || url.contains(".cn") || url.contains(".jp")) {
properties.setFontProvider(new DefaultFontProvider(false, false, true));
}
// convert the html file to pdf file.
HtmlConverter.convertToPdf(new File(htmlFilePath), new File(pdfFilePath), properties);
Maven dependencies
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.6</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>2.1.3</version>
</dependency>
Use iText's HTMLWorker
Example
When I needed HTML to PDF conversion earlier this year, I tried the trial of Winnovative HTML to PDF converter (I think ExpertPDF is the same product, too). It worked great so we bought a license at that company. I don't go into it too in depth after that.