Apache POI - formatting output to HTML - html

I am writing to an Excel file using Apache POI, but I want my output to be formatted as HTML not as literal text.
SXSSFWorkbook workbook = new SXSSFWorkbook();
Sheet sheet0 = workbook.createSheet("sheet0");
Row row0 = sheet0.createRow(2);
Cell cell0 = row0.createCell(2);
cell0.setCellValue("<html><b>blah blah blah</b></html>");
What appears when I open the Excel file is:
"<html><b>blah blah blah</b></html>"
but I want:
"blah blah blah"
essentially I am looking for a piece of code along the lines of:
cell0.setCellFormat(CellFormat.HTML);
Except, that doesn't exist.
here is some info on this topic
http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/ss/examples/html/ToHtml.java
I will try this for now:
public void printPage() throws IOException {
try {
ensureOut();
if (completeHTML) {
out.format(
"<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>%n");
out.format("<html>%n");
out.format("<head>%n");
out.format("</head>%n");
out.format("<body>%n");
}
print();
if (completeHTML) {
out.format("</body>%n");
out.format("</html>%n");
}
} finally {
if (out != null)
out.close();
if (output instanceof Closeable) {
Closeable closeable = (Closeable) output;
closeable.close();
}
}
}

Based on my version for DocX, here is the adapted version for Hssf. As with the other version, you'll have to debug and extend the loop for the various css styles.
Update: I've overlooked yesterday, that you wanted to have a streaming XSSF solution, so I fiddled around, if it's possible to just use the usermodel classes (not really, when it comes to font colors), furthermore I wondered why SXSSF didn't use any of my font setting until I found out, that's currently by design (see Bug 52484)
import java.awt.Color;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.Enumeration;
import javax.swing.text.*;
import javax.swing.text.html.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class StyledTextXls {
public static void main(String[] args) throws Exception {
HTMLEditorKit kit = new HTMLEditorKit();
HTMLDocument doc = (HTMLDocument)kit.createDefaultDocument();
kit.insertHTML(doc, doc.getLength(), "<p>paragraph <b>1</b></p>", 0, 0, null);
kit.insertHTML(doc, doc.getLength(), "<p>paragraph <span style=\"color:red\">2</span></p>", 0, 0, null);
Workbook wb = new XSSFWorkbook();
// Workbook wb = new HSSFWorkbook();
// Workbook wb = new SXSSFWorkbook(100); // doesn't work yet - see Bug 52484
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
StringBuffer sb = new StringBuffer();
for (int lines=0, lastPos=-1; lastPos < doc.getLength(); lines++) {
if (lines > 0) sb.append("\n");
Element line = doc.getParagraphElement(lastPos+1);
lastPos = line.getEndOffset();
for (int elIdx=0; elIdx < line.getElementCount(); elIdx++) {
final Element frag = line.getElement(elIdx);
String subtext = doc.getText(frag.getStartOffset(), frag.getEndOffset()-frag.getStartOffset());
sb.append(subtext);
}
}
CreationHelper ch = wb.getCreationHelper();
RichTextString rt = ch.createRichTextString(sb.toString());
for (int lines=0, lastPos=-1; lastPos < doc.getLength(); lines++) {
Element line = doc.getParagraphElement(lastPos+1);
lastPos = line.getEndOffset();
for (int elIdx=0; elIdx < line.getElementCount(); elIdx++) {
final Element frag = line.getElement(elIdx);
Font font = getFontFromFragment(wb, frag);
rt.applyFont(frag.getStartOffset()+lines, frag.getEndOffset()+lines, font);
}
}
cell.setCellValue(rt);
cell.getCellStyle().setWrapText(true);
row.setHeightInPoints((6*sheet.getDefaultRowHeightInPoints()));
sheet.autoSizeColumn((short)0);
FileOutputStream fos = new FileOutputStream("richtext"+(wb instanceof HSSFWorkbook ? ".xls" : ".xlsx"));
wb.write(fos);
fos.close();
}
static Font getFontFromFragment(Workbook wb, Element frag) {
// creating a font on each is call is not very efficient
// but should be ok for this exercise ...
Font font = wb.createFont();
final AttributeSet as = frag.getAttributes();
final Enumeration<?> ae = as.getAttributeNames();
while (ae.hasMoreElements()) {
final Object attrib = ae.nextElement();
try {
if (CSS.Attribute.COLOR.equals(attrib)) {
// I don't know how to really work with the CSS-swing class ...
Field f = as.getAttribute(attrib).getClass().getDeclaredField("c");
f.setAccessible(true);
Color c = (Color)f.get(as.getAttribute(attrib));
if (font instanceof XSSFFont) {
((XSSFFont)font).setColor(new XSSFColor(c));
} else if (font instanceof HSSFFont && wb instanceof HSSFWorkbook) {
HSSFPalette pal = ((HSSFWorkbook)wb).getCustomPalette();
HSSFColor col = pal.findSimilarColor(c.getRed(), c.getGreen(), c.getBlue());
((HSSFFont)font).setColor(col.getIndex());
}
} else if (CSS.Attribute.FONT_WEIGHT.equals(attrib)) {
if ("bold".equals(as.getAttribute(attrib).toString())) {
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
}
}
} catch (Exception e) {
System.out.println(attrib.getClass().getCanonicalName()+" can't be handled.");
}
}
return font;
}
}

