harshini
harshini

Reputation: 553

Generating Output in JAVA

Can we generate an .html doc using java? Usually we get ouput in cmd prompt wen we run java programs. I want to generate output in the form of .html or .doc format is their a way to do it in java?

Upvotes: 4

Views: 46779

Answers (11)

RoToRa
RoToRa

Reputation: 38441

HTML is just plain text. Just write the HTML code to a file or standard out.

Word files are more complicated. Have a look at libraries such as Apache POI.

Upvotes: 2

Sergey Ushakov
Sergey Ushakov

Reputation: 2483

A very straightforward and reliable approach to creation of plain HTML may be based on a SAX handler and default XSLT transformer, the latter having intrinsic capability of HTML output:

String encoding = "UTF-8";
FileOutputStream fos = new FileOutputStream("myfile.html");
OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
StreamResult streamResult = new StreamResult(writer);

SAXTransformerFactory saxFactory =
    (SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler tHandler = saxFactory.newTransformerHandler();
tHandler.setResult(streamResult);

Transformer transformer = tHandler.getTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

writer.write("<!DOCTYPE html>\n");
writer.flush();
tHandler.startDocument();
    tHandler.startElement("", "", "html", new AttributesImpl());
        tHandler.startElement("", "", "head", new AttributesImpl());
            tHandler.startElement("", "", "title", new AttributesImpl());
                tHandler.characters("Hello".toCharArray(), 0, 5);
            tHandler.endElement("", "", "title");
        tHandler.endElement("", "", "head");
        tHandler.startElement("", "", "body", new AttributesImpl());
            tHandler.startElement("", "", "p", new AttributesImpl());
                tHandler.characters("5 > 3".toCharArray(), 0, 5); // note '>' character
            tHandler.endElement("", "", "p");
        tHandler.endElement("", "", "body");
    tHandler.endElement("", "", "html");
tHandler.endDocument();
writer.close();

Note that XSLT transformer will release you from the burden of escaping special characters like >, as it takes necessary care of it by itself.

And it is easy to wrap SAX methods like startElement() and characters() to something more convenient to one's taste...

And it may be worth noting that dealing without templates and document allocation in memory (e.g. DOM) gives you more freedom in terms of the resulting document size...

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240976

For HTML

Just write data into .html file (they are simply text files with .html extension), using raw file io operation

For Example :

    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    sb.append("<head>");
    sb.append("<title>Title Of the page");
    sb.append("</title>");
    sb.append("</head>");
    sb.append("<body> <b>Hello World</b>");
    sb.append("</body>");
    sb.append("</html>");
    FileWriter fstream = new FileWriter("MyHtml.html");
    BufferedWriter out = new BufferedWriter(fstream);
    out.write(sb.toString());
    out.close();

For word document

This thread answers it

Upvotes: 4

Miguel Gamboa
Miguel Gamboa

Reputation: 9393

I already felt that need in the past and I end up developing a java library--HtmlFlow (deployed at Maven Central Repository)--that provides a simple API to write HTML in a fluent style. Check it here: https://github.com/fmcarvalho/HtmlFlow.

You can use HtmlFlow with, or without, data binding, but here I present an example of binding the properties of a Task object into HTML elements. Consider a Task Java class with three properties: Title, Description and a Priority and then we can produce an HTML document for a Task object in the following way:

import htmlflow.HtmlView;

import model.Priority;
import model.Task;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class App {

    private static HtmlView<Task> taskDetailsView(){
        HtmlView<Task> taskView = new HtmlView<>();
        taskView
                .head()
                .title("Task Details")
                .linkCss("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css");
        taskView
                .body().classAttr("container")
                .heading(1, "Task Details")
                .hr()
                .div()
                .text("Title: ").text(Task::getTitle)
                .br()
                .text("Description: ").text(Task::getDescription)
                .br()
                .text("Priority: ").text(Task::getPriority);
        return taskView;
    }

    public static void main(String [] args) throws IOException{
        HtmlView<Task> taskView = taskDetailsView();
        Task task =  new Task("Special dinner", "Have dinner with someone!", Priority.Normal);

        try(PrintStream out = new PrintStream(new FileOutputStream("Task.html"))){
            taskView.setPrintStream(out).write(task);
            Runtime.getRuntime().exec("explorer Task.html");
        }
    }
}

Upvotes: 3

Jeff
Jeff

Reputation: 21902

HTML is simply plain text with a bunch of tags, as others have answered. My suggestion, if you are doing something that is more complex than just outputting a basic HTML snippet, is to use a template engine such as StringTemplate.

StringTemplate lets you create a text file (actually, a HTML file) that looks like this:

<html>
    <head>
       <title>Example</title>
    </head>
    <body>
       <p>Hello $name$</p>
   </body>
</html>

That is your template. Then in your Java code, you would fill in the $name$ placeholder like this and then output the resulting HTML page:

StringTemplate page = group.getInstanceOf("page");
page.setAttribute("name", "World");
System.out.println(page.toString());

This will print out the following result on your screen:

<html>
    <head>
       <title>Example</title>
    </head>
    <body>
       <p>Hello World</p>
   </body>
</html>

Of course, the above example Java code isn't the complete code, but it illustrates how to use a template that's still valid HTML (makes it easier to edit in a HTML editor) while keeping your Java code simple (by avoiding having a bunch of HTML tags in your System.out.println statements).

As for MS Office .doc format, that is more complex and you can look into Apache POI for that.

Upvotes: 3

Kojotak
Kojotak

Reputation: 2070

If you have some document-like data (structured), I'll suggest to use DOM (document object model) and than convert it in desired format (xml, html, doc, whatever). But if you have just some application output, you can easily wrap it with html. Not necessarily within java - you can also store your program's output in plain text file and convert it in html later (add body, paragprahs, headers and other HTML elements).

Upvotes: 0

ncmathsadist
ncmathsadist

Reputation: 4889

To generate an HTML document, you should write to a file. Since HTML is a text format, you would write to a text file. Doing this requires these classes

java.io.File - this represents locations in your file system

java.io.FileWriter - this establishes a connection from your program to a file

java.io.BufferedWriter -this enables buffered writing of text, which is much faster

java.io.IOException - one of these nasties is thrown if there is a problem writing to the file. It is a checked (vs. runtime) exception and you must handle it.

The Head First Java book contains a very nice coverage of these classes and show you how to use them. To use these you must first know about exception handling. That is also covered in Head First Java.

I hope this gets you started.

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114817

Sure.

The general approach: You create the document in memory, namely in a StringBuilder and write the content of that builder to a file.

StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.append("<html><body>");
htmlBuilder.append("Hello world!");
htmlBuilder.append("</body></html>\n");

FileWriter writer = new FileWriter(System.getProperty("user.home") + "/hello.html");
writer.write(htmlBuilder.toString());
writer.close();

Put this in a main method, execute and you'll find a html file in your home directory

Upvotes: 1

0x77D
0x77D

Reputation: 1574

Check this:

try {
    BufferedWriter out = new BufferedWriter(new FileWriter("outfilename.html"));
    out.write("aString"); //Here you pass your output
    out.close();
} catch (IOException e) {
}

You will need to import BufferedWriter, FileWriter and IOException, wich are under java.io

The "aString" should be a String variable that stores html code or doc xml

Upvotes: 1

Nanne
Nanne

Reputation: 64429

I don't know why you say this:

Usually we get ouput in cmd prompt wen we run java programs .

I've been running some java programs today, but they do not do anything with a cmd prompt. If you use system.out.println, yes, but most advanced programs have a little bit more for communciation. Like an interface :)

What you want to do is look into file handlers. Open (or create) a file, write content to that file, and close it. Then you have a file. You can write anything you want to that file, so obviously also something that would make it an HTML or a doc. It's easy to find howtos on file-writing

Upvotes: 1

VoteyDisciple
VoteyDisciple

Reputation: 37813

Output is just output. What it means and how you use it is entirely up to you.

If you System.out.println('<p>Hello world!</p>'); you just produced HTML.

The .doc format is obviously a bit trickier, since it's not a simple matter of putting in tags, but there are libraries to get the job done. Google can suggest more than a few.

Upvotes: 2

Related Questions