Java を使用して、Web アプリケーションからネットワーク プリンターにテキストを送信しようとしています。小さなテストを行うために、スタンドアロンの Java プログラムを作成して実行しました。最初は、文字が重なって印刷されていました。Orcale のバグ レポートを読んだ後、JRE を 1.7 から 1.6 に変更しました。その後、すべてがうまくいきました。しかし、Webアプリケーションを使用して印刷すると、同じプログラムが再び文字を重ねて印刷します。JRE 1.6 と Tomcat 6 を使用するように Web アプリケーションの設定を変更しました。プログラムを以下に示します。
public static void main(String[] args) {
TextPrint tp = new TextPrint();
try {
tp.textprint("test");
} catch (IOException e) {
e.printStackTrace();
}
}
public void textprint(String nmae) throws IOException {
PrintService printService = getPrintService("\\\\ADMIN-PC\\TVS MSP 250 Star");
PrinterJob printJob = PrinterJob.getPrinterJob();
try {
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(new Copies(1));
attributes.add(OrientationRequested.PORTRAIT);
printJob.setPrintService(printService);
attributes
.add(new PrinterResolution(120, 72, ResolutionSyntax.DPI));
PageFormat pPageFormat = new PageFormat();
Paper pPaper = pPageFormat.getPaper();
pPaper.setSize(432, 432);
pPaper.setImageableArea(0, 0, pPaper.getWidth(), pPaper.getHeight());
pPageFormat.setPaper(pPaper);
printJob.setPrintable(this, pPageFormat);
printJob.print();
} catch (PrinterException e1) {
e1.printStackTrace();
}
}
public void drawString(Graphics g, String line, int wc, int lineW, int y) {
g.drawString(line, (300 - lineW) / 2, y);// center
}
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
if (pageIndex > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
final String[][] priceTable = {
{ "1", "Paracetamol", "BAT123456", "03/20", "999", "8934.78",
"38865.22", "|" },
{ "2", "Distillation Water - Oral suspension (Ped)",
"BAT123457", "10/20", "99", "45.00", "4455.00", "|" },
{ "3", "Vicks", "BAT123458", "M05-21", "34", "453.00",
"15402.00", "|" },
{ "4", "Test Name ", "BAT123459", "12/21", "56", "53.00",
"2968.00", "|" },
{ "15", "No Name Tablets", "BAT123460", "06-22", "23",
"456.00", "10488.00", "|" },
{ "10", "Others", "BAT123461", "02/23", "7", "76.00", "532.00",
"|" } };
String[] columnW = { "10", "27", "200", "262", "295", "312", "340",
"410" };
String[] columnCharLen = { "2", "30", "10", "5", "2", "7", "8", "1" };
String[] align = { "R", "L", "L", "L", "R", "R", "R", "R" };
for (int i = 0; i < priceTable.length; i++) {
int y = 84 + (i * 12);
for (int j = 0; j < priceTable[i].length; j++) {
int xAxis = Integer.valueOf(columnW[j]);
int xChar = Integer.valueOf(columnCharLen[j]);
int diff = xChar - priceTable[i][j].length();
if (diff > 0 && align[j].equalsIgnoreCase("R")) {
xAxis = (int) (xAxis + (diff * 5.6));
}
System.out.println(" X for - " + priceTable[i][j] + " - "
+ xAxis);
graphics.drawString(priceTable[i][j], xAxis, y);//
}
}
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}