Related

BarabasiAlbertGenerator implementation

I wanted to implement BarabasiAlbertGenerator to generate graph. After creating all Factory objects in main method and changing the Objects (V, E) to (Integer, String) in the generator class, two errors worried me after making all possible modification.
1. index_vertex.put(v, i); type mismatch
2. index_vertex.put(newVertex, new Integer(vertex_index.size() - 1));// an Object of Integer cannot be instantiated. I made several casting the errors still appear. Please any help on how to correct the errors.
public class BarabasiAlbertGenerator<Integer, String> implements EvolvingGraphGenerator<Integer, String> {
mGraph = graphFactory.create();
vertex_index = new ArrayList<Integer>(2*init_vertices);
index_vertex = new HashMap<Integer, Integer>(2*init_vertices);
for (int i = 0; i < init_vertices; i++) {
Integer v = vertexFactory.create();
mGraph.addVertex(v);
vertex_index.add(v);
index_vertex.put(v, i);
seedVertices.add(v);
}
mElapsedTimeSteps = 0;
}
for (Pair<Integer> pair : added_pairs)
{
Integer v1 = pair.getFirst();
Integer v2 = pair.getSecond();
if (mGraph.getDefaultEdgeType() != EdgeType.UNDIRECTED ||
!mGraph.isNeighbor(v1, v2))
mGraph.addEdge(edgeFactory.create(), pair);
}
// now that we're done attaching edges to this new vertex,
// add it to the index
vertex_index.add(newVertex);
index_vertex.put(newVertex, new Integer(vertex_index.size() - 1));
}
public static void main(String[] args) {
SparseGraph<Integer, String> sir = new SparseGraph<Integer, String>();
ConstantFactory<Graph<Integer, String>> graphFactory = new ConstantFactory<Graph<Integer, String>>(sir);
InstantiateFactory<Integer> vertexFactory = new InstantiateFactory<Integer>(Integer.class);
InstantiateFactory<String> edgeFactory = new InstantiateFactory<String>(String.class);
HashSet<Integer> seedVertices = new HashSet<Integer>();
int evolve = 1;
int node = 10;
int agents = 100;
BarabasiAlbertGenerator<Integer, String> bbr = new BarabasiAlbertGenerator<Integer, String>(graphFactory, vertexFactory, edgeFactory, agents, node, seedVertices);
bbr.evolveGraph(evolve);
Layout<Integer, String> layout = new CircleLayout(sir);
layout.setSize(new Dimension(300,300));
BasicVisualizationServer<Integer,String> vv =
new BasicVisualizationServer<Integer,String>(layout);
vv.setPreferredSize(new Dimension(350,350));
// Setup up a new vertex to paint transformer...
Transformer<Integer,Paint> vertexPaint = new Transformer<Integer,Paint>() {
public Paint transform(Integer i) {
return Color.GREEN;
}
};
// Set up a new stroke Transformer for the edges
float dash[] = {10.0f};
final Stroke edgeStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
Transformer<String, Stroke> edgeStrokeTransformer =
new Transformer<String, Stroke>() {
public Stroke transform(String s) {
return edgeStroke;
}
};
vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer);
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
//vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
JFrame frame = new JFrame("Undirected Graph ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
frame.pack();
frame.setVisible(true);
}
I don't think you want to use InstantiateFactory.
I was able to run your program after changing it to look like this (mostly the vertex and edge factories):
public static void main(String[] args) {
SparseGraph<Integer, String> sir = new SparseGraph<Integer, String>();
ConstantFactory<Graph<Integer, String>> graphFactory = new ConstantFactory<Graph<Integer, String>>(sir);
Factory<Integer> vertexFactory = new Factory<Integer>() {
int i = 0;
public Integer create() {
return i++;
}
};
Factory<String> edgeFactory = new Factory<String>() {
int i = 0;
public String create() {
return "" + i++;
}
};
HashSet<Integer> seedVertices = new HashSet<Integer>();
int evolve = 1;
int node = 10;
int agents = 100;
BarabasiAlbertGenerator<Integer, String> bbr = new BarabasiAlbertGenerator<Integer, String>(graphFactory, vertexFactory, edgeFactory, agents, node, seedVertices);
bbr.evolveGraph(evolve);
Layout<Integer, String> layout = new CircleLayout(sir);
layout.setSize(new Dimension(300, 300));
BasicVisualizationServer<Integer, String> vv =
new BasicVisualizationServer<Integer, String>(layout);
vv.setPreferredSize(new Dimension(350, 350));
// Setup up a new vertex to paint transformer...
Transformer<Integer, Paint> vertexPaint = new Transformer<Integer, Paint>() {
public Paint transform(Integer i) {
return Color.GREEN;
}
};
// Set up a new stroke Transformer for the edges
float dash[] = {10.0f};
final Stroke edgeStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
Transformer<String, Stroke> edgeStrokeTransformer =
new Transformer<String, Stroke>() {
public Stroke transform(String s) {
return edgeStroke;
}
};
vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer);
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
//vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
JFrame frame = new JFrame("Undirected Graph ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
frame.pack();
frame.setVisible(true);
}
Make sure your imports are correct. I used these:
import edu.uci.ics.jung.algorithms.generators.random.BarabasiAlbertGenerator;
import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseGraph;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.renderers.Renderer;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.Transformer;
import org.apache.commons.collections15.functors.ConstantFactory;
import javax.swing.*;
import java.awt.*;
import java.util.HashSet;

