Question

I want to create a small preview of HTML that will be printed within a Swing app. Basically, it would display the page at the size of a PageFormat class (i.e. the size of a printable page), but at 1/4 the size or less of the page.

So far, I've tried the following:

    //Create components
    JDialog frame = new JDialog(new JFrame("Test"), "Test", true);
    JPanel panel = new JPanel(){
    @Override
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.scale(0.5,0.5);
        super.paintComponent(g2);
    }};  
    PageFormat pf = new PageFormat();
    Dimension dimension = new Dimension();
    dimension.setSize(pf.getImageableWidth(), pf.getImageableHeight());
    panel.setPreferredSize(dimension);

    panel.add(new JEditorPane("text/html", "<i>Testing, testing, one two three</i>"));

    //Finalize everything
    frame.setContentPane(panel);
    frame.pack();
    frame.setVisible(true);

Unfortunately, this creates a JPanel that is the full page size, but scales the JEditorPane into the upper left quarter of the screen because the size of the JPanel doesn't seem to scale as well. Also, if you click on the JEditorPane, it appears at full size. How can I get the effect I want?

Also, this doesn't have to be an editable HTML page, so if there is some clever solution that doesn't involve directly displaying HTML, I'm open to it.

Was it helpful?

Solution

http://java-sl.com/JEditorPanePrinter.html you can use the code to see how preview is implemeted.

Alternatively yu can define a BufferedImage passing desired width/height> Use the image's getGraphics() and apply the AffineTransform you need (scale in the simplest case). Then just call yourJEditorPane.paint(g) where g is the image's Graphics.

OTHER TIPS

Instead of using setpreferredsize() try using setmaximumsize and instead of assigning pf.getImageableWidth(), pf.getImageableHeight() directly, assign it to some int and try to print it. Then change the int according to the required size

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top