我需要为我的打印机打印pdf文件。使用此代码,我已将我的pdf转换为bytearray,但我陷入困境,不知道如何将其发送到打印机。有人可以帮帮我吗?
File file = new File("java.pdf");
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
//Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
System.out.println("ERROR!");
}
byte[] bytes = bos.toByteArray();
提前谢谢。
答案 0 :(得分:2)
要遵循的步骤:
示例代码段:
byte[] bytes = bos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream( bytes );
// First identify the default print service on the system
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
// prepare the flvaor you are intended to print
DocFlavor docFlavor = DocFlavor.BYTE_ARRAY.PDF;
// prepare the print job
DocPrintJob printJob = printService.createPrintJob();
// prepare the document, with default attributes, ready to print
Doc docToPrint = new SimpleDoc( bais, docFlavor, null );
// now send the doc to print job, with no attributes to print
printJob.print( docToPrint, null );
答案 1 :(得分:1)
另一种方法是使用intent发送pdf文件,这里是example
示例代码:
Intent prnIntent = new Intent(Intent.ACTION_SEND);
prnIntent.putExtra(Intent.EXTRA_STREAM, uri);
prnIntent.setType("application/pdf");
startActivity(Intent.createChooser(prnIntent , "Send pdf using:"));
使用这种方法不需要使用缓冲区,但是您可以直接将pdf文件发送给打印机!
答案 2 :(得分:1)
使用ByteArrayInputStream
抛出java.lang.IllegalArgumentException
,但常规字节数组对我有效。修改Ravinder Reddy:
// Get default print service
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
// Create a print job
DocPrintJob printJob = printService.createPrintJob();
// Optional fancy listener
printJob.addPrintJobListener(new PrintJobAdapter() {
@Override
public void printJobCompleted(PrintJobEvent pje) {
System.out.println("PDF printing completed");
super.printJobCompleted(pje);
}
@Override
public void printJobFailed(PrintJobEvent pje) {
System.out.println("PDF printing failed");
super.printJobFailed(pje);
}
});
// Check the PDF file and get a byte array
File pdfFile = new File("path/to/pdf");
if (pdfFile.exists() && pdfFile.isFile()) {
byte[] PDFByteArray = Files.readAllBytes(FileSystems.getDefault().getPath(pdfFile.getAbsolutePath()));
// Create a doc and print it
Doc doc = new SimpleDoc(PDFByteArray, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
printJob.print(doc, null);
}