• Java导出pdf格式文件


    Java实现导出pdf |word |ppt 格式文件

    controller层

     @ApiOperation("导出")
        @GetMapping("/download")
        public void download(@RequestParam("userId") Long userId ,HttpServletResponse response) {
            reportResultService.generateWordXWPFDocument(userId,response);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    serviceimpi层:

     /**
         * 下载word
         * @param userId
         * @param response
         */
    //    @Override
    //    public void generateWordXWPFDocument(Long userId,HttpServletResponse response) {
    //        try {
    //            XWPFDocument doc = new XWPFDocument();
    //            List<ReportDetail>  ReportDetail = reportResultMapper.reportDetails(userId);
    //            createParagraph(doc, ReportDetail.get(0).getReport());
    //            response.reset();
    //            response.setContentType("application/octet-stream");
    //            response.setHeader("Content-disposition",
    //                    "attachment;filename=user_word_" + System.currentTimeMillis() + ".docx");
    //            OutputStream os = response.getOutputStream();
    //            doc.write(os);
    //            os.close();
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //        }
    //    }
    
        /**
         * 下载pdf
         * @param userId
         * @param response
         */
        @Override
        public void generateWordXWPFDocument(Long userId,HttpServletResponse response) {
            try {
    
                response.reset();
                response.setContentType("application/octet-stream");
                response.setHeader("Content-disposition", "attachment;filename=user_pdf_" + System.currentTimeMillis() + ".pdf");
    
                OutputStream os = response.getOutputStream();
                // document
                com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.A4);
                PdfWriter pdfWriter = PdfWriter.getInstance(document, os);
                // open
                document.open();
                List<ReportDetail> reportDetails = reportResultMapper.reportDetails(userId);
                if (!reportDetails.isEmpty()) {
                    String report = reportDetails.get(0).getReport();
                    document.add(createParagraph(report));
                }
                document.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 下载word
         * @param doc
         * @param content
         */
        private void createParagraph(XWPFDocument doc, String content) {
            XWPFParagraph actType = doc.createParagraph();
            XWPFRun runText2 = actType.createRun();
            runText2.setText(content);
            runText2.setFontSize(11);
            // 设置段落对齐方式
            actType.setAlignment(ParagraphAlignment.CENTER); // 居中对齐
            actType.setVerticalAlignment(TextAlignment.CENTER); // 垂直居中对齐
        }
    
        /**
         * 下载pdf
         * @param content
         * @return
         * @throws IOException
         * @throws DocumentException
         */
        private com.itextpdf.text.Paragraph createParagraph(String content) throws IOException, DocumentException {
            Font font = new Font(getBaseFont(), 12, Font.NORMAL);
            Paragraph paragraph = new Paragraph(content, font);
            paragraph.setAlignment(Element.ALIGN_LEFT);
            paragraph.setIndentationLeft(12); //设置左缩进
            paragraph.setIndentationRight(12); //设置右缩进
            paragraph.setFirstLineIndent(24); //设置首行缩进
            paragraph.setLeading(20f); //行间距
            paragraph.setSpacingBefore(5f); //设置段落上空白
            paragraph.setSpacingAfter(10f); //设置段落下空白
            return paragraph;
        }
    
        private BaseFont getBaseFont() throws IOException, DocumentException {
            return BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92

    或者可以使用以下工具类实现

    package com.zllms.common.utils.poi;
    
    import com.itextpdf.text.*;
    import com.itextpdf.text.pdf.*;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Objects;
    
    /**
     * @Author: wangjj
     * @Date: 2020/11/4 15:53
     * @Description pdf生成工具类
     */
    @Slf4j
    public class PdfCreateUtil {
    
        /**
         * @Author Yangy
         * @Description 创建document
         * @Date 16:24 2020/11/5
         * @Param []
         * @return com.itextpdf.text.Document
         **/
        public static Document getDocumentInstance(){
            //此处方法可以初始化document属性,document默认A4大小
            Document document = new Document();
            return document;
        }
    
        /**
         * @Author Yangy
         * @Description 设置document基本属性
         * @Date 16:24 2020/11/5
         * @Param [document]
         * @return com.itextpdf.text.Document
         **/
        public static Document setDocumentProperties(Document document,String title,String author,String subject,String keywords,String creator){
            // 标题
            document.addTitle(title);
            // 作者
            document.addAuthor(author);
            // 主题
            document.addSubject(subject);
            // 关键字
            document.addKeywords(keywords);
            // 创建者
            document.addCreator(creator);
            return document;
        }
    
        /**
         * @Author Yangy
         * @Description 创建段落,可设置段落通用格式
         * @Date 16:24 2020/11/5
         * @Param []
         * @return com.itextpdf.text.Paragraph
         **/
        public static Paragraph getParagraph(String content,Font fontStyle,int align,int lineIdent,float leading){
            //设置内容与字体样式
            Paragraph p = new Paragraph(content,fontStyle);
            //设置文字居中 0=靠左,1=居中,2=靠右
            p.setAlignment(align);
            //首行缩进
            p.setFirstLineIndent(lineIdent);
            //设置左缩进
    //		p.setIndentationLeft(12);
            //设置右缩进
    //		p.setIndentationRight(12);
            //行间距
            p.setLeading(leading);
            //设置段落上空白
            p.setSpacingBefore(5f);
            //设置段落下空白
            p.setSpacingAfter(10f);
            return p;
        }
    
        /**
         * @Author Yangy
         * @Description 获取图片
         * @Date 16:39 2020/11/5
         * @Param [imgUrl]
         * @return com.itextpdf.text.Image
         **/
        public static Image getImage(String imgUrl,int align,int percent){
            Image image = null;
            try {
                image = Image.getInstance(imgUrl);
            } catch (BadElementException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //设置图片位置
            image.setAlignment(align);
            //依照比例缩放
            image.scalePercent(percent);
            return image;
        }
    
        /**
         * @Author Yangy
         * @Description 创建表格
         * @Date 16:43 2020/11/5
         * @Param [dataList=数据集合,maxWidth=表格最大宽度,align=位置(0,靠左   1,居中     2,靠右)
         * @return com.itextpdf.text.pdf.PdfPTable
         **/
        public static PdfPTable getTable(List<List<String>> dataList,int maxWidth,int align,Font font){
            if(Objects.isNull(dataList) || dataList.size() == 0){
                log.warn("data list is empty when create table");
                return null;
            }
    
            int columns = dataList.get(0).size();
            PdfPTable table = new PdfPTable(columns);
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            //设置列边框
            table.getDefaultCell().setBorder(1);
    
            //此处可自定义表的每列宽度比例,但需要对应列数
    //		int width[] = {10,45,45};//设置每列宽度比例
    //		table.setWidths(width);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
            //边距:单元格的边线与单元格内容的边距
            table.setPaddingTop(1f);
            //间距:单元格与单元格之间的距离
            table.setSpacingBefore(0);
            table.setSpacingAfter(0);
    
            for (int i = 0; i < dataList.size(); i++) {
                for (int j = 0; j < dataList.get(i).size(); j++) {
                    table.addCell(createCell(dataList.get(i).get(j),font));
                }
            }
    
            return table;
        }
    
        /**
         * @Author Yangy
         * @Description 自定义表格列样式属性
         * @Date 16:54 2020/11/5
         * @Param [value, font]
         * @return com.itextpdf.text.pdf.PdfPCell
         **/
        private static PdfPCell createCell(String value, Font font) {
            PdfPCell cell = new PdfPCell();
            //设置列纵向位置,居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            //设置列横向位置,居中
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPhrase(new Phrase(value, font));
            return cell;
        }
    
        /**
         * @Author Yangy
         * @Description 获取自定义字体
         * @Date 11:38 2020/11/6
         * @Param [size=字大小, style=字风格, fontFamily=字体, color=颜色]
         * @return com.itextpdf.text.Font
         **/
        public static Font setFont(float size, int style, String fontFamily, BaseColor color)
                throws IOException, DocumentException {
            //设置中文可用
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new Font(bfChinese,size,style);
            font.setFamily(fontFamily);
            font.setColor(color);
            return font;
        }
    
        /**
         * @Author Yangy
         * @Description 创建水印设置
         * @Date 12:04 2020/11/6
         * @Param [markContent]
         * @return xxx.xxx.data.util.PdfCreateUtil.Watermark
         **/
        public static Watermark createWaterMark(String markContent) throws IOException, DocumentException {
            return new Watermark(markContent);
        }
    
        /**
         * @Author Yangy
         * @Description 设置水印
         * @Date 12:03 2020/11/6
         * @Param
         * @return
         **/
        public static class Watermark extends PdfPageEventHelper {
            Font FONT = PdfCreateUtil.setFont(30f, Font.BOLD, "",new GrayColor(0.95f));
            private String waterCont;//水印内容
    
            public Watermark() throws IOException, DocumentException {
    
            }
    
            public Watermark(String waterCont) throws IOException, DocumentException {
                this.waterCont = waterCont;
            }
    
            @Override
            public void onEndPage(PdfWriter writer, Document document) {
                for (int i = 0; i < 5; i++) {
                    for (int j = 0; j < 5; j++) {
                        ColumnText.showTextAligned(writer.getDirectContentUnder(),
                                Element.ALIGN_CENTER,
                                new Phrase(StringUtils.isEmpty(this.waterCont) ? "" : this.waterCont, FONT),
                                (50.5f + i * 350),
                                (40.0f + j * 150),
                                writer.getPageNumber() % 2 == 1 ? 45 : -45);
                    }
                }
            }
        }
    
        public static HeaderFooter createHeaderFooter(){
            return new HeaderFooter();
        }
    
        /**
         * @Author Yangy
         * @Description 页眉/页脚
         * @Date 12:25 2020/11/6
         * @Param
         * @return
         **/
        public static class HeaderFooter extends PdfPageEventHelper {
            // 总页数
            PdfTemplate totalPage;
            Font hfFont;
            {
                try {
                    hfFont = setFont(8, Font.NORMAL,"",BaseColor.BLACK);
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            // 打开文档时,创建一个总页数的模版
            @Override
            public void onOpenDocument(PdfWriter writer, Document document) {
                PdfContentByte cb =writer.getDirectContent();
                totalPage = cb.createTemplate(30, 16);
            }
    
            // 一页加载完成触发,写入页眉和页脚
            @Override
            public void onEndPage(PdfWriter writer, Document document) {
                PdfPTable table = new PdfPTable(3);
                try {
                    table.setTotalWidth(PageSize.A4.getWidth() - 100);
                    table.setWidths(new int[] { 24, 24, 3});
                    table.setLockedWidth(true);
                    table.getDefaultCell().setFixedHeight(-10);
                    table.getDefaultCell().setBorder(Rectangle.BOTTOM);
    
                    table.addCell(new Paragraph("我是页眉/页脚", hfFont));
                    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
                    table.addCell(new Paragraph("第" + writer.getPageNumber() + "页/", hfFont));
                    // 总页数
                    PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
                    cell.setBorder(Rectangle.BOTTOM);
                    table.addCell(cell);
                    // 将页眉写到document中,位置可以指定,指定到下面就是页脚
                    table.writeSelectedRows(0, -1, 50,PageSize.A4.getHeight() - 20, writer.getDirectContent());
                } catch (Exception de) {
                    throw new ExceptionConverter(de);
                }
            }
    
            // 全部完成后,将总页数的pdf模版写到指定位置
            @Override
            public void onCloseDocument(PdfWriter writer,Document document) {
                String text = "总" + (writer.getPageNumber()) + "页";
                ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,hfFont), 2, 2, 0);
            }
    
        }
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
  • 相关阅读:
    《向量数据库指南》——TruLens + Milvus Cloud 构建RAG案例
    【ArcGIS微课1000例】0031:ArcGIS中的32个拓扑规则(图文详解)
    第1篇 目标检测概述 —(3)YOLO系列算法
    智慧农业:农林牧数据可视化监控平台
    基于SpringBoot蜗牛兼职网的设计与实现【附PPT|万字文档(LW)和搭建文档】
    图G的拉普拉斯矩阵为什么由L=D-A定义
    【Python&图像超分】Real-ESRGAN图像超分模型(超分辨率重建)详细安装和使用教程
    Mysql 通过binlog伪装master恢复数据库
    springboot曦乐苹果园林管理系统的设计与实现毕业设计源码100854
    基于K8S构建Spark镜像-尚硅谷Java培训
  • 原文地址:https://blog.csdn.net/leaning_java/article/details/136256715