Search in sources :

Example 6 with PrintOptions

use of qz.printer.PrintOptions in project tray by qzind.

the class PrintPDF method parseData.

@Override
public void parseData(JSONArray printData, PrintOptions options) throws JSONException, UnsupportedOperationException {
    PrintOptions.Pixel pxlOpts = options.getPixelOptions();
    double convert = 72.0 / pxlOpts.getUnits().as1Inch();
    for (int i = 0; i < printData.length(); i++) {
        JSONObject data = printData.getJSONObject(i);
        HashSet<Integer> pagesToPrint = new HashSet<>();
        if (!data.isNull("options")) {
            JSONObject dataOpt = data.getJSONObject("options");
            if (!dataOpt.isNull("pageWidth") && dataOpt.optDouble("pageWidth") > 0) {
                docWidth = dataOpt.optDouble("pageWidth") * convert;
            }
            if (!dataOpt.isNull("pageHeight") && dataOpt.optDouble("pageHeight") > 0) {
                docHeight = dataOpt.optDouble("pageHeight") * convert;
            }
            if (!dataOpt.isNull("pageRanges")) {
                String[] ranges = dataOpt.optString("pageRanges", "").split(",");
                for (String range : ranges) {
                    String[] period = range.split("-");
                    try {
                        int start = Integer.parseInt(period[0]);
                        pagesToPrint.add(start);
                        if (period.length > 1) {
                            int end = Integer.parseInt(period[period.length - 1]);
                            pagesToPrint.addAll(IntStream.rangeClosed(start, end).boxed().collect(Collectors.toSet()));
                        }
                    } catch (NumberFormatException nfe) {
                        log.warn("Unable to parse page range {}.", range);
                    }
                }
            }
        }
        PrintingUtilities.Flavor flavor = PrintingUtilities.Flavor.valueOf(data.optString("flavor", "FILE").toUpperCase(Locale.ENGLISH));
        try {
            PDDocument doc;
            if (flavor == PrintingUtilities.Flavor.BASE64) {
                doc = PDDocument.load(new ByteArrayInputStream(Base64.decodeBase64(data.getString("data"))));
            } else {
                doc = PDDocument.load(ConnectionUtilities.getInputStream(data.getString("data")));
            }
            if (pxlOpts.getBounds() != null) {
                PrintOptions.Bounds bnd = pxlOpts.getBounds();
                for (PDPage page : doc.getPages()) {
                    PDRectangle box = new PDRectangle((float) (bnd.getX() * convert), page.getMediaBox().getUpperRightY() - (float) ((bnd.getHeight() + bnd.getY()) * convert), (float) (bnd.getWidth() * convert), (float) (bnd.getHeight() * convert));
                    page.setMediaBox(box);
                }
            }
            if (pagesToPrint.isEmpty()) {
                pagesToPrint.addAll(IntStream.rangeClosed(1, doc.getNumberOfPages()).boxed().collect(Collectors.toSet()));
            }
            originals.add(doc);
            List<PDDocument> splitPages = splitter.split(doc);
            // ensures non-ranged page will still get closed
            originals.addAll(splitPages);
            for (int pg = 0; pg < splitPages.size(); pg++) {
                if (pagesToPrint.contains(pg + 1)) {
                    // ranges are 1-indexed
                    printables.add(splitPages.get(pg));
                }
            }
        } catch (FileNotFoundException e) {
            throw new UnsupportedOperationException("PDF file specified could not be found.", e);
        } catch (IOException e) {
            throw new UnsupportedOperationException(String.format("Cannot parse (%s)%s as a PDF file: %s", flavor, data.getString("data"), e.getLocalizedMessage()), e);
        }
    }
    log.debug("Parsed {} files for printing", printables.size());
}
Also used : PDPage(org.apache.pdfbox.pdmodel.PDPage) PrintingUtilities(qz.utils.PrintingUtilities) JSONObject(org.codehaus.jettison.json.JSONObject) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) PrintOptions(qz.printer.PrintOptions) PDRectangle(org.apache.pdfbox.pdmodel.common.PDRectangle) HashSet(java.util.HashSet)

Example 7 with PrintOptions

use of qz.printer.PrintOptions in project tray by qzind.

the class PrintingUtilities method processPrintRequest.

/**
 * Determine print variables and send data to printer
 *
 * @param session WebSocket session
 * @param UID     ID of call from web API
 * @param params  Params of call from web API
 */