Images don't display in PDF

I have a fairly simple HTML page rendered via asp.net. It looks beautiful in the PDF after running it through HtmlRenderer.PdfSharp EXCEPT that the images don't appear. Just the red X of a missing image in the PDF even though the web page itself does display the image correctly.
Here is my HtmlRenderer.PdfSharp code:
public void BuildPDF( string url, string pdfPath ) {
string html = GetHTML(url);
Byte[] res = null;
using( MemoryStream ms = new MemoryStream() ) {
using( FileStream file = new FileStream(pdfPath, FileMode.Create, FileAccess.Write) ) {
byte[] bytes = new byte[ms.Length];
var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
pdf.Save(ms);
res = ms.ToArray();
file.Write(res, 0, res.Length);
ms.Close();
}
}
}
private string GetHTML(string url) {
string html = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using( HttpWebResponse response = (HttpWebResponse)request.GetResponse() )
using( Stream stream = response.GetResponseStream() )
using( StreamReader reader = new StreamReader(stream) ) {
html = reader.ReadToEnd();
}
return html;
}
And here is the img HTML that doesn't render in the PDF: <img src="images/ChartImg.png" />
How can I solve this?
Use the absolute path to the images.
<img src="http://example.org/images/ChartImg.png" />
You can parse the html and do a string replace first before passing it to the pdf converter.
The Code below:
var pdf = PdfGenerator.GeneratePdf(Html, PageSize.A4, 20, null, OnStylesheetLoad, OnImageLoadPdfSharp);
... ...
public static void OnImageLoadPdfSharp(object sender, HtmlImageLoadEventArgs e)
{
var url = e.Src;
if (!e.Src.StartsWith("http://") && !e.Src.StartsWith("https://"))
{
var ImgFilePath = System.Web.HttpContext.Current.Server.MapPath(url);
if (XImage.ExistsFile(ImgFilePath))
e.Callback(XImage.FromFile(ImgFilePath));
var ImgFilePath2 = System.Web.HttpContext.Current.Server.MapPath(url);
if (XImage.ExistsFile(ImgFilePath2))
e.Callback(XImage.FromFile(ImgFilePath2));
}
else
{
using (var client = new WebClient())
{
using (var stream = new MemoryStream(client.DownloadData(url)))
{
e.Callback(XImage.FromStream(stream));
}
}
}
}
It's better to use the image resolution callback for this for this:
var pdf = PdfGenerator.GeneratePdf(html, pdfConfig, imageLoad: OnImageLoad);
// snip
private void OnImageLoad(object sender, HtmlImageLoadEventArgs e)
{
using (var client = new WebClient())
{
var url = e.Src;
if (!e.Src.StartsWith("http://") && !e.Src.StartsWith("https://"))
{
url = Properties.Settings.Default.BaseUrl.TrimEnd('/') + e.Src;
}
using (var stream = new MemoryStream(client.DownloadData(url)))
{
e.Callback(XImage.FromStream(stream));
}
}
}
I'm late for your problem but maybe this will help someone else.
I used absolute urls and they were correct. Images were loaded correctly when I opened html file in browser.
However, they were not loaded after I converted this html to pdf. So I tried to use image resolution callback like #ohjo suggested. An exception occured here: An existing connection was forcibly closed by the remote host.
I was able to solve this but adding one more line that sets SecurityProtocol to this solution:
var pdf = PdfGenerator.GeneratePdf(Html, PageSize.A4, 20, null, OnStylesheetLoad, OnImageLoadPdfSharp);
... ...
public static void OnImageLoadPdfSharp(object sender, HtmlImageLoadEventArgs e)
{
var url = e.Src;
if (!e.Src.StartsWith("http://") && !e.Src.StartsWith("https://"))
{
var ImgFilePath = System.Web.HttpContext.Current.Server.MapPath(url);
if (XImage.ExistsFile(ImgFilePath))
e.Callback(XImage.FromFile(ImgFilePath));
var ImgFilePath2 = System.Web.HttpContext.Current.Server.MapPath(url);
if (XImage.ExistsFile(ImgFilePath2))
e.Callback(XImage.FromFile(ImgFilePath2));
}
else
{
using (var client = new WebClient())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (var stream = new MemoryStream(client.DownloadData(url)))
{
e.Callback(XImage.FromStream(stream));
}
}
}
}

