GP Coder

Trang chia sẻ kiến thức lập trình Java

  • Java Core
    • Basic Java
    • OOP
    • Exception Handling
    • Multi-Thread
    • Java I/O
    • Networking
    • Reflection
    • Collection
    • Java 8
  • Design pattern
    • Creational Pattern
    • Structuaral Pattern
    • Behavior Pattern
  • Web Service
    • SOAP
    • REST
  • JPA
  • Java library
    • Report
    • Json
    • Unit Test
  • Message Queue
    • ActiveMQ
    • RabbitMQ
  • All
Trang chủ Java Core Java I/O Hướng dẫn sử dụng Printing Service trong Java

Hướng dẫn sử dụng Printing Service trong Java

Đăng vào 17/12/2017 . Được đăng bởi GP Coder . 5393 Lượt xem . Toàn màn hình

Giới thiệu

Java Print Service API (Dịch vụ in) cho phép thực hiện lệnh in trên tất cả các nền tảng Java. Java Print Service API bao gồm một bộ thuộc tính (attribute) in mở rộng dựa trên các thuộc tính chuẩn được chỉ định trong Giao thức Internet Printing Protocol (IPP). Với các thuộc tính này, ứng dụng client và server có thể khám phá và chọn các máy in có các tính năng được xác định bởi các thuộc tính. Ngoài ra StreamPrintService cho phép các ứng dụng có thể chuyển mã dữ liệu sang các định dạng khác nhau, các bên thứ ba có thể tự động cài đặt các dịch vụ in riêng của họ thông qua Service Provider Interface.

Java Print Service API bao gồm các package:

  • javax.print: Cung cấp các lớp và interface chính cho Java Print Service API.
  • javax.print.attribute: Cung cấp các lớp và interface mô tả các loại thuộc tính Java Print Service và các phương thức có thể được thu thập thành các bộ thuộc tính.
  • javax.print.attribute.standard: Bao gồm các lớp xác định các thuộc tính in cụ thể.
  • javax.print.event: Bao gồm các lớp sự kiện (event) và listener interfaces để theo dõi các dịch vụ in và tiến độ công việc in cụ thể.

Ví dụ liệt kê danh sách dịch vụ in hiện có


import javax.print.PrintService;
import java.awt.print.PrinterJob;

public class PrintName {
    public static void main(String[] args) {
        //
        // Lookup for the available print services.
        //
        PrintService[] printServices = PrinterJob.lookupPrintServices();

        //
        // Iterates the print services and print out its name.
        //
        for (PrintService printService : printServices) {
            String name = printService.getName();
            System.out.println("Name = " + name);
        }
    }
}

Ví dụ lấy dịch vụ in mặc định của hệ thống và hiển thị các thuộc tính của nó


import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.Attribute;
import javax.print.attribute.AttributeSet;

public class GetPrinter {
	public static void main(String[] args) {
		//
		// Gets the default print service for this environment.
		// Null is returned when no default print service found.
		//
		PrintService printer = PrintServiceLookup.lookupDefaultPrintService();

		if (printer != null) {
			String printServiceName = printer.getName();
			System.out.println("Print Service Name = " + printServiceName);
			//
			// Getting print service's attribute set.
			//
			AttributeSet attributes = printer.getAttributes();
			for (Attribute a : attributes.toArray()) {
				String name = a.getName();
				String value = attributes.get(a.getClass()).toString();
				System.out.println(name + " : " + value);
			}
		}
	}
}

Kết quả thực thi chương trình trên:


Print Service Name = Foxit Reader PDF Printer
printer-name : Foxit Reader PDF Printer
printer-is-accepting-jobs : accepting-jobs
color-supported : supported
queued-job-count : 0

Ví dụ tạo ứng dụng in file sử dụng Java Print Service

Một ứng dụng sử dụng Java Print Service API thực hiện các bước sau để xử lý một yêu cầu in:

  • Tạo một lớp định nghĩa định dạng dữ liệu in (một DocFlavor phù hợp: pdf, text, …).
  • Tạo và điền vào một AttributeSet, gói gọn một tập hợp các thuộc tính mô tả các khả năng dịch vụ in mong muốn, chẳng hạn như: khả năng in 5 bản sao, đóng dấu và hai mặt.
  • Tìm một dịch vụ in có thể xử lý các yêu cầu in như được xác định bởi DocFlavor và tập hợp các thuộc tính.
  • Tạo một lệnh in từ dịch vụ in (Java Print Service).
  • Gọi phương thức in.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
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.MediaSize;
import javax.print.attribute.standard.Sides;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;

public class PrintFileExample {

	private static boolean jobRunning = true;

