亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java實(shí)現(xiàn)導(dǎo)出pdf格式文件的示例代碼

 更新時(shí)間:2024年02月25日 16:55:10   作者:@卓越俊逸_角立杰出@  
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)導(dǎo)出pdf格式文件的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

Java實(shí)現(xiàn)導(dǎo)出pdf |word |ppt 格式文件

controller層:

 @ApiOperation("導(dǎo)出")
    @GetMapping("/download")
    public void download(@RequestParam("userId") Long userId ,HttpServletResponse response) {
        reportResultService.generateWordXWPFDocument(userId,response);
    }

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);
        // 設(shè)置段落對(duì)齊方式
        actType.setAlignment(ParagraphAlignment.CENTER); // 居中對(duì)齊
        actType.setVerticalAlignment(TextAlignment.CENTER); // 垂直居中對(duì)齊
    }

    /**
     * 下載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); //設(shè)置左縮進(jìn)
        paragraph.setIndentationRight(12); //設(shè)置右縮進(jìn)
        paragraph.setFirstLineIndent(24); //設(shè)置首行縮進(jìn)
        paragraph.setLeading(20f); //行間距
        paragraph.setSpacingBefore(5f); //設(shè)置段落上空白
        paragraph.setSpacingAfter(10f); //設(shè)置段落下空白
        return paragraph;
    }

    private BaseFont getBaseFont() throws IOException, DocumentException {
        return BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    }

或者可以使用以下工具類(lèi)實(shí)現(xiàn)

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生成工具類(lèi)
 */
@Slf4j
public class PdfCreateUtil {

    /**
     * @Author Yangy
     * @Description 創(chuàng)建document
     * @Date 16:24 2020/11/5
     * @Param []
     * @return com.itextpdf.text.Document
     **/
    public static Document getDocumentInstance(){
        //此處方法可以初始化document屬性,document默認(rèn)A4大小
        Document document = new Document();
        return document;
    }

    /**
     * @Author Yangy
     * @Description 設(shè)置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){
        // 標(biāo)題
        document.addTitle(title);
        // 作者
        document.addAuthor(author);
        // 主題
        document.addSubject(subject);
        // 關(guān)鍵字
        document.addKeywords(keywords);
        // 創(chuàng)建者
        document.addCreator(creator);
        return document;
    }

    /**
     * @Author Yangy
     * @Description 創(chuàng)建段落,可設(shè)置段落通用格式
     * @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){
        //設(shè)置內(nèi)容與字體樣式
        Paragraph p = new Paragraph(content,fontStyle);
        //設(shè)置文字居中 0=靠左,1=居中,2=靠右
        p.setAlignment(align);
        //首行縮進(jìn)
        p.setFirstLineIndent(lineIdent);
        //設(shè)置左縮進(jìn)
//		p.setIndentationLeft(12);
        //設(shè)置右縮進(jìn)
//		p.setIndentationRight(12);
        //行間距
        p.setLeading(leading);
        //設(shè)置段落上空白
        p.setSpacingBefore(5f);
        //設(shè)置段落下空白
        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();
        }
        //設(shè)置圖片位置
        image.setAlignment(align);
        //依照比例縮放
        image.scalePercent(percent);
        return image;
    }

    /**
     * @Author Yangy
     * @Description 創(chuàng)建表格
     * @Date 16:43 2020/11/5
     * @Param [dataList=數(shù)據(jù)集合,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);
        //設(shè)置列邊框
        table.getDefaultCell().setBorder(1);

        //此處可自定義表的每列寬度比例,但需要對(duì)應(yīng)列數(shù)
//		int width[] = {10,45,45};//設(shè)置每列寬度比例
//		table.setWidths(width);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
        //邊距:單元格的邊線與單元格內(nèi)容的邊距
        table.setPaddingTop(1f);
        //間距:?jiǎn)卧衽c單元格之間的距離
        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();
        //設(shè)置列縱向位置,居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        //設(shè)置列橫向位置,居中
        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=字風(fēng)格, fontFamily=字體, color=顏色]
     * @return com.itextpdf.text.Font
     **/
    public static Font setFont(float size, int style, String fontFamily, BaseColor color)
            throws IOException, DocumentException {
        //設(shè)置中文可用
        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 創(chuàng)建水印設(shè)置
     * @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 設(shè)置水印
     * @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;//水印內(nèi)容

        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 頁(yè)眉/頁(yè)腳
     * @Date 12:25 2020/11/6
     * @Param
     * @return
     **/
    public static class HeaderFooter extends PdfPageEventHelper {
        // 總頁(yè)數(shù)
        PdfTemplate totalPage;
        Font hfFont;
        {
            try {
                hfFont = setFont(8, Font.NORMAL,"",BaseColor.BLACK);
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 打開(kāi)文檔時(shí),創(chuàng)建一個(gè)總頁(yè)數(shù)的模版
        @Override
        public void onOpenDocument(PdfWriter writer, Document document) {
            PdfContentByte cb =writer.getDirectContent();
            totalPage = cb.createTemplate(30, 16);
        }

        // 一頁(yè)加載完成觸發(fā),寫(xiě)入頁(yè)眉和頁(yè)腳
        @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("我是頁(yè)眉/頁(yè)腳", hfFont));
                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
                table.addCell(new Paragraph("第" + writer.getPageNumber() + "頁(yè)/", hfFont));
                // 總頁(yè)數(shù)
                PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
                cell.setBorder(Rectangle.BOTTOM);
                table.addCell(cell);
                // 將頁(yè)眉寫(xiě)到document中,位置可以指定,指定到下面就是頁(yè)腳
                table.writeSelectedRows(0, -1, 50,PageSize.A4.getHeight() - 20, writer.getDirectContent());
            } catch (Exception de) {
                throw new ExceptionConverter(de);
            }
        }

        // 全部完成后,將總頁(yè)數(shù)的pdf模版寫(xiě)到指定位置
        @Override
        public void onCloseDocument(PdfWriter writer,Document document) {
            String text = "總" + (writer.getPageNumber()) + "頁(yè)";
            ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,hfFont), 2, 2, 0);
        }

    }


}

