java 使用itextpdf分割pdf文件,pdf分页

itextpdf依赖

        
            com.itextpdf
            itextpdf
            5.5.13.2
        

代码实现,  我这里是直接输出到response的响应流了,给前端页面分页查看pdf用,如果分割成多个pdf文件,可以输出到自己的FileOutputStream

PdfReader reader = null;
        PdfWriter writer = null;
        //获取文件输入流
        FileInputStream is = null;
        try (
                //获取响应输出流
                ServletOutputStream os = response.getOutputStream()
        ) {
            //截取文件名称
            String fileName = path.substring(path.lastIndexOf("\\"));
            //文件下载
            response.setHeader("content-disposition",
                    "attachment;fileName=" + new String(fileName.getBytes("gb2312"), StandardCharsets.ISO_8859_1));

            // 页码为0 下载整个文件
            if (pageNum == 0) {
                is = new FileInputStream(tbSysParamsMapper.selectById("FILEPATH").getValue() + "\\" + path);
                IoUtil.copy(is, os);
            } else {

                reader = new PdfReader(tbSysParamsMapper.selectById("FILEPATH").getValue() + "\\" + path);

                //总页数
                int pageCount = reader.getNumberOfPages();
                if (pageNum > pageCount) {
                    throw new MyException(RespCodeEnum.NOT_HAVE_PAGES);
                }

                Document dd = new Document(reader.getPageSize(pageNum));
                writer = PdfWriter.getInstance(dd, os);
                dd.open();
                PdfContentByte cb = writer.getDirectContent();
                dd.newPage();
                cb.addTemplate(writer.getImportedPage(reader, pageNum), 0, 0);
                dd.close();
                writer.close();
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (writer != null) {
                writer.close();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

你可能感兴趣的:(java,java,开发语言,后端,pdf分页,pdf分割)