java 打印pdf文件

依赖

compile group: 'org.apache.pdfbox', name: 'pdfbox', version: '2.0.3'
//    compile group: 'org.apache.pdfbox', name: 'pdfbox-app', version: '1.8.10'
compile group: 'org.apache.pdfbox', name: 'fontbox', version: '1.5.0'

1. 生成pdf 文件  

pdf 文件代码

public Map<String, Object> generatePDF(Map<String, Object> params) {
        Map<String, Object> data = new HashMap<>(params);
        String pwoId = ConversionUtil.toString(params.get(FIELD_ID));
        if (!StringUtil.isEmpty(pwoId)) {
            String filepath = FILEPATH_PDF + pwoId + +new java.util.Date().getTime() + ".pdf";
            Document document = null;
            if (!StringUtil.equalsIgnoreCase(way, DEFAULT_WAY)) {
                document = new Document(PageSize.A4);
            } else {
                document = new Document(PageSize.A4.rotate());
            }
            try {
                BaseFont encoding = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                Font font = new Font(encoding, DEFAULT_FONT_SIZE, Font.NORMAL, BaseColor.BLACK);
                File file = new File(filepath);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
                PdfWriter.getInstance(document, new FileOutputStream(filepath));
                document.open();
                Paragraph title = new Paragraph(DEFAULT_TITLE, font);
                data.put(PRINTER_STATUS, STATE_SUCCESS);
                data.put(PRINTER_TIME, LocalDateTime.now());
                data.put(PRINTER_NAME, "HP LaserJet Pro MFP M128fw");
                String text = printTemplateText(data);
                Paragraph body = new Paragraph(text, font);
                title.setAlignment(Element.ALIGN_CENTER);
                title.setSpacingAfter(DEFAULT_AFTER_SPACING);
                title.setSpacingBefore(DEFAULT_BEFORE_SPACING);
                document.add(title);
                document.add(body);
                document.close();
                if (logger.isDebugEnabled()) {
                    logger.debug("PDF create filepath : " + file.getAbsolutePath());
                }
                int format = ConversionUtil.toInt(way);
                if (file.exists()) {
                    data.put(PRINTER_CODE, 200);//目前生成pdf,打印失败也算处置成功
                }

                if (printAction(data, file, format)) {
                    data.put(PRINTER_CODE, 200);
                    if (logger.isDebugEnabled()) {
                        logger.debug(filepath + "File printed successfully");
                    }
                } else {
                    data.put(PRINTER_CODE, 500);
                }
            } catch (Throwable e) {
                logger.error("create PDF file failed", e);
            }
        }
        return data;
    }

 

2 . 打印pdf 文件

 private static boolean printAction(Map<String, Object> data, File file, int way) throws PrinterException, IOException {
        Boolean isPrint = false;
        PDDocument document = null;
        try {
            document = PDDocument.load(file);
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setJobName(file.getName());
            //查找并设置打印机,获得所有打印机
            PrintService[] printServices = PrinterJob.lookupPrintServices();
            if (printServices == null || printServices.length == 0) {
                logger.error("Failed to print. No available printer found.");
                isPrint = false;
                return isPrint;
            }
            PrintService printService = null;
            for (int i = 0, len = printServices.length; i < len; i++) {
                printService = printServices[i];
                if (printService == null) {
                    continue;
                } else {
                    printJob.setPrintService(printService);
                    data.put(PRINTER_NAME, printService.getName());
                }
                //设置纸张及缩放
                PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);
                //设置多页打印
                Book book = new Book();
                PageFormat pageFormat = new PageFormat();
                //设置打印方向 1纵向 0 横向
                pageFormat.setOrientation(way);
                //设置纸张
                pageFormat.setPaper(getPaper());
                book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
                printJob.setPageable(book);
                //设置打印份数
                printJob.setCopies(1);
                //添加打印属性
                HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
                pars.add(Sides.DUPLEX); //设置单双页
                try {
                    printJob.print(pars);
                    isPrint = true;
                } catch (PrinterException e) {
                    isPrint = false;
                    continue;
                }
            }
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return isPrint;
    }
上一篇:JavaScript对象


下一篇:Python中turtle库的使用