public static void processPrintRequest(Session session, String UID, JSONObject params) throws JSONException {
    Format format = getPrintFormat(params.getJSONArray("data"));
    PrintProcessor processor = PrintingUtilities.getPrintProcessor(format);
    log.debug("Using {} to print", processor.getClass().getName());
    try {
        PrintOutput output = new PrintOutput(params.optJSONObject("printer"));
        PrintOptions options = new PrintOptions(params.optJSONObject("options"), output, format);
        processor.parseData(params.getJSONArray("data"), options);
        processor.print(output, options);
        log.info("Printing complete");
        PrintSocketClient.sendResult(session, UID, null);
    } catch (PrinterAbortException e) {
        log.warn("Printing cancelled");
        PrintSocketClient.sendError(session, UID, "Printing cancelled");
    } catch (Exception e) {
        log.error("Failed to print", e);
        PrintSocketClient.sendError(session, UID, e);
    } finally {
        PrintingUtilities.releasePrintProcessor(processor);
    }
}
Also used : PrinterAbortException(java.awt.print.PrinterAbortException) PrintProcessor(qz.printer.action.PrintProcessor) PrintOptions(qz.printer.PrintOptions) PrintOutput(qz.printer.PrintOutput) PrinterAbortException(java.awt.print.PrinterAbortException) JSONException(org.codehaus.jettison.json.JSONException)

Example 8 with PrintOptions

use of qz.printer.PrintOptions in project tray by qzind.

the class PrintRaw method print.

@Override
public void print(PrintOutput output, PrintOptions options) throws PrintException {
    PrintOptions.Raw rawOpts = options.getRawOptions();
    List<ByteArrayBuilder> pages;
    if (rawOpts.getSpoolSize() > 0 && rawOpts.getSpoolEnd() != null && !rawOpts.getSpoolEnd().isEmpty()) {
        try {
            pages = ByteUtilities.splitByteArray(commands.getByteArray(), rawOpts.getSpoolEnd().getBytes(destEncoding), rawOpts.getSpoolSize());
        } catch (UnsupportedEncodingException e) {
            throw new PrintException(e);
        }
    } else {
        pages = new ArrayList<>();
        pages.add(commands);
    }
    for (int i = 0; i < rawOpts.getCopies(); i++) {
        for (ByteArrayBuilder bab : pages) {
            try {
                if (output.isSetHost()) {
                    printToHost(output.getHost(), output.getPort(), bab.getByteArray());
                } else if (output.isSetFile()) {
                    printToFile(output.getFile(), bab.getByteArray());
                } else {
                    if (rawOpts.isForceRaw()) {
                        if (SystemUtilities.isWindows()) {
                            // Placeholder only; not yet supported
                            printToBackend(output.getNativePrinter(), bab.getByteArray(), rawOpts.isRetainTemp(), Backend.WIN32_WMI);
                        } else {
                            // Try CUPS backend first, fallback to LPR
                            printToBackend(output.getNativePrinter(), bab.getByteArray(), rawOpts.isRetainTemp(), Backend.CUPS_RSS, Backend.CUPS_LPR);
                        }
                    } else {
                        printToPrinter(output.getPrintService(), bab.getByteArray(), rawOpts);
                    }
                }
            } catch (IOException e) {
                throw new PrintException(e);
            }
        }
    }
}
Also used : PrintOptions(qz.printer.PrintOptions) ByteArrayBuilder(qz.common.ByteArrayBuilder) javax.print(javax.print)

Aggregations

PrintOptions (qz.printer.PrintOptions)8 PageFormat (java.awt.print.PageFormat)3 PrintRequestAttributeSet (javax.print.attribute.PrintRequestAttributeSet)3 JSONException (org.codehaus.jettison.json.JSONException)3 JSONObject (org.codehaus.jettison.json.JSONObject)3 PrinterJob (java.awt.print.PrinterJob)2 IOException (java.io.IOException)2 javafx.print (javafx.print)2 javax.print (javax.print)2 PDDocument (org.apache.pdfbox.pdmodel.PDDocument)2 PDPage (org.apache.pdfbox.pdmodel.PDPage)2 PDRectangle (org.apache.pdfbox.pdmodel.common.PDRectangle)2 PrintingUtilities (qz.utils.PrintingUtilities)2 ArabicShapingException (com.ibm.icu.text.ArabicShapingException)1 BufferedImage (java.awt.image.BufferedImage)1 Paper (java.awt.print.Paper)1 PrinterAbortException (java.awt.print.PrinterAbortException)1 PrinterException (java.awt.print.PrinterException)1 InputStream (java.io.InputStream)1 URL (java.net.URL)1