	public static void main(String[] args) throws InterruptedException, IOException {
		// Input the file
		InputStream is = new BufferedInputStream(new FileInputStream("data/test.pdf"));

		// Set the document type: create a PDF doc flavor
		DocFlavor myFormat = DocFlavor.INPUT_STREAM.PDF;

		// Create a Doc
		Doc myDoc = new SimpleDoc(is, myFormat, null);

		// Build a set of attributes
		PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
		aset.add(new Copies(5)); // print five copies
		aset.add(MediaSize.ISO.A4); // print stapled
		aset.add(Sides.DUPLEX); // print double-sided

		// discover the printers that can print the format according to the
		// instructions in the attribute set
		PrintService[] services = PrintServiceLookup.lookupPrintServices(myFormat, aset);

		// Create a print job from one of the print services
		if (services.length > 0) {
			// Create and return a PrintJob capable of handling data from
			// any of the supported document flavors.
			DocPrintJob printJob = services[0].createPrintJob();

			// register a listener to get notified when the job is complete
			printJob.addPrintJobListener(new JobCompleteMonitor());

			try {
				// Print a document with the specified job attributes.
				printJob.print(myDoc, aset);

				while (jobRunning) {
					Thread.sleep(1000);
				}
			} catch (PrintException pe) {
			}
		}

		System.out.println("Exiting app");
		is.close();
	}

	private static class JobCompleteMonitor extends PrintJobAdapter {
		@Override
		public void printJobCompleted(PrintJobEvent jobEvent) {
			System.out.println("Job completed");
			jobRunning = false;
		}
	}

}

Tài liệu tham khảo:

  • https://docs.oracle.com/javase/8/docs/technotes/guides/jps/index.html
  • https://docs.oracle.com/javase/8/docs/technotes/guides/jps/spec/JPSTOC.fm.html
  • https://docs.oracle.com/javase/8/docs/technotes/guides/jps/spec/jpsOverview.fm4.html
4.5
02
Nếu bạn thấy hay thì hãy chia sẻ bài viết cho mọi người nhé! Và Donate tác giả

Shares

Chuyên mục: Java I/O Được gắn thẻ: IO, Print

Giới thiệu java.io.tmpdir
Đọc ghi file CSV trong Java

Có thể bạn muốn xem:

  • Hướng dẫn sử dụng luồng vào ra nhị phân trong Java (12/12/2017)
  • Hướng dẫn phân tích nội dung HTML sử dụng thư viện Jsoup (02/01/2018)
  • Hướng dẫn đọc và ghi file excel trong Java sử dụng thư viện Apache POI (23/12/2017)
  • Hướng dẫn xuất dữ liệu ra file word, pdf với xDocReport (28/12/2017)
  • Thao tác với tập tin và thư mục trong Java (14/12/2017)

Bình luận

bình luận

Tìm kiếm

Bài viết mới

  • Clean code 13/01/2024
  • Giới thiệu CloudAMQP – Một RabbitMQ server trên Cloud 02/10/2020
  • Kết nối RabbitMQ sử dụng Web STOMP Plugin 19/06/2020
  • Sử dụng publisher confirm trong RabbitMQ 16/06/2020
  • Sử dụng Dead Letter Exchange trong RabbitMQ 13/06/2020

Xem nhiều

  • Hướng dẫn Java Design Pattern – Factory Method (97351 lượt xem)
  • Hướng dẫn Java Design Pattern – Singleton (96986 lượt xem)
  • Giới thiệu Design Patterns (86648 lượt xem)
  • Lập trình đa luồng trong Java (Java Multi-threading) (85486 lượt xem)
  • Giới thiệu về Stream API trong Java 8 (83024 lượt xem)

Lưu trữ

Thẻ đánh dấu

Annotation Authentication Basic Java Behavior Pattern Collection Creational Design Pattern Cấu trúc điều khiển Database Dependency Injection Design pattern Eclipse Exception Executor Service Google Guice Gson Hibernate How to Interceptor IO Jackson Java 8 Java Core JDBC JDK Jersey JMS JPA json JUnit JWT Message Queue Mockito Multithreading OOP PowerMockito RabbitMQ Reflection Report REST SOAP Structuaral Pattern Swagger Thread Pool Unit Test Webservice

Liên kết

  • Clean Code
  • JavaTpoint
  • Refactoring Guru
  • Source Making
  • TutorialsPoint
  • W3Schools Online Web Tutorials

Giới thiệu

GP Coder là trang web cá nhân, được thành lập với mục đích lưu trữ, chia sẽ kiến thức đã học và làm việc của tôi. Các bài viết trên trang này chủ yếu về ngôn ngữ Java và các công nghệ có liên quan đến Java như: Spring, JSF, Web Services, Unit Test, Hibernate, SQL, ...
Hi vọng góp được chút ít công sức cho sự phát triển cộng đồng Coder Việt.

Donate tác giả

Tìm kiếm các bài viết của GP Coder với Google Search

Liên hệ

Các bạn có thể liên hệ với tôi thông qua:
  • Trang liên hệ
  • Linkedin: gpcoder
  • Email: contact@gpcoder.com
  • Skype: ptgiang56it

Follow me

Copyright 2025 © GP Coder · All Rights Reserved · Giới thiệu · Chính sách · Điều khoản · Liên hệ ·

Share

Blogger
Delicious
Digg
Email
Facebook
Facebook messenger
Flipboard
Google
Hacker News
Line
LinkedIn
Mastodon
Mix
Odnoklassniki
PDF
Pinterest
Pocket
Print
Reddit
Renren
Short link
SMS
Skype
Telegram
Tumblr
Twitter
VKontakte
wechat
Weibo
WhatsApp
X
Xing
Yahoo! Mail

Copy short link

Copy link