jFinal+itextpdf5.5.8导出pdf

本文介绍了如何在Java项目中使用itextpdf5.5.8处理中文,包括引入字体、创建Document对象,以及生成包含中文表单的PDF文件,供前端下载。
摘要由CSDN通过智能技术生成

首先,确保项目中导入了itextpdf5.5.8的jar包,如果是maven的话,确保引入了itextpdf的依赖

由于itextpdf5.5.8的版本中对中文是不支持的,如果pdf中存在中文的话需要引入字体,可以百度一些免费的商用字体,可以在这里面下载ttf文件到项目中

首先创建document对象

        Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ServletContext servletContext = getRequest().getServletContext();
Font chineseFont = fontUtils(servletContext, "/fonts/HanZiZhiMeiFangSongGBK-MianFei(God-FangSongGBK-free)-2.ttf");

 然后通过ByteArrayOutPutStream写入字节数组中,ByteArrayOutPutStream是输出流写入一个内部字节数组的一个类。当你想将数据先存储在内存中,而不是直接写入文件或网络时,它非常有用。获取servletContext上下文,通过fontUtils将中文字体设置出来

private Font fontUtils(ServletContext servletContext, String fontFilePath) throws IOException, DocumentException {
        InputStream is = servletContext.getResourceAsStream(fontFilePath);
        if (is == null) {
            throw new IOException("Font file not found at path: " + fontFilePath);
        }
        // 创建一个临时文件来存储字体文件
        File tempFile = File.createTempFile("font", ".ttf");
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            // 如果创建临时文件或写入时发生错误,删除可能已创建的临时文件
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
            throw e; // 重新抛出异常
        } finally {
            if (is != null) {
                is.close();
            }
        }
        // 关闭输入流
        is.close();
        // 使用临时文件的路径创建BaseFont对象
        String fontPath = tempFile.getAbsolutePath();
        BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        boolean deleted = tempFile.delete();
        if (!deleted) {
            // 如果删除失败,您可以选择记录一个警告或抛出异常
            log.warn("Unable to delete temporary font file: " + tempFile.getAbsolutePath());
        }
        // 创建并返回Font对象
        return new Font(baseFont, 12, Font.NORMAL);

    }
}
try {
            PdfWriter instance = PdfWriter.getInstance(document, baos);
            document.open();
             Paragraph numberParagraph = new Paragraph("编号: " +                     formRecords.getStr("number"),chineseFont);
            document.add(numberParagraph);
            document.add(new Chunk(Chunk.NEWLINE)); // 添加新行
//这是pdf中一个form表单的部分
document.add(currencyParagraph);
            document.add(new Chunk(Chunk.NEWLINE)); // 添加新行
            PdfPTable table = new PdfPTable(customHeaders.length);
            for (String headerText : customHeaders) {
                PdfPCell headerCell = new PdfPCell(new Phrase(headerText, chineseFont)); // 使用中文字体
                headerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(headerCell);
            }
            BigDecimal totalPrice = BigDecimal.ZERO;
            for (Record record : tableRecords) {
                // 使用中文字体创建单元格内容
                table.addCell(new Phrase(record.getStr("artno"), chineseFont));
                
            }
           // 将表格添加到PDF文档中
            document.add(table);
            document.close();
            byte[] pdfBytes = baos.toByteArray();
            HttpServletResponse response = getResponse();
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=report.pdf");
            response.setContentLength(pdfBytes.length);
            try (ServletOutputStream os = response.getOutputStream()) {
                os.write(pdfBytes);
                os.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

通过以上代码可以实现生成pdf前端进行下载

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面我将为您提供一个简单的demo示例,使用jfinal+vue+el来实现一个用户管理系统。 1. 准备工作 首先,需要安装Java环境和Maven工具。然后,创建一个Maven项目,并添加以下依赖: ```xml <dependency> <groupId>com.jfinal</groupId> <artifactId>jfinal</artifactId> <version>4.9.06</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> ``` 2. 创建数据库表 在MySQL中创建一个名为user的表,包含以下字段: - id - username - password - nickname - email 3. 创建后端代码 创建一个UserController类,用于处理用户相关的请求。 ```java public class UserController extends Controller { public void index() { render("index.html"); } public void list() { int pageNumber = getParaToInt("page"); int pageSize = getParaToInt("limit"); Page<User> userList = User.dao.paginate(pageNumber, pageSize, "select *", "from user"); renderJson(JSON.toJSONString(userList)); } public void save() { User user = getModel(User.class, ""); if (user.save()) { renderJson(JSON.toJSONString(Result.success())); } else { renderJson(JSON.toJSONString(Result.failure("保存失败"))); } } public void update() { User user = getModel(User.class, ""); if (user.update()) { renderJson(JSON.toJSONString(Result.success())); } else { renderJson(JSON.toJSONString(Result.failure("更新失败"))); } } public void delete() { Integer id = getParaToInt("id"); if (User.dao.deleteById(id)) { renderJson(JSON.toJSONString(Result.success())); } else { renderJson(JSON.toJSONString(Result.failure("删除失败"))); } } } ``` 创建一个User类,用于操作数据库。 ```java public class User extends Model<User> { public static final User dao = new User().dao(); public Integer getId() { return getInt("id"); } public void setId(Integer id) { set("id", id); } public String getUsername() { return getStr("username"); } public void setUsername(String username) { set("username", username); } public String getPassword() { return getStr("password"); } public void setPassword(String password) { set("password", password); } public String getNickname() { return getStr("nickname"); } public void setNickname(String nickname) { set("nickname", nickname); } public String getEmail() { return getStr("email"); } public void setEmail(String email) { set("email", email); } } ``` 4. 创建前端代码 创建一个index.html文件,用于展示用户列表和添加用户。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>User Management System</title> <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.15.1/theme-chalk/index.css"> </head> <body> <div id="app"> <el-container> <el-header> <h1 style="color: white">用户管理系统</h1> </el-header> <el-main> <el-table :data="userList" border style="width: 100%"> <el-table-column label="ID" prop="id"></el-table-column> <el-table-column label="用户名" prop="username"></el-table-column> <el-table-column label="昵称" prop="nickname"></el-table-column> <el-table-column label="邮箱" prop="email"></el-table-column> <el-table-column label="操作"> <template slot-scope="scope"> <el-button type="primary" @click="editUser(scope.row)">编辑</el-button> <el-button type="danger" @click="deleteUser(scope.row)">删除</el-button> </template> </el-table-column> </el-table> <el-pagination :total="total" :page-size="pageSize" :current-page.sync="currentPage" @current-change="getPage"></el-pagination> <el-form :model="user" ref="userForm" label-width="80px" style="margin-top: 20px;"> <el-form-item label="用户名" prop="username"> <el-input v-model="user.username" placeholder="请输入用户名"></el-input> </el-form-item> <el-form-item label="密码" prop="password"> <el-input v-model="user.password" placeholder="请输入密码"></el-input> </el-form-item> <el-form-item label="昵称" prop="nickname"> <el-input v-model="user.nickname" placeholder="请输入昵称"></el-input> </el-form-item> <el-form-item label="邮箱" prop="email"> <el-input v-model="user.email" placeholder="请输入邮箱"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="saveUser">保存</el-button> <el-button @click="resetForm">重置</el-button> </el-form-item> </el-form> </el-main> </el-container> </div> <script src="https://cdn.staticfile.org/vue/2.6.14/vue.min.js"></script> <script src="https://cdn.staticfile.org/element-ui/2.15.1/index.js"></script> <script src="https://cdn.staticfile.org/axios/0.21.1/axios.min.js"></script> <script type="text/javascript"> new Vue({ el: '#app', data: { userList: [], total: 0, pageSize: 10, currentPage: 1, user: { username: '', password: '', nickname: '', email: '' } }, created: function () { this.getPage(1); }, methods: { getPage: function (page) { let _this = this; axios.get('/user/list', { params: { page: page, limit: _this.pageSize } }).then(function (response) { _this.userList = response.data.list; _this.total = response.data.total; }).catch(function (error) { console.log(error); }); }, editUser: function (row) { this.user = row; }, deleteUser: function (row) { let _this = this; let id = row.id; axios.post('/user/delete', { id: id }).then(function (response) { _this.getPage(_this.currentPage); }).catch(function (error) { console.log(error); }); }, saveUser: function () { let _this = this; this.$refs.userForm.validate(function (valid) { if (valid) { axios.post('/user/save', _this.user).then(function (response) { _this.getPage(_this.currentPage); _this.resetForm('userForm'); }).catch(function (error) { console.log(error); }); } else { return false; } }); }, resetForm: function (formName) { this.$refs[formName].resetFields(); this.user = { username: '', password: '', nickname: '', email: '' }; } } }); </script> </body> </html> ``` 5. 配置路由 在JFinalConfig类中配置路由。 ```java public class DemoConfig extends JFinalConfig { @Override public void configConstant(Constants me) { me.setDevMode(true); } @Override public void configRoute(Routes me) { me.add("/user", UserController.class); } @Override public void configPlugin(Plugins me) { DruidPlugin dp = new DruidPlugin("jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8", "root", "123456"); me.add(dp); ActiveRecordPlugin arp = new ActiveRecordPlugin(dp); me.add(arp); arp.addMapping("user", User.class); } @Override public void configInterceptor(Interceptors me) { } @Override public void configHandler(Handlers me) { } } ``` 6. 运行项目 运行项目,访问http://localhost:8080/user/index即可看到用户管理系统页面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值