Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9160185
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T13:40:38+00:00 2026-06-17T13:40:38+00:00

Is there a way I can rig a PrinterJob in Java to NOT actually

  • 0

Is there a way I can rig a PrinterJob in Java to NOT actually print to a printer so that I can get the graphics objects for each page? I tried setting the PrintService to null, but Java wouldn’t allow that.

This is so that I can retrieve an accurate Print Preview for the document without essentially rebuilding PrinterJobs functions from the ground-up in a different context.

Here’s the code for the print function in my program:

public int print(Graphics graphics, PageFormat pageFormat, int page) throws PrinterException {

    deepCopyString = string;

    FontMetrics metrics = graphics.getFontMetrics(font);
    int lineHeight = metrics.getHeight();

    arrangePage(graphics, pageFormat, metrics);

    if (page > pageBreaks.length){
        return NO_SUCH_PAGE;
    }

    Graphics2D g = (Graphics2D) graphics;

    g.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g.setFont(font);

    int begin = (page == 0) ? 0 : pageBreaks[page-1];
    int end = (page == pageBreaks.length) ? lines.length : pageBreaks[page];

    int y = 0;
    int x = 0;

    for (int line = begin; line < end; line++){
        x = 0;
        y += lineHeight;

        checkSyntax(line);

        String l = lines[line];

        for (int c = 0; c < l.length(); c++){
            applySyntax(c, line);

            metrics = graphics.getFontMetrics(font);
            String ch = Character.toString(l.charAt(c));

            g.setFont(font);
            g.drawString(ch, x, y);

            x += metrics.charWidth(l.charAt(c));
            //System.out.println(c + "/"+l.length());
        }

        //g.drawString(lines[line], 0, y);
    }

    reset();

    records.add(g);

    return PAGE_EXISTS;
}

You can already see that the Graphics objects are recorded so that I can paint them in another component, but it’s rather useless seeing as it will go ahead and send these to my printer before the record can be completed.

This may be a bad idea in general, and I’m pretty new to printing. If this is seriously a bad way to go about this, feel free to direct me to a source that’ll explain a better way.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T13:40:39+00:00Added an answer on June 17, 2026 at 1:40 pm

    Basically, you want to create you own Graphics context to which you can paint. You also need to construct a PageFormat that can be past to the print method.

    enter image description here

    public class TestPrint implements Printable  {
    
        private BufferedImage background;
        public static final float DPI = 72;
    
        public static void main(String[] args) {
            new TestPrint();
        }
    
        public TestPrint() {
    
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (Exception ex) {
                    }
    
                    try {
                        background = ImageIO.read(new File("C:/Users/shane/Dropbox/MegaTokyo/MgkGrl_Yuki_by_fredrin.jpg"));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
    
                    float width = cmToPixel(21f, DPI);
                    float height = cmToPixel(29.7f, DPI);
    
                    Paper paper = new Paper();
                    float margin = cmToPixel(1, DPI);
                    paper.setImageableArea(margin, margin, width - (margin * 2), height - (margin * 2));
                    PageFormat pf = new PageFormat();
                    pf.setPaper(paper);
    
                    BufferedImage img = new BufferedImage(Math.round(width), Math.round(height), BufferedImage.TYPE_INT_RGB);
                    Graphics2D g2d = img.createGraphics();
                    g2d.setColor(Color.WHITE);
                    g2d.fill(new Rectangle2D.Float(0, 0, width, height));
                    try {
                        g2d.setClip(new Rectangle2D.Double(pf.getImageableX(), pf.getImageableY(), pf.getImageableWidth(), pf.getImageableHeight()));
                        print(g2d, pf, 0);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                    }
                    g2d.dispose();
    
                    JFrame frame = new JFrame("Test");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new JLabel(new ImageIcon(img)));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    
                }
            });
    
        }
    
        public float cmToPixel(float cm, float dpi) {
    
            return (dpi / 2.54f) * cm;
    
        }
    
        public int print(Graphics graphics, PageFormat pageFormat, int page) throws PrinterException {
    
            if (page > 0) {
                return NO_SUCH_PAGE;
            }
    
            Graphics2D g = (Graphics2D) graphics;
    
            g.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
            if (background != null) {
    
                int x = (int)Math.round((pageFormat.getImageableWidth() - background.getWidth()) / 2f);
                int y = (int)Math.round((pageFormat.getImageableHeight() - background.getHeight()) / 2f);
    
                g.drawImage(background, x, y, null);
    
            }
    
            g.setColor(Color.BLACK);
            g.draw(new Rectangle2D.Double(0, 0, pageFormat.getImageableWidth() - 1, pageFormat.getImageableHeight() - 1));
    
            return PAGE_EXISTS;
        }
    }
    

    Now, obviously, there are going to be difference to what is printed to the screen and what’s printed to the printer, because we’re not actually using the same hardware device, but the basic concept applies

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

is there any way can get a textarea line-height(i want a number of px,not
Is there way that I can read the file from remote server using fopen
Is there any way I can set a formatter on models that will convert
Is there way you can suggest to help to get rid of calling the
Is there a way I can get a blank MVC template for VS2008? Like
Is there any way I can rename the window titlebar of an application that
Is there any way I can get NHibernate to use the READPAST hint when
Is there any way you can get CreatedBy field for SPListItem Folder . I
Is there any way can declare a bean in just like JSP UseBean in
Is there any way we can fetch X509 Public Cetrificates using c# from AD

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.