Java使用原生态的打印方法直接调用打印机打印,仅支持gif、jpeg、png

    1. package com.example.demo.common;
    2. import javax.print.*;
    3. import javax.print.attribute.DocAttributeSet;
    4. import javax.print.attribute.HashDocAttributeSet;
    5. import javax.print.attribute.HashPrintRequestAttributeSet;
    6. import javax.print.attribute.PrintRequestAttributeSet;
    7. import java.io.File;
    8. import java.io.FileInputStream;
    9. import java.io.IOException;
    10. import java.io.InputStream;
    11. public class PrintUtils {
    12. public static void main(String[] args) {
    13. print("C:/Users/92384/Documents/test.png");
    14. }
    15. public static void print(String pathName){
    16. File file = new File(pathName); //获取选择的文件
    17. //构建打印请求属性集
    18. PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    19. //设置打印格式,因为未确定类型,所以选择autosense
    20. DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
    21. PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    22. System.out.println(service + " supports :");
    23. DocFlavor[] flavors = service.getSupportedDocFlavors();
    24. for (int i = 0; i < flavors.length; i++) {
    25. System.out.println("\t" + flavors[i]);
    26. }
    27. //定位默认的打印服务
    28. PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    29. //构造待打印的文件流
    30. InputStream fis = null;
    31. if(defaultService != null){
    32. try {
    33. DocPrintJob job = defaultService.createPrintJob(); //创建打印作业
    34. fis = new FileInputStream(file);
    35. DocAttributeSet das = new HashDocAttributeSet();
    36. Doc doc = new SimpleDoc(fis, flavor, das); //指定打印内容
    37. job.print(doc, pras);
    38. } catch (Exception e) {
    39. e.printStackTrace();
    40. } finally {
    41. try {
    42. fis.close();
    43. } catch (IOException e) {
    44. // TODO Auto-generated catch block
    45. e.printStackTrace();
    46. }
    47. }
    48. }
    49. }
    50. }