Facing issues while printing on Dot Matrix Printer

I am developing a desktop application in java swing; in which I need to take a bill print on dot matrix printer, the print will be having name, address and table which will be having item, qty, price…etc, which should be printed as per their x, y positions on paper, font stored in database .
But in print there is issue of overlapping/attaching letters if I use the following code:
class BillPrint implements ActionListener, Printable
{
PrintMngt PM=new PrintMngt();
public int print(Graphics gx, PageFormat pf, int page) throws PrinterException {
if (page>0){return NO_SUCH_PAGE;}
Graphics2D g = (Graphics2D)gx; //Cast to Graphics2D object
g.translate(pf.getImageableX(), pf.getImageableY());
Vector<Vector<Object>> data =PM.getvarientDetail(printID);
for (int i = 0; i <data.size(); i++) {
if(data.get(i).get(3).toString().equalsIgnoreCase("DYNAMIC"))
{
String bill_no=textField_Trans.getText();
int TblH,TblL;
Vector<String> Tbl_HL=PM.getTblHieghtNoLline(printID);
//PRINT_ID0, QUERY_STATIC1, OBJECT_NAME2, QUERY_TYPE3, X4, Y5, WIDTH6,
//ALIGN7, FONT8, F_SIZE9, F_STYLE10, SECTION11, LOOPES_NO12, OBJ_FORMAT13, VARIANT_ID14
TblH=Integer.parseInt(Tbl_HL.get(0).toString());
TblL=Integer.parseInt(Tbl_HL.get(1).toString());
int x=Integer.parseInt(data.get(i).get(4).toString());
int y=Integer.parseInt(data.get(i).get(5).toString());
String fName=data.get(i).get(8).toString();
int fSize=Integer.parseInt(data.get(i).get(9).toString());
String fStyle=data.get(i).get(10).toString();
Font font=null;
if(fStyle.equalsIgnoreCase("Plain"))
{
font = new Font(fName,Font.PLAIN, fSize);
}
else if(fStyle.equalsIgnoreCase("Bold"))
{
font = new Font(fName,Font.BOLD, fSize);
}
else if(fStyle.equalsIgnoreCase("Italic"))
{
font = new Font(fName,Font.ITALIC, fSize);
}
else if(fStyle.equalsIgnoreCase("Bold Italic"))
{
font = new Font(fName,Font.BOLD+ Font.ITALIC, fSize);
}
System.out.println("Myqry"+data.get(i).get(1).toString());
Vector<String> Query_Static=PM.getQuery_Static(data.get(i).get(1).toString(),bill_no);
for (int j = NoOfProd; j < Query_Static.size(); j++) {
g.drawString(Query_Static.get(j).toString(),x,y);
y=y+TblH/TblL;
g.setFont(font);
}
}
}
return PAGE_EXISTS; //Page exists (offsets start at zero!)
}
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
int ProductCnt= PM.getNoProduct(textField_Trans.getText().toString());//no. of products under given billno
int TableLine=PM.getTblNoLline(printID);//no. of lines to print
System.out.println("No of TableLines="+TableLine);
System.out.println("No of Product="+ProductCnt);
for (int i = 0; i <(TableLine/ProductCnt); i++)
{
job.print();
NoOfProd=NoOfProd+TableLine;
}
NoOfProd=0;
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
}//end actionPerformed
}//end BillPrint
I have also tried with writing data to .txt file and then printing it. Here output is proper i.e letters are not overlapping , but here in this method I m not able to give proper positions for my data. Following method I used for this:
private void printData(){
File output = new File("E:\\PrintFile1.txt");
output.setWritable(true);
String billNo="B1000", patient = "ABC";
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(output));
out.write(billNo + "\n");
out.write(patient + "\n" );
out.write("\n");
out.write("\n");
out.close();
}
catch (java.io.IOException e)
{
System.out.println("Failed to write Output");
}
FileInputStream textStream = null;
try
{
textStream = new FileInputStream("E:\\PrintFile1.txt");
}
catch (java.io.FileNotFoundException e)
{
System.out.println("Error trying to find the print file.");
}
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc mydoc = new SimpleDoc(textStream, flavor, null);
PrintService printer = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob printJob = printer.createPrintJob();
try
{
printJob.print(mydoc, null);
}
catch (javax.print.PrintException e)
{
JOptionPane.showMessageDialog(this, "Error occured while attempting to print.", "Error!", JOptionPane.ERROR_MESSAGE);
}
}
Basically for the issue in the letters i just add one space for each character in the string
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
public class Print implements Printable {
/* Just add one space for all charaters */
String numero = "Numero Nro :";
String numeroreplace = numero.replaceAll(".(?=.)", "$0 ");
public Print() {
super();
}
/* The font for you string */
public int print(Graphics g,PageFormat pf, int page) throws PrinterException{
Font textFont = new Font(Font.SANS_SERIF,Font.PLAIN,8);
/* To set the position, you can use for or while if u need it. */
g.setFont(textFont);
g.drawString(numeroreplace,350,150);
}
}
Finally you need to copy all this code just add one space for all characters in code.
Note : you must be call from yor main program.

