Hello Everyone,
I have a bit of code that allows me to print some text.
This works fine on modern printers like inkjets and laser jets.
However, when I specify a Dot Matrix printer, the character spacing is terrible.
I've come to understand (slightly, I think) that Dot Matrix printers do not print graphics too well.
Even though I'm only printing text, the program renders it as graphics.
Because of this, I would like to ask what is the correct way of printing using a Dot Matrix printer.
Below is my current code:
public class TextPrintable implements Printable { private String stringToPrint = "1234567890\n!@#$%^&*()"; private int xCoor = 0; private int yCoor = 0; private double margin = 0.5 * 72; private Font mainFont = new Font("Roman PS", Font.PLAIN, 9); /* Getters and Setters here */ @Override public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { if(pageIndex > 0) { return Printable.NO_SUCH_PAGE; } Graphics2D g2d = (Graphics2D)graphics; g2d.setFont(mainFont); int charHeight = g2d.getFontMetrics().getHeight(); /* Perform rendering */ for(String line : this.stringToPrint.split("\n")) { g2d.translate(0, charHeight); g2d.drawString(line, (float)(xCoor + margin), (float)(yCoor + margin)); } return 0; } }
private void textPrintBtnActionPerformed(java.awt.event.ActionEvent evt) { String data = this.txtArea.getText(); TextPrintable tp= new TextPrintable(); if(data == null) { System.out.println("No data from text area"); } else { System.out.println("Data:"); System.out.println(data); tp.setStringToPrint(data); } int xCoor = Integer.parseInt(this.xTxtField.getText()); int yCoor = Integer.parseInt(this.yTxtField.getText()); PrinterJob job = PrinterJob.getPrinterJob(); tp.setxCoor(xCoor); tp.setyCoor(yCoor); tp.setStringToPrint(data); double margin = 0.5 * 72; Paper paper = new Paper(); paper.setImageableArea(margin, margin, paper.getWidth() - (margin * 2), paper.getHeight() - (margin * 2)); PageFormat pf = new PageFormat(); pf.setPaper(paper); job.setPrintable(tp, pf); try { job.print(); } catch(PrinterException pe) { pe.printStackTrace(); } }