ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java 打印pdf文件

2019-12-24 18:02:09  阅读:205  来源: 互联网

标签:PRINTER java 打印 file new put pdf document data


依赖

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

标签:PRINTER,java,打印,file,new,put,pdf,document,data
来源: https://www.cnblogs.com/daijiabao/p/12092824.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有