Blackberry json parser

I want to create a simple json parser for BlackBerry to test. I found this example, and implement my code as follows
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import org.json.me.JSONArray;
import org.json.me.JSONObject;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;
public final class MyScreen extends MainScreen
{
HttpConnection conn = null;
InputStream in = null;
String _response = null;
Vector _adBeanVector=null;
int code;
public MyScreen()
{
setTitle("MyTitle");
try
{
StringBuffer url=new StringBuffer().append("http://codeincloud.tk/json_android_example.php");
conn = (HttpConnection) Connector.open(url.toString(), Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while (-1 != (len = in.read(buffer))) {
out.write(buffer);
}
out.flush();
_response = new String(out.toByteArray());
JSONObject resObject=new JSONObject(_response);
String _key =resObject.getString("Insert Json Key");
_adBeanVector = new Vector();
JSONArray newsArray = resObject.getJSONArray("Insert Json Array Key");
if(newsArray.length() > 0)
{
for (int i=0 ;i < newsArray.length() ; i++)
{
Vector _adElementsVector=new Vector();
JSONObject newsObj = newsArray.getJSONObject(i);
_adElementsVector.addElement(newsObj.getString("message"));
//_adElementsVector.addElement(newsObj.getString("Insert Json Array Element Key2"));
_adBeanVector.addElement(_adElementsVector);
}
}
if (out != null){
out.close();
}
if (in != null){
in.close();
}
if (conn != null){
conn.close();
}
}
} catch (Exception e)
{
Dialog.alert(e.getMessage());
}
}
}
but I cannot modify it for my purpose. Can any one help me to modify this code sample to access this json. I'm very much new to this subject area.
Thank you in advance.
try this -
JSONObject resObject=new JSONObject(_response);
String _name=resObject.getString("name"); //This will get the result as Froyo
String _version=resObject.getString("version"); //This will get the result as Android 2.2
Dialo.alert("Name : "+_name+" and Version : "+_version);

How send a html file direclty to the printer in java