到此這篇關(guān)于Java實(shí)現(xiàn)導(dǎo)出pdf格式文件的示例代碼的文章就介紹到這了,更多相關(guān)Java導(dǎo)出pdf內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot服務(wù)器端解決跨域問(wèn)題

    SpringBoot服務(wù)器端解決跨域問(wèn)題

    這篇文章主要介紹了SpringBoot服務(wù)器端解決跨域問(wèn)題,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下
    2020-11-11
  • Mybatis+Druid+MybatisPlus多數(shù)據(jù)源配置方法

    Mybatis+Druid+MybatisPlus多數(shù)據(jù)源配置方法

    在項(xiàng)目開(kāi)發(fā)中,經(jīng)常需要連接多個(gè)數(shù)據(jù)庫(kù),使用Mybatis、Druid和MybatisPlus可以實(shí)現(xiàn)多數(shù)據(jù)源配置,通過(guò)定義配置類(lèi)和修改配置文件,如properties或yaml,可以設(shè)置多個(gè)數(shù)據(jù)源,本文介紹了配置項(xiàng)包括Druid基本配置、數(shù)據(jù)源一、數(shù)據(jù)源二,感興趣的朋友一起看看吧
    2024-09-09
  • 詳解Java打包鏡像部署

    詳解Java打包鏡像部署

    這篇文章主要介紹了Java打包鏡像部署,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2023-11-11
  • 心動(dòng)嗎?正大光明的免費(fèi)使用IntelliJ IDEA商業(yè)版

    心動(dòng)嗎?正大光明的免費(fèi)使用IntelliJ IDEA商業(yè)版

    這篇文章主要介紹了正大光明的免費(fèi)使用IntelliJ IDEA商業(yè)版,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2020-02-02
  • Java刷題之最小k個(gè)數(shù)的思路及具體實(shí)現(xiàn)

    Java刷題之最小k個(gè)數(shù)的思路及具體實(shí)現(xiàn)

    這篇文章主要介紹了Java刷題之最小k個(gè)數(shù)的思路及具體實(shí)現(xiàn),最小K個(gè)數(shù)是一個(gè)經(jīng)典的top-K問(wèn)題,可以通過(guò)整體排序、建立小根堆或大根堆的方式解決,排序方式時(shí)間復(fù)雜度較高,適合數(shù)據(jù)量小的場(chǎng)景,小根堆適合k較小的情況,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-10-10
  • Spring?Cloud?Sleuth?和?Zipkin?進(jìn)行分布式跟蹤使用小結(jié)

    Spring?Cloud?Sleuth?和?Zipkin?進(jìn)行分布式跟蹤使用小結(jié)

    分布式跟蹤是一種機(jī)制,我們可以使用它跟蹤整個(gè)分布式系統(tǒng)中的特定請(qǐng)求,分布式跟蹤允許您跟蹤分布式系統(tǒng)中的請(qǐng)求,本文給大家介紹Spring?Cloud?Sleuth?和?Zipkin?進(jìn)行分布式跟蹤使用小結(jié),感興趣的朋友一起看看吧
    2022-03-03
  • Java集合快速失敗與安全失敗解析

    Java集合快速失敗與安全失敗解析

    這篇文章主要介紹了Java集合快速失敗與安全失敗解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • Java8 新特性Lambda表達(dá)式實(shí)例詳解

    Java8 新特性Lambda表達(dá)式實(shí)例詳解

    這篇文章主要介紹了Java8 新特性Lambda表達(dá)式實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • SpringBoot+Mybatis-plus+shardingsphere實(shí)現(xiàn)分庫(kù)分表的方案

    SpringBoot+Mybatis-plus+shardingsphere實(shí)現(xiàn)分庫(kù)分表的方案

    實(shí)現(xiàn)億級(jí)數(shù)據(jù)量分庫(kù)分表的項(xiàng)目是一個(gè)挑戰(zhàn)性很高的任務(wù),下面是一個(gè)基于Spring Boot的簡(jiǎn)單實(shí)現(xiàn)方案,感興趣的朋友一起看看吧
    2024-03-03
  • SpringBoot測(cè)試類(lèi)注入Bean失敗的原因及分析

    SpringBoot測(cè)試類(lèi)注入Bean失敗的原因及分析

    SpringBoot 2.2版本前后測(cè)試類(lèi)有所變化,2.2版本之后使用JUnit 5,導(dǎo)入注解@SpringBootTest和@Test來(lái)自junit.jupiter.api包;而2.2版本之前使用JUnit 4,需要額外導(dǎo)入@RunWith注解來(lái)自junit.runner包,無(wú)論哪個(gè)版本,都需確保測(cè)試類(lèi)和啟動(dòng)類(lèi)的包名一致
    2024-09-09

最新評(píng)論