几年没有接触过Java,但我被要求编写一些Java代码来打印图片和一些文本几次。它在 Mac 上运行良好,但从 Windows 机器打印时打印出来的内容会被裁剪。图像是他的分辨率,大约 8x10,300DPI。
public class printClass implements Printable {
BufferedImage image;
private URL url;
printClass(URL url1) {
url = url1;
}
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
AffineTransform theAT = g2d.getTransform();
double theScaleFactor = (72d / 300d);
Font font = new Font("Arial", Font.PLAIN, 10);
Font font2 = new Font("Arial", Font.PLAIN, 5);
g2d.setFont(font);
if (page < 10) {
g2d.scale(theScaleFactor, theScaleFactor);
g2d.drawRenderedImage(image, null);
g2d.setTransform(theAT);
return PAGE_EXISTS;
} else {
return NO_SUCH_PAGE;
}
}public void init() {
try {
img = ImageIO.read(url);
image = (BufferedImage) img;
} catch (IOException e) {
System.out.println("Error: " + e);
}
PrinterJob job = PrinterJob.getPrinterJob();
PrinterResolution pr = new PrinterResolution(300, 300, PrinterResolution.DPI);
PrintRequestAttributeSet attrib = new HashPrintRequestAttributeSet();
PageFormat pFormat = job.getPageFormat(attrib);
Paper paper = pFormat.getPaper();
paper.setImageableArea(0.0,0.0,pFormat.getPaper().getWidth(), pFormat.getPaper().getHeight());
pFormat.setPaper(paper);
attrib.add(pr);
attrib.add(PrintQuality.HIGH);
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print(attrib);
} catch (PrinterException ex) {
}
}
}
}
URL 是正在打印的图像。这是 Java 小程序的一部分。此代码中缺少文本添加部分,但如下所示:
g.drawString(markUpText, x, y);
一如既往地提前谢谢你。