twoface1997
twoface1997

Reputation: 23

Printing HTML as browser would see it - java

I am trying to automate the process of printing shipping labels for our company. I have a program that takes an email and gathers all the information from it that we need and puts it in an HTML file. I am using HTML because we want to include our logo,a JPG file hosted online (If you know of a way to do this without using HTML that would work, please share). I then have that file set to automatically print to the default printer without showing a dialog box. The problem is, what prints out is the text of the file, meaning all the html tags print out. Here is my code( sorry its a bit messy, I will clean it up when I get it working).

import java.util.*;
import java.io.*;
import java.io.File;
import java.lang.Object;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.print.*;
import javax.print.attribute.*;
import java.awt.print.*;
import java.awt.Desktop;
import javax.print.*;
import javax.print.attribute.*;
import java.io.*;
import java.awt.*;
public class Main2
{
    public Main2()
    {
        Path file = Paths.get("D:\\email\\2016.txt");
        ArrayList<String> text = new ArrayList<String>(1000);
        boolean stop = false;
        int i = 0;
        String line1;
        String line2;
        File myFile = new File("");
        try{
            File printme = File.createTempFile("printme", ".html", new     File("D:\\email\\output\\"));
            myFile.deleteOnExit();
            String pathName = (myFile.getAbsolutePath());

            BufferedWriter bw = new BufferedWriter(new FileWriter(printme));  
            bw.write("<html> <head> <meta name=vs_targetSchema     content=\"http://schemas.microsoft.com/intellisense/ie5\"><style     type=\"text/css\"> A { text-decoration: none; } A:link { color: #3366cc; text-    decoration: none; }   A:visited { color: #663399; text-decoration: none; }        A:active { color: #cccccc; text-decoration: none; } A:Hover { text-decoration:     underline; } BODY, TD, CENTER, P { font-family: Geneva, Verdana, Arial,     Helvetica; font-size: 12px; color: #333333; }    .body { font-family: Geneva,     Verdana, Arial, Helvetica; font-size: 10px; color: #333333; }  .content { font-    family: Arial, Helvetica, sans-serif; font-size: 11px; font-weight: normal;     color: #000000; }   .title { font-family: Helvetica, Arial, sans-serif; font-    size: 10px; font-weight: normal; color: #000000; } .headline { font-family:     Helvetica, Arial, sans-serif; font-size: 14px; font-weight: bold; color:     #000000; }    .message { font-family: Geneva, Verdana, Arial, Helvetica; font-    size: 9px; }    </style> </head><body bgcolor=\"#ffffff\" LINK=\"#3366cc\"     VLINK=\"#3366cc\" ALINK=\"#3366cc\" LEFTMARGIN=\"0\" TOPMARGIN=\"0\">    <table     cellSpacing=1 cellPadding=3 width=\"100%\" border=\"0\" runat=\"server\">    <tr>            <td colSpan=1><IMG src=\"http://www.eshanes.com//Images/eshaneslogo.jpg\"     border=0></td>    </tr>");
            bw.write("<TD class=FormLabel vAlign=top align=left     width=\"50%\"><br><h3><b>");

            BufferedReader reader = Files.newBufferedReader(file,     Charset.defaultCharset());
            line1 = reader.readLine();
            line1 = reader.readLine();
            line1 = reader.readLine();
            while(stop == false)
            {
                line1 = reader.readLine();
                line2 = reader.readLine();
                if ((line1.length() >= 22) && (line1.substring(0,     21).equals("Special Instructions:")))
                {
                    stop = true;
                    break;
                }

                else if ((line2.length() >= 22) && (line2.substring(0,        21).equals("Special Instructions:")))
                {
                    bw.write("<TD class=FormLabel vAlign=top align=left        width=\"50%\"><h3><b>            <br><br><b>");
                    bw.write(line1);
                    bw.write("</h3></b>");
                    stop = true;
                    break;
                }
                else
                {
                    bw.write(line1);
                    bw.write("<br>");
                    bw.write(line2);
                    bw.write("<br>");
                }
            }
            bw.write("</h3></b>             </TD>");
            reader.close();
            bw.close();
            print(printme);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void print(File file) {

        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        PrintService printService[] =     PrintServiceLookup.lookupPrintServices(flavor, pras);
        PrintService defaultService =     PrintServiceLookup.lookupDefaultPrintService();
        // PrintService service =     ServiceUI.printDialog(GraphicsEnvironment.getLocalGraphicsEnvironment().getDefau    ltScreenDevice().getDefaultConfiguration(), 200, 200,
        //     printService, defaultService, flavor, pras);
        //if (service != null) {
        DocPrintJob job = defaultService.createPrintJob();
        try{
            FileInputStream fis = new FileInputStream(file);
            DocAttributeSet das = new HashDocAttributeSet();
            Doc document = new SimpleDoc(fis, flavor, das);
            job.print(document, pras);
            //Thread.sleep(10000);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        catch (Exception e) {
        }

    }
}

Please help me fix this problem.

Upvotes: 1

Views: 2635

Answers (3)

twoface1997
twoface1997

Reputation: 23

Thanks for the help, DebD! This did not solve my problem, but it led me in the right direction. Here is the code that worked if anyone needs it:

public static void print(File file) {
    JFrame frame = new JFrame();
    JEditorPane pane= new JEditorPane();
    pane.setContentType("text/html");
    try{
        pane.setPage(file.toURI().toURL());
    }catch (IOException ex){
        System.out.println("MALFORMED ERROR!");
    }
    frame.add(pane);
    frame.setSize(200,200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    try{
        pane.print(null, null, false, PrintServiceLookup.lookupDefaultPrintService(), null, false);
    } catch (Exception e){
        System.out.println("PRINT ERROR!");
    }
}

Upvotes: 1

Jesper Juhl
Jesper Juhl

Reputation: 31468

What you seem to want is to parse the HTML, then do layout and rendering like a browser would. That's a fairly monumental task to undertake from scratch.

What you probably want is to find an existing layout engine that you can hand your HTML to and which will then return a rendered document/image/whatever.

Upvotes: 0

DebD
DebD

Reputation: 404

You need to first render the HTML. You could use JEditorPane for that. Just set the content type to "text/html", set your content. Now, you get a snap of the rendered contents as below

JEditorPane jp = new JEditorPane("text/html", textString);
jp.validate();
int w = jp.getWidth(), h = jp.getHeight();
BufferedImage saveimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = saveimg.createGraphics();
jp.paint(g2);

Now, use the graphics object to print.

Upvotes: 0

Related Questions