【问题标题】:Printing HTML as browser would see it - java打印 HTML 作为浏览器会看到它 - java
【发布时间】:2016-08-05 15:13:54
【问题描述】:

我正在尝试为我们公司自动化打印运输标签的过程。我有一个程序,它接收一封电子邮件并从中收集我们需要的所有信息并将其放入 HTML 文件中。我使用 HTML 是因为我们想要包含我们的徽标,一个在线托管的 JPG 文件(如果您知道不使用 HTML 的方法,请分享)。然后我将该文件设置为自动打印到默认打印机而不显示对话框。问题是,打印出来的是文件的文本,这意味着所有的 html 标签都会打印出来。这是我的代码(对不起,它有点乱,我会在它工作时清理它)。

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) {
        }

    }
}

请帮我解决这个问题。

【问题讨论】:

    标签: java html printing


    【解决方案1】:

    您需要先呈现 HTML。 您可以为此使用 JEditorPane。只需将内容类型设置为“text/html”,设置您的内容。现在,您可以得到如下渲染内容的快照

    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);
    

    现在,使用图形对象进行打印。

    【讨论】:

    • 我还没有运行这段代码,但听起来这将是我要尝试的第一件事。本质上是用java渲染并打印出来。
    【解决方案2】:

    您似乎想要的是解析 HTML,然后像浏览器一样进行布局和渲染。从头开始,这是一项相当艰巨的任务。

    可能想要的是找到一个现有的布局引擎,你可以将你的 HTML 交给它,然后它会返回一个渲染的文档/图像/任何东西。

    【讨论】:

      【解决方案3】:

      感谢您的帮助,DebD!这并没有解决我的问题,但它引导我朝着正确的方向前进。如果有人需要,这是可以使用的代码:

      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!");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-06-19
        • 1970-01-01
        • 1970-01-01
        • 2014-03-01
        • 2018-07-20
        • 1970-01-01
        • 1970-01-01
        • 2020-10-04
        • 2010-11-22
        相关资源
        最近更新 更多