Java生成PDF文件,添加图片和表格内容,以及浏览器端下载

本文介绍如何使用Java生成包含Echarts图表和表格内容的PDF文件。首先,通过前端获取64位编码的Echarts图,后台解析并转换为图片,接着将表格数据拼接成字符串传至后台,进行PDF制作并添加内容。
摘要由CSDN通过智能技术生成

页面内容含有表格、echarts图;生成PDF文件报表

思路:先把页面的echarts图的64位获取,后台进行解析echarts图,生成图片,然后在添加到PDF文件中;

表格内容获取,可以根据标签获取标签内容,进行字符串拼接,然后把所有字符串数据传到后台进行逻辑处理,再进行PDF制作,内容添加

上面是一个思路,下面我们进行代码实现

这是页面代码,我只是简单的布局一下,思路是这样的:把页面所有的数据都拼接成有规律的字符串,传递到后台逻辑方法里面进行处理,

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="modo" uri="/WEB-INF/custom-tld/urltag.tld" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>pdf报表图文生成</title>
    <meta name="renderer" content="webkit"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE">
    <%@ include file="../system/allresources.jsp" %>
    <link rel="stylesheet" href="${ctp}/static/scripts/util/layui/css/layui.css"/>
    <link rel="stylesheet" href="${ctp}/static/scripts/util/layui/css/modules/laydate             /default/laydate.css" media="all">
    <script src="${ctp}/static/scripts/util/layui/lay/modules/laydate.js" type="text/javascript"></script>
</head>

<body >

<%--生成pdf文件的按钮--%>
<div onclick="makePDF_rank()"> 生成pdf报表
</div>
<%--用于获取echarts图的base64编码--%>
<form id="chartForm" style="display:none">
    <input id="imageValue" name="base64Info" type="text" maxlength="500000"/>
    <input id="imageValue01" name="base64Info1" type="text" maxlength="50000"/>
    <input id="imageValue02" name="base64Info2" type="text" maxlength="50000"/>
    <input id="imageValue03" name="base64Info3" type="text" maxlength="50000"/>
    <input id="imageValue04" name="base64Info4" type="text" maxlength="50000"/>
    <input id="imageValue05" name="base64Info5" type="text" maxlength="50000"/>
    <input id="imageValue06" name="base64Info6" type="text" maxlength="50000"/>

    <input id="ds1" name="TBDS1" type="text" maxlength="50000"/>
    <input id="ds2" name="TBDS2" type="text" maxlength="50000"/>
    <input id="dataes" name="dataes" type="text" maxlength="50000"/>
    <input id="tableData" name="tableData" type="text" maxlength="50000"/>

</form>






<div style="height:auto;width:100vw;padding-bottom:5vh;">
    <div class="content">
    

        <div >
            <table class="layui-table">
                <colgroup>
                    <col width="18%">
                    <col>
                </colgroup>
                <thead>
                <tr>
                    <th rowspan="2">项目</th>
                    <th colspan="3">营业收入总额</th>
                    <th colspan="3">纳税总额</th>
                </tr>
                <tr>
                    <th class="th1"></th>
                    <th>上年同期</th>
                    <th>同比(%)</th>
                    <th class="th1"></th>
                    <th>上年同期</th>
                    <th>同比(%)</th>
                </tr>


 
                 <tr>
                    <td>data1</td>
                    <td>data2</td>
                    <td>data3</td>
                    <td >data4</td>
                    <td>data5</td>
                    <td>data6</td>
                </tr>
                </thead>
                <tbody style="color:#000">
               <tr>
                    <td>data1</td>
                    <td>data2</td>
                    <td>data3</td>
                    <td >data4</td>
                    <td>data5</td>
                    <td>data6</td>
                </tr>
             
                </tbody>
            </table>
            <table class="layui-table">
                <colgroup>
                    <col width="18%">
                    <col>
                </colgroup>
                <thead>
                <tr>
                    <th rowspan="2">项目</th>
                    <th colspan="3">营业收入总额</th>
                    <th colspan="3">纳税总额</th>
                </tr>
                <tr>
                    <th class="th1"></th>
                    <th>上年同期</th>
                    <th>同比(%)</th>
                    <th class="th1"></th>
                    <th>上年同期</th>
                    <th>同比(%)</th>
                </tr>


 
                 <tr>
                    <td>data1</td>
                    <td>data2</td>
                    <td>data3</td>
                    <td >data4</td>
                    <td>data5</td>
                    <td>data6</td>
                </tr>
                </thead>
                <tbody style="color:#000">
               <tr>
                    <td>data1</td>
                    <td>data2</td>
                    <td>data3</td>
                    <td >data4</td>
                    <td>data5</td>
                    <td>data6</td>
                </tr>
             
                </tbody>
            </table>

            <div style="width:42vw;height:30vh;display:inline-block" id="incomeDiv">

            </div>
            <div style="width:42vw;height:30vh;display:inline-block;" id="dutyDiv">

            </div>
            <div style="width:28vw;height:30vh;display:inline-block;" id="assetsDiv">

            </div>
            <div style="width:28vw;height:30vh;display:inline-block;" id="profitDiv">

            </div>
            <div style="width:28vw;height:30vh;display:inline-block;" id="debtDiv">

            </div>

        


     
        </div>


  


