[英]Printing an image with some text in java
我需要在打印機上以Java(Swing)打印圖像和一些數據,但都沒有用。 我只能處理數據,但不能處理圖像。 我有一個abc.png文件和6個jTextBoxes,這些值必須從打印機上打印出來。 我正在使用FileWriter和PrinterJob類來實現作業。 數據和圖像可以分別打印,但不能一起打印。 有人可以給我一些建議。
謝謝。
打印圖像的代碼:
try {
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0)
throw new RuntimeException("No printer services available.");
PrintService ps = pss[0];
System.out.println("Printing to " + ps);
DocPrintJob job = ps.createPrintJob();
FileInputStream fin = new FileInputStream("C://a.gif");
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);
//Doc doc1=new SimpleDoc();
job.print(doc, pras);
//fin.close();
} catch (IOException ie) {
ie.printStackTrace();
} catch (PrintException pe) {
pe.printStackTrace();
}
打印文本的代碼:
只需在FileInputStream中傳遞文件在硬盤上的位置即可。
一種解決方案是創建包含原始圖像和文本的第二個圖像。
這樣的事情可能行得通嗎? (未經測試):
public Image addTextToImage(BufferedImage i, String[] text) {
final int VERTICLE_PADDING_PIXELS = 5;
final int LEFT_MARGIN_PIXELS = 5;
FontMetrics fm = i.createGraphics().getFontMetrics();
int width = i.getWidth();
int height = i.getHeight()
+ (text.length * (fm.getHeight() + VERTICLE_PADDING_PIXELS));
for (String s : text) {
width = Math.max(width, fm.stringWidth(s) + LEFT_MARGIN_PIXELS);
}
BufferedImage result = new BufferedImage(i.getHeight(), width, height);
Graphics2D g = result.createGraphics();
g.drawImage(i, 0, 0, null);
for (int x = 0; x < text.length; x++) {
g.drawString(text[x], LEFT_MARGIN_PIXELS, i.getHeight() + (x + 1) *VERTICLE_PADDING_PIXELS + x*fm.getHeight());
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.