我正在打印机上打印PNG图像。图像打印在页面中央,不会填满整个页面。我尝试增加图像的大小,但它始终位于页面的中心。任何想法如何使其适合页面?
psStream = new URL(url).openStream();
if (psStream == null) {
return "Unable to fetch image";
}
DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
Doc myDoc = new SimpleDoc(psStream, flavor, null);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintServiceAttributeSet attributes = new HashPrintServiceAttributeSet();
attributes.add(new PrinterName(printData.printer, Locale.getDefault()));
final PrintService[] printServices = PrintServiceLookup.lookupPrintServices(flavor, attributes);
if (printServices.length == 0) {
return "Could not find printer " + printData.printer;
} else {
myPrinter = printServices[0];
DocPrintJob job = myPrinter.createPrintJob();
try {
job.print(myDoc, aset);
return null;
} catch (Exception e) {
e.printStackTrace();
return "Could not print : " + e.getMessage();
}
}
答案 0 :(得分:0)
基本上,您必须调整图像大小以适应页面尺寸。此外,打印机驱动程序默认定义页面边框区域。因此,要使用整个页面,您必须删除这些边框。但是,有时候删除边框是不可能的,因为它是由打印机的驱动程序控制的,所以你可以控制你控制的驱动程序。
public void print(String imageFileName) throws IOException, PrinterException {
final PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
final BufferedImage image = ImageIO.read(new File(imageFileName));
final PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setJobName("MyApp: " + imageFileName);
printJob.setPrintService(printService);
printJob.setPrintable(new Printable() {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex == 0) {
final Paper paper = pageFormat.getPaper();
paper.setImageableArea(0.0, 0.0, pageFormat.getPaper().getWidth(), pageFormat.getPaper().getHeight());
pageFormat.setPaper(paper);
graphics.translate((int) pageFormat.getImageableX(), (int) pageFormat.getImageableY());
graphics.drawImage(image, 0, 0, (int) pageFormat.getPaper().getWidth(), (int) pageFormat.getPaper().getHeight(), null);
return PAGE_EXISTS;
} else {
return NO_SUCH_PAGE;
}
}
});
printJob.print();
}
我猜你不想要打印拉伸的图像,所以你必须正确地缩放图像。还有另一篇文章似乎是相同的,并展示了如何缩放图像:Fit image into the printing area
答案 1 :(得分:0)
这是我用来打印Java Swing JPanel的一些代码。您可以修改它以从png打印BufferedImage。
我保持图像成比例,因此它只能水平或垂直填充页面,但不能同时填充两者。
var _message = _criticalData.Select(item1 => item1.States.Select(item2 =>item2.Messages).ToArray()).ToArray()