</body>

<script>

   
  
    function report() {

   

   

    var incomeDiv_2 = echarts.init(document.getElementById("incomeDiv_2"));
    var dutyDiv_2 = echarts.init(document.getElementById("dutyDiv_2"));
    var assetsDiv_2 = echarts.init(document.getElementById("assetsDiv_2"));
    var profitDiv_2 = echarts.init(document.getElementById("profitDiv_2"));
    var debtDiv_2 = echarts.init(document.getElementById("debtDiv_2"));
   
             
        

    }

   

        chart.setOption(option);
    }

    
    var incomeDiv;
    var dutyDiv;
    var assetsDiv;
    var profitDiv;
    var debtDiv;
   

    //调用生成PDF的方法,把本页面的echarts 图的64位码传输过去,并生成图片添加到PDF文件中
    function makePDF_rank() {
        //查询年度
        var StartDate = $("#StartDate").val();


        var chartExportUrl = '${ctp }/rankController/makePdfFile_rank';
        //饼图
        var bingPic1 = incomeDiv.getDataURL();//获取echarts图的base64编码,为png格式。
        var bingPic2 = dutyDiv.getDataURL();//获取echarts图的base64编码,为png格式。
        var bingPic3 = assetsDiv.getDataURL();//获取echarts图的base64编码,为png格式。
        var bingPic4 = prof
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个通过Word模板生成DOCX文件并转换为PDF,并提供浏览器下载Java代码示例: ```java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.docx4j.Docx4J; import org.docx4j.convert.out.pdf.PdfConversion; import org.docx4j.convert.out.pdf.viaXSLFO.ConversionOptions; import org.docx4j.fonts.IdentityPlusMapper; import org.docx4j.fonts.Mapper; import org.docx4j.model.structure.PageSizePaper; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart; import org.docx4j.wml.CTBorder; import org.docx4j.wml.CTBorderPr; import org.docx4j.wml.CTTbl; import org.docx4j.wml.CTTblBorders; import org.docx4j.wml.CTTblGrid; import org.docx4j.wml.CTTblLayoutType; import org.docx4j.wml.CTTblPr; import org.docx4j.wml.CTTblWidth; import org.docx4j.wml.ObjectFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WordToPdfController { @RequestMapping(value = "/word-to-pdf", method = RequestMethod.GET) public void generatePdf(HttpServletResponse response) throws Exception { // 获取Word模板文件 File templateFile = new File("template.docx"); FileInputStream in = new FileInputStream(templateFile); // 替换Word中的变量 Map<String, String> variables = new HashMap<>(); variables.put("name", "John Doe"); variables.put("age", "30"); variables.put("address", "123 Main Street"); byte[] docxBytes = replaceVariables(in, variables); // 将DOCX文件转换为PDF byte[] pdfBytes = convertToPdf(docxBytes); // 设置响应头 response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=output.pdf"); // 将PDF文件写入响应体 OutputStream out = response.getOutputStream(); out.write(pdfBytes); out.flush(); out.close(); } private byte[] replaceVariables(InputStream in, Map<String, String> variables) throws Exception { // 加载Word模板文件 WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(in); MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart(); // 获取文档中的所有段落和表格 java.util.List<Object> paragraphsAndTables = documentPart.getContent(); // 遍历文档中的所有段落和表格 for(Object paragraphOrTable : paragraphsAndTables) { if(paragraphOrTable instanceof XWPFParagraph) { // 如果是段落,则替换其中的变量 XWPFParagraph paragraph = (XWPFParagraph) paragraphOrTable; for(XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if(text != null) { for(Map.Entry<String, String> entry : variables.entrySet()) { if(text.contains(entry.getKey())) { text = text.replace(entry.getKey(), entry.getValue()); run.setText(text, 0); } } } } } else if(paragraphOrTable instanceof XWPFTable) { // 如果是表格,则遍历其中的单元格并替换其中的变量 XWPFTable table = (XWPFTable) paragraphOrTable; for(XWPFTableRow row : table.getRows()) { for(XWPFTableCell cell : row.getTableCells()) { for(XWPFParagraph paragraph : cell.getParagraphs()) { for(XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if(text != null) { for(Map.Entry<String, String> entry : variables.entrySet()) { if(text.contains(entry.getKey())) { text = text.replace(entry.getKey(), entry.getValue()); run.setText(text, 0); } } } } } } } } } // 将修改后的文档保存为字节数组 ByteArrayOutputStream out = new ByteArrayOutputStream(); Docx4J.save(wordMLPackage, out); return out.toByteArray(); } private byte[] convertToPdf(byte[] docxBytes) throws Exception { // 加载DOCX文件 ByteArrayInputStream in = new ByteArrayInputStream(docxBytes); WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(in); // 设置字体映射 Mapper fontMapper = new IdentityPlusMapper(); wordMLPackage.setFontMapper(fontMapper); // 设置页面大小和边距 PageSizePaper pageSizePaper = new PageSizePaper(); pageSizePaper.setCode("A4"); wordMLPackage.getDocumentModel().getSections().get(0).getPageDimensions().setPageSize(pageSizePaper); wordMLPackage.getDocumentModel().getSections().get(0).getPageDimensions().setMarginTop(1440); wordMLPackage.getDocumentModel().getSections().get(0).getPageDimensions().setMarginBottom(1440); wordMLPackage.getDocumentModel().getSections().get(0).getPageDimensions().setMarginLeft(1440); wordMLPackage.getDocumentModel().getSections().get(0).getPageDimensions().setMarginRight(1440); // 获取文档中的所有表格 java.util.List<Object> tables = wordMLPackage.getMainDocumentPart().getContent(); for (Object obj : tables) { if (obj instanceof javax.xml.bind.JAXBElement && ((javax.xml.bind.JAXBElement<?>) obj).getDeclaredType().getName().equals("org.docx4j.wml.Tbl")) { javax.xml.bind.JAXBElement<org.docx4j.wml.Tbl> element = (javax.xml.bind.JAXBElement<org.docx4j.wml.Tbl>) obj; org.docx4j.wml.Tbl table = element.getValue(); // 设置表格边框 CTTbl ctTbl = table.getCTTbl(); CTTblPr tblPr = ctTbl.getTblPr(); if (tblPr == null) { tblPr = new CTTblPr(); ctTbl.setTblPr(tblPr); } CTTblBorders borders = tblPr.getTblBorders(); if (borders == null) { borders = new CTTblBorders(); tblPr.setTblBorders(borders); } CTBorder border = new CTBorder(); border.setColor("#000000"); border.setSz(new BigInteger("2")); CTBorderPr borderPr = new CTBorderPr(); borderPr.setTop(border); borderPr.setBottom(border); borderPr.setLeft(border); borderPr.setRight(border); borders.setTop(borderPr); borders.setBottom(borderPr); borders.setLeft(borderPr); borders.setRight(borderPr); // 设置表格宽度 CTTblGrid tblGrid = ctTbl.getTblGrid(); if (tblGrid == null) { tblGrid = new CTTblGrid(); ctTbl.setTblGrid(tblGrid); } for (int i = 0; i < table.getContent().size(); i++) { Object row = table.getContent().get(i); if (row instanceof javax.xml.bind.JAXBElement && ((javax.xml.bind.JAXBElement<?>) row).getDeclaredType().getName().equals("org.docx4j.wml.Tr")) { javax.xml.bind.JAXBElement<org.docx4j.wml.Tr> rowElement = (javax.xml.bind.JAXBElement<org.docx4j.wml.Tr>) row; org.docx4j.wml.Tr tr = rowElement.getValue(); for (int j = 0; j < tr.getContent().size(); j++) { Object cell = tr.getContent().get(j); if (cell instanceof javax.xml.bind.JAXBElement && ((javax.xml.bind.JAXBElement<?>) cell).getDeclaredType().getName().equals("org.docx4j.wml.Tc")) { javax.xml.bind.JAXBElement<org.docx4j.wml.Tc> cellElement = (javax.xml.bind.JAXBElement<org.docx4j.wml.Tc>) cell; org.docx4j.wml.Tc tc = cellElement.getValue(); CTTblWidth tblWidth = new CTTblWidth(); tblWidth.setType("dxa"); tblWidth.setW(BigInteger.valueOf(1000)); tc.getTcPr().setTcW(tblWidth); } } } } } } // 将文档转换为PDF ConversionOptions conversionOptions = new ConversionOptions(); conversionOptions.setQuality(PdfConversionQualityEnum.PDF_A_1_B); OutputStream out = new ByteArrayOutputStream(); PdfConversion converter = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage); converter.output(out, conversionOptions); return ((ByteArrayOutputStream) out).toByteArray(); } } ``` 在上述代码中,我们首先通过`replaceVariables()`方法将Word模板中的变量替换为实际值,然后通过`convertToPdf()`方法将DOCX文件转换为PDF。最后,我们将PDF文件写入响应体并设置响应头,使得浏览器可以下载文件。注意,这里我们使用了`docx4j`和`poi`两个开源库来处理Word和PDF文件
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值