在不显示打印对话框的情况下进行打印,可以使用Java中的PrinterJob类。以下是一个简单的示例代码:
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.PrintQuality;
import java.io.FileInputStream;
import java.io.IOException;
public class PrintWithoutDialog {
public static void main(String[] args) throws IOException, PrintException {
String filePath = "path/to/your/file.txt";
FileInputStream inputStream = new FileInputStream(filePath);
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc doc = new SimpleDoc(inputStream, flavor, null);
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
if (printService != null) {
System.out.println("Found printer: " + printService.getName());
DocPrintJob printJob = printService.createPrintJob();
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(MediaSizeName.ISO_A4);
attributes.add(OrientationRequested.PORTRAIT);
attributes.add(new Copies(1));
attributes.add(new PrintQuality(50));
printJob.print(doc, attributes);
System.out.println("Document sent to printer");
} else {
System.out.println("No printer found");
}
}
}
这个示例代码将会打印一个文本文件,并且不会显示打印对话框。你可以根据需要修改代码,以适应不同的文件类型和打印需求。
注意:这个示例代码仅适用于Java SE环境,不适用于Java Web应用程序。
领取专属 10元无门槛券
手把手带您无忧上云