All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.core.print.Printer Maven / Gradle / Ivy

There is a newer version: 2024.0.2
Show newest version
package shz.core.print;

import shz.core.NullHelp;
import shz.core.PRException;
import shz.core.ToList;
import shz.core.msg.ClientFailureMsg;
import shz.core.net.NetHelp;

import javax.print.*;
import javax.print.attribute.PrintRequestAttributeSet;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.List;

public class Printer {
    protected final PrintRequestAttributeSet attributes;
    protected final DocFlavor flavor;

    public Printer(PrintRequestAttributeSet attributes, DocFlavor flavor) {
        this.attributes = attributes;
        this.flavor = flavor;
    }

    public Printer(DocFlavor flavor) {
        this(null, flavor);
    }

    public final List services() {
        return ToList.asList(PrintServiceLookup.lookupPrintServices(flavor, attributes));
    }

    public final List serviceNames() {
        List services = services();
        if (services.isEmpty()) return Collections.emptyList();
        return ToList.explicitCollect(services.stream().map(PrintService::getName), services.size());
    }

    public final PrintService service(String name) {
        if (NullHelp.isBlank(name)) return PrintServiceLookup.lookupDefaultPrintService();
        for (PrintService service : services()) if (name.equals(service.getName())) return service;
        return null;
    }

    public final void print(PrintService service, Doc doc) {
        ClientFailureMsg.requireNonNull(service, "请选择打印服务");
        DocPrintJob job = service.createPrintJob();
        try {
            job.print(doc, attributes);
        } catch (PrintException e) {
            throw PRException.of(e);
        }
    }

    public final void print(InetSocketAddress address, int timeoutMillis, byte[] bytes) {
        NetHelp.send(address, timeoutMillis, bytes);
    }

    public final void print(String host, int port, byte[] bytes) {
        NetHelp.send(InetSocketAddress.createUnresolved(host, port), 0, bytes);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy