如何获取一个文件在Java中发送到打印机时所需的页面数?
我正在做一个项目,在那里我得到一个文件,然后用如何获取一个文件在Java中发送到打印机时所需的页面数?,java,printing,desktop,Java,Printing,Desktop,我正在做一个项目,在那里我得到一个文件,然后用desktop.print(文件)打印它 但是,如果这个文件非常大,比如说50页,那么我就不想将作业发送到打印机 在我开始工作之前,有没有办法获取文件需要打印的页数 以下是我执行此操作的代码部分: File file = new File(filePath); try { desktop.print(file); } catch (IOException e) { System.out.println("error
desktop.print(文件)打印它代码>
但是,如果这个文件非常大,比如说50页,那么我就不想将作业发送到打印机
在我开始工作之前,有没有办法获取文件需要打印的页数
以下是我执行此操作的代码部分:
File file = new File(filePath);
try {
desktop.print(file);
} catch (IOException e) {
System.out.println("error in trying to print");
e.printStackTrace();
}
如果你得到文件大小,看看它是小于还是大于50页的文件大小。通过这种方式,您可以根据文件大小决定是否要打印。以下是获取文件大小的方法:
public static void main(String[] args)
{
File file =new File("c:\\java_xml_logo.jpg");
if(file.exists()){
double bytes = file.length();
double kilobytes = (bytes / 1024);
double megabytes = (kilobytes / 1024);
double gigabytes = (megabytes / 1024);
double terabytes = (gigabytes / 1024);
double petabytes = (terabytes / 1024);
double exabytes = (petabytes / 1024);
double zettabytes = (exabytes / 1024);
double yottabytes = (zettabytes / 1024);
System.out.println("bytes : " + bytes);
System.out.println("kilobytes : " + kilobytes);
System.out.println("megabytes : " + megabytes);
System.out.println("gigabytes : " + gigabytes);
System.out.println("terabytes : " + terabytes);
System.out.println("petabytes : " + petabytes);
System.out.println("exabytes : " + exabytes);
System.out.println("zettabytes : " + zettabytes);
System.out.println("yottabytes : " + yottabytes);
}else{
System.out.println("File does not exists!");
}
}
}
试着找一些java库来帮助您解决这个问题。我向谷歌询问“java打印库”,它向我展示了几个库。@user717630不起作用,因为文件类型不同,大小不一定与页面对应length@PatrykRoszczyniała这些似乎都是控制台打印类型的库。我看到的唯一提到的是javax.print,它不是第三方库。如果你看到了,请给我指一下user2464620,也许这就是你问题的答案?@user2464620这个答案看起来比其他所有答案都好,但不幸的是,我并不总是能够访问文件中的内容。它可以是pdf、或.docx或任何文件类型,也可以是文本和图片的混合体。所以我从来并没有实际处理过任何文件内容,只是用桌面打印出来。