I'm using this to send a htlm file direclty to printer and it says invalid flavour which means that the printer does not support the formats. Any one have an idea to do this..
/**
* #param args
*/
public static void main(String[] args) {
// Input the file
FileInputStream textStream = null;
try {
textStream = new FileInputStream("./some.html");
} catch (FileNotFoundException ffne) {
}
if (textStream == null) {
return;
}
// Set the document type
DocFlavor myFormat = DocFlavor.INPUT_STREAM.TEXT_HTML_HOST;
// Create a Doc
Doc myDoc = new SimpleDoc(textStream, myFormat , null);
// Build a set of attributes
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
//aset.add(MediaSize.NA.LEGAL);
aset.add(Sides.ONE_SIDED);
// discover the printers that can print the format according to the
// instructions in the attribute set
PrintService services = PrintServiceLookup.lookupDefaultPrintService();
//PrintServiceLookup.lookupPrintServices(myFormat, aset);
// Create a print job from one of the print services
//System.out.println("====5======="+service.get);
//if (services.length > 0) {
for (int i = 0; i < services.getSupportedDocFlavors().length; i++) {
System.out.println("====getSupportedDocFlavors======="+services.getSupportedDocFlavors()[i]);
}
DocPrintJob job = services.createPrintJob();
try {
job.print(myDoc, aset);
} catch (PrintException pe) {
System.out.println("====PrintException======="+pe);
}
//}
}
It says
sun.print.PrintJobFlavorException: invalid flavor
You are trying to force printer to handle (render) HTML document onto the paper. It will never work that way. And ofcourse the flavor you are sending is not supported.
First of all you need to render HTML into some graphical representation and then send it to printer. There are no good cross-platform tools for Java that could render modern HTML pages. But there is one in JavaFX and i guess you could use it to handle the task.
About printing the final image you can read here:
http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html
or see the code here:
http://www.java2s.com/Code/Java/2D-Graphics-GUI/PrintanImagetoprintdirectly.htm
or just find any other resource - there are a lot about printing.
public class POSPrinter {
private static final Log LOG = LogFactory.getLog(POSPrinter.class);
public POSPrinter(Long billID, String printMode) {
}
/**
*
* This method prints the specified PDF to specified printer under specified
*
* job name
*
*
*
* #param filePath
* Path of PDF file
*
* #param printerName
* Printer name
*
* #param jobName
* Print job name
*
* #throws IOException
*
* #throws PrinterException
*/
public void printPDF(String filePath, String printerName, String jobName,
Integer height, Integer width) throws IOException, PrinterException {
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] pdfContent = new byte[fileInputStream.available()];
fileInputStream.read(pdfContent, 0, fileInputStream.available());
ByteBuffer buffer = ByteBuffer.wrap(pdfContent);
final PDFFile pdfFile = new PDFFile(buffer);
Printable printable = new Printable() {
public int print(Graphics graphics, PageFormat pageFormat,
int pageIndex) throws PrinterException {
int pagenum = pageIndex + 1;
if ((pagenum >= 1) && (pagenum <= pdfFile.getNumPages())) {
Graphics2D graphics2D = (Graphics2D) graphics;
PDFPage page = pdfFile.getPage(pagenum);
Rectangle imageArea = new Rectangle(
(int) pageFormat.getImageableX(),
(int) pageFormat.getImageableY(),
(int) pageFormat.getImageableWidth(),
(int) pageFormat.getImageableHeight());
graphics2D.translate(0, 0);
PDFRenderer pdfRenderer = new PDFRenderer(page, graphics2D,
imageArea, null, null);
try {
page.waitForFinish();
pdfRenderer.run();
} catch (InterruptedException exception) {
exception.printStackTrace();
}
return PAGE_EXISTS;
} else {
return NO_SUCH_PAGE;
}
}
};
PrinterJob printJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = PrinterJob.getPrinterJob().defaultPage();
printJob.setJobName(jobName);
Book book = new Book();
book.append(printable, pageFormat, pdfFile.getNumPages());
printJob.setPageable(book);
Paper paper = new Paper();
paper.setSize(width, height);
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
// pageFormat
pageFormat.setPaper(paper);
// PrintService[] printServices = PrinterJob.lookupPrintServices();
//
// for (int count = 0; count < printServices.length; ++count) {
//
// if (printerName.equalsIgnoreCase(printServices[count].getName())) {
//
// printJob.setPrintService(printServices[count]);
//
// break;
//
// }
//
// }
PrintService printService = PrintServiceLookup
.lookupDefaultPrintService();
printJob.setPrintService(printService);
printJob.print();
}