码迷,mamicode.com
首页 > 编程语言 > 详细

java 打印pdf文件

时间:2019-12-24 18:54:25      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:des   ati   trace   rac   deb   shm   center   data   object   

依赖

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;
    }

java 打印pdf文件

标签:des   ati   trace   rac   deb   shm   center   data   object   

原文地址:https://www.cnblogs.com/daijiabao/p/12092824.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!