若依+lodop+jasperreports+ireport 设计打印票据格式

一、设计表格

官网下载ireport5.6,解压安装,jdk 1.7适配ireport5.6,jdk1.8不适配

安装好jdk1.7(不用配置path,安装好就行),进入ireport5.6安装目录,找到配置文件,配置jdk1.7安装路径

在这里插入图片描述打开软件 选择a4 模板
在这里插入图片描述添加参数studentList ,也就是java 绑定表格数据
在这里插入图片描述选择Table 拖到页面上、表格对应的子数据设置·字段,也就是对应Java 传入studentList对象的属性
注意:属性名和字段类型必须对应
在这里插入图片描述在这里插入图片描述
表格绑定studentList,设置数据类型是集合类型
在这里插入图片描述在这里插入图片描述
选择数据类型为:new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{studentList})

保存文件

二、若依VUE前端

封装lodop.js

import request from "@/utils/request";

var CreatedOKLodop7766 = null

export function needCLodop() {
  try {
    var ua = navigator.userAgent
    if (ua.match(/Windows\sPhone/i) != null) return true
    if (ua.match(/iPhone|iPod/i) != null) return true
    if (ua.match(/Android/i) != null) return true
    if (ua.match(/Edge\D?\d+/i) != null) return true

    var verTrident = ua.match(/Trident\D?\d+/i)
    var verIE = ua.match(/MSIE\D?\d+/i)
    var verOPR = ua.match(/OPR\D?\d+/i)
    var verFF = ua.match(/Firefox\D?\d+/i)
    var x64 = ua.match(/x64/i)
    if (verTrident == null && verIE == null && x64 !== null) return true
    else if (verFF !== null) {
      verFF = verFF[0].match(/\d+/)
      if (verFF[0] >= 41 || x64 !== null) return true
    } else if (verOPR !== null) {
      verOPR = verOPR[0].match(/\d+/)
      if (verOPR[0] >= 32) return true
    } else if (verTrident == null && verIE == null) {
      var verChrome = ua.match(/Chrome\D?\d+/i)
      if (verChrome !== null) {
        verChrome = verChrome[0].match(/\d+/)
        if (verChrome[0] >= 41) return true
      }
    }
    return false
  } catch (err) {
    return true
  }
}

// ====页面引用CLodop云打印必须的JS文件:====
if (needCLodop()) {
  var head =
    document.head ||
    document.getElementsByTagName('head')[0] ||
    document.documentElement
  var oscript = document.createElement('script')
  oscript.src = 'http://localhost:8000/CLodopfuncs.js?priority=1'
  head.insertBefore(oscript, head.firstChild)

  // 引用双端口(8000和18000)避免其中某个被占用:
  oscript = document.createElement('script')
  oscript.src = 'http://localhost:18000/CLodopfuncs.js?priority=0'
  head.insertBefore(oscript, head.firstChild)
}

// ====获取LODOP对象的主过程:====
export function getLodop(oOBJECT, oEMBED) {
  var strHtmInstall =
    "<br><font color='#FF00FF'>打印控件未安装!点击这里<a href='install_lodop32.exe' target='_self'>执行安装</a>,安装后请刷新页面或重新进入。</font>"
  var strHtmUpdate =
    "<br><font color='#FF00FF'>打印控件需要升级!点击这里<a href='install_lodop32.exe' target='_self'>执行升级</a>,升级后请重新进入。</font>"
  var strHtm64_Install =
    "<br><font color='#FF00FF'>打印控件未安装!点击这里<a href='install_lodop64.exe' target='_self'>执行安装</a>,安装后请刷新页面或重新进入。</font>"
  var strHtm64_Update =
    "<br><font color='#FF00FF'>打印控件需要升级!点击这里<a href='install_lodop64.exe' target='_self'>执行升级</a>,升级后请重新进入。</font>"
  var strHtmFireFox =
    "<br><br><font color='#FF00FF'>(注意:如曾安装过Lodop旧版附件npActiveXPLugin,请在【工具】->【附加组件】->【扩展】中先卸它)</font>"
  var strHtmChrome =
    "<br><br><font color='#FF00FF'>(如果此前正常,仅因浏览器升级或重安装而出问题,需重新执行以上安装)</font>"
  var strCLodopInstall =
    "<br><font color='#FF00FF'>CLodop云打印服务(localhost本地)未安装启动!点击这里<a href='http://www.lodop.net/download/CLodop_Setup_for_Win32NT_https_3.046Extend.zip' download target='_self'>执行安装</a>,安装后请刷新页面。</font>"
  const strCLodopUpdate =
    "<br><font color='#FF00FF'>CLodop云打印服务需升级!点击这里<a href='http://www.lodop.net/download/CLodop_Setup_for_Win32NT_https_3.046Extend.zip' download target='_self'>执行升级</a>,升级后请刷新页面。</font>"
  let LODOP
  try {
    const isIE =
      navigator.userAgent.indexOf('MSIE') >= 0 ||
      navigator.userAgent.indexOf('Trident') >= 0
    if (needCLodop()) {
      try {
        // eslint-disable-next-line no-undef
        LODOP = getCLodop()
        // eslint-disable-next-line no-empty
      } catch (err) {}
      if (!LODOP && document.readyState !== 'complete') {
        alert('C-Lodop没准备好,请稍后再试!')
        return
      }
      if (!LODOP) {
        if (isIE) document.write(strCLodopInstall)
        else {
          document.body.innerHTML =
            strCLodopInstall + document.body.innerHTML
        }
        return
      } else {
        // eslint-disable-next-line no-undef
        if (CLODOP.CVERSION < '3.0.4.3') {
          if (isIE) document.write(strCLodopUpdate)
          else {
            document.body.innerHTML =
              strCLodopUpdate + document.body.innerHTML
          }
        }
        if (oEMBED && oEMBED.parentNode) { oEMBED.parentNode.removeChild(oEMBED) }
        if (oOBJECT && oOBJECT.parentNode) { oOBJECT.parentNode.removeChild(oOBJECT) }
      }
    } else {
      var is64IE = isIE && navigator.userAgent.indexOf('x64') >= 0
      // =====如果页面有Lodop就直接使用,没有则新建:==========
      // eslint-disable-next-line eqeqeq
      if (oOBJECT != undefined || oEMBED != undefined) {
        if (isIE) LODOP = oOBJECT
        else LODOP = oEMBED
      } else if (CreatedOKLodop7766 == null) {
        LODOP = document.createElement('object')
        LODOP.setAttribute('width', 0)
        LODOP.setAttribute('height', 0)
        LODOP.setAttribute(
          'style',
          'position:absolute;left:0px;top:-100px;width:0px;height:0px;',
        )
        if (isIE) {
          LODOP.setAttribute(
            'classid',
            'clsid:2105C259-1E0C-4534-8141-A753534CB4CA',
          )
        } else LODOP.setAttribute('type', 'application/x-print-lodop')
        document.documentElement.appendChild(LODOP)
        CreatedOKLodop7766 = LODOP
      } else LODOP = CreatedOKLodop7766
      // =====Lodop插件未安装时提示下载地址:==========
      if (LODOP == null || typeof LODOP.VERSION === 'undefined') {
        if (navigator.userAgent.indexOf('Chrome') >= 0) {
          document.body.innerHTML =
            strHtmChrome + document.body.innerHTML
        }
        if (navigator.userAgent.indexOf('Firefox') >= 0) {
          document.body.innerHTML =
            strHtmFireFox + document.body.innerHTML
        }
        if (is64IE) document.write(strHtm64_Install)
        else if (isIE) document.write(strHtmInstall)
        else {
          document.body.innerHTML =
            strHtmInstall + document.body.innerHTML
        }
        return LODOP
      }
    }
    if (LODOP.VERSION < '6.2.2.3') {
      if (!needCLodop()) {
        if (is64IE) document.write(strHtm64_Update)
        else if (isIE) document.write(strHtmUpdate)
        else {
          document.body.innerHTML =
            strHtmUpdate + document.body.innerHTML
        }
      }
      return LODOP
    }
    // ===如下空白位置适合调用统一功能(如注册语句、语言选择等):===

    // ===========================================================
    return LODOP
  } catch (err) {
    alert('getLodop出错:' + err)
  }
}

export function getLodopHtml(url,method){
  var timestamp = Date.now();

  if((url+"").indexOf("?")>0){
    url+="&temp=" + timestamp
  }else{
    url+="?temp=" + timestamp
  }

  return request({
    url: url,
    method: method || "get"
  })
}

发送get打印请求方法

**注意:**url中pages对应参数是Java 打印对象(studentPrint)

prints() {
      var url = "/student/prints/ireport/html?pages=studentPrint"
      getLodopHtml(url).then(html =>{
        debugger
        var LODOP = getLodop();
        LODOP.PRINT_INIT("打印控件");
        LODOP.SET_PRINT_PAGESIZE("0", "", "", "");
        LODOP.ADD_PRINT_HTM("0", "0", "100%", "100%", html);
        LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT", "Full-Width");
        // 预览
        LODOP.PREVIEW();
      });

    },

三、若依VUE后端

resource创建文件夹,把刚刚设计好的文件,修改文件内容

language="groovy" 替换为 language="java" 

在这里插入图片描述

修改文件名与前端url 参数pages对应的值一样

然后放入resource创建的文件夹
StudentPrint.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report6" language="java" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="d2147d1b-e498-4342-9a61-51aca874689b">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <style name="table">
        <box>
            <pen lineWidth="1.0" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_TH" mode="Opaque" backcolor="#F0F8FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_CH" mode="Opaque" backcolor="#BFE1FF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <style name="table_TD" mode="Opaque" backcolor="#FFFFFF">
        <box>
            <pen lineWidth="0.5" lineColor="#000000"/>
        </box>
    </style>
    <subDataset name="Table Dataset 1" uuid="49ab48a3-3b84-4d02-9ca0-52a978a6f640">
        <field name="id" class="java.lang.String"/>
        <field name="name" class="java.lang.String"/>
        <field name="sex" class="java.lang.String"/>
        <field name="age" class="java.lang.Integer"/>
    </subDataset>
    <parameter name="studentList" class="java.util.Collection"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="79" splitType="Stretch"/>
    </title>
    <pageHeader>
        <band height="48" splitType="Stretch">
            <componentElement>
                <reportElement key="table" style="table" x="0" y="0" width="555" height="48" uuid="241bca2b-e403-4736-a0e9-252148827565"/>
                <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                    <datasetRun subDataset="Table Dataset 1" uuid="b7959260-d9af-4015-b0b8-e47120ebbd3c">
                        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{studentList})]]></dataSourceExpression>
                    </datasetRun>
                    <jr:column width="90" uuid="46b80cf9-1d45-4eee-b9c7-fcb81541200a">
                        <jr:columnHeader style="table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="90" height="30" uuid="a4d46b08-d7a1-4183-964e-7faa5da73501"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">
                                    <font size="14"/>
                                </textElement>
                                <text><![CDATA[学号]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table_TD" height="20">
                            <textField>
                                <reportElement x="0" y="0" width="90" height="20" uuid="efd3707a-5328-4d53-93e7-4e1e7e582d76"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">
                                    <font size="14"/>
                                </textElement>
                                <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="90" uuid="741b5948-5068-44cd-9c89-773c97cac560">
                        <jr:columnHeader style="table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="90" height="30" uuid="3b94f639-85f4-46bf-84ae-292c7b0db662"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">
                                    <font size="14"/>
                                </textElement>
                                <text><![CDATA[姓名]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table_TD" height="20">
                            <textField>
                                <reportElement x="0" y="0" width="90" height="20" uuid="b04e4c08-c6cb-4024-9579-3862494c6f75"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">
                                    <font size="14"/>
                                </textElement>
                                <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="90" uuid="c4f1be4f-ec3a-4e1b-bb2c-549e6d464aea">
                        <jr:columnHeader style="table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="90" height="30" uuid="79d1c27e-b860-43d2-a28b-8965afcf16c3"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">
                                    <font size="14"/>
                                </textElement>
                                <text><![CDATA[性别]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table_TD" height="20">
                            <textField>
                                <reportElement x="0" y="0" width="90" height="20" uuid="bec7dff1-8dba-4652-a966-1f769aadc370"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">
                                    <font size="14"/>
                                </textElement>
                                <textFieldExpression><![CDATA[$F{sex}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                    <jr:column width="90" uuid="44d43ef9-e618-4c80-82cb-3c986feff9f3">
                        <jr:columnHeader style="table_CH" height="30">
                            <staticText>
                                <reportElement x="0" y="0" width="90" height="30" uuid="6a2b467a-8af4-46d7-b69c-04d5434daea5"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">
                                    <font size="14"/>
                                </textElement>
                                <text><![CDATA[年纪]]></text>
                            </staticText>
                        </jr:columnHeader>
                        <jr:detailCell style="table_TD" height="20">
                            <textField>
                                <reportElement x="0" y="0" width="90" height="20" uuid="ceba60b6-8ac1-4dcc-abe5-bb4801a64b81"/>
                                <textElement textAlignment="Center" verticalAlignment="Middle">
                                    <font size="14"/>
                                </textElement>
                                <textFieldExpression><![CDATA[$F{age}]]></textFieldExpression>
                            </textField>
                        </jr:detailCell>
                    </jr:column>
                </jr:table>
            </componentElement>
        </band>
    </pageHeader>
    <columnHeader>
        <band height="61" splitType="Stretch"/>
    </columnHeader>
    <detail>
        <band height="125" splitType="Stretch"/>
    </detail>
    <columnFooter>
        <band height="45" splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="54" splitType="Stretch"/>
    </pageFooter>
    <summary>
        <band height="42" splitType="Stretch"/>
    </summary>
</jasperReport>

注意: 文件里面是 language=“java”
jasperreports.properties

net.sf.jasperreports.awt.ignore.missing.font=true

Java 打印配置
在这里插入图片描述

StudentPrint.java

@Component
public class StudentPrint implements IHandler {

    protected Logger logger = LoggerFactory.getLogger(StudentPrint.class);

    @Autowired
    private IHCrkService hCrkService;

    /**
     * 如果不设置的话 那么就取默认的
     *
     * @param setting
     * @return
     */
    @Override
    public void getPrintSetting(PrintSetting setting) {
    }

    @Override
    public void getParameters(Map<String, Object> map, Map<String, Object> response)  {
        try{
            List<Student> list = new ArrayList<>();
            for (int i = 0; i < 5 ; i++) {
                Student student = new Student(i+"","王"+i,"男",i);
                list.add(student);
            };
            response.put("studentList",list);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("打印失败:{}",e.getMessage());
        }
    }
    /**
     * 获取Field参数
     *
     * @param request
     * @param records
     */
    @Override
    public void getFields(Map<String, Object> request, List<Map<String, Object>> records) {
    }
}

StudentPrintController.java

@RestController
@RequestMapping("/student/prints/ireport")
public class StudentPrintController {
    private static final Logger logger = LoggerFactory.getLogger(StudentPrintController.class);

    @GetMapping("/html")
    public void html(HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            PrintLoader.export(request,response);
        }
        catch (Exception e)
        {
            errorMessage(response, e);
        }
    }

    @GetMapping("/print_image")
    public void print_image(HttpServletRequest request, HttpServletResponse response) throws IOException, JRException {
        PrintLoader.image(request,response);
    }

    private void errorMessage(HttpServletResponse response, Exception e)
    {
        logger.error("打印报表出错!",e);
        PrintWriter writer = null;
        try {
            response.setContentType("text/html; charset=UTF-8");
            writer = response.getWriter();
            writer.write("<h3>打印报表出错<h3><h4>" + e.getMessage() + "</h4>");
        } catch (IOException ex) {
            logger.error("返回报表错误日志失败!",e);
        }
    }
}

IAdvanceHandler.java

public interface IAdvanceHandler extends IHandler {
    void processPrintDesigner(JasperDesign jasperDesign);
}

IHandler.java

public interface IHandler {
    /**
     * 如果不设置的话 那么就取默认的
     * @return
     */
    void getPrintSetting(PrintSetting setting);

    /**
     * 获取Parameters参数
     * @param request
     * @param response
     */
    void getParameters(Map<String, Object> request, Map<String, Object> response);

    /**
     * 获取Field参数
     * @param request
     * @param records
     */
    void getFields(Map<String, Object> request, List<Map<String, Object>> records);

}

PrintLoader.java

public class PrintLoader {

    /**
     * 这个需要从url传入 标识页面的bean
     */
    private final static String PAGES = "pages";
    /**
     * 这个需要从url传入 标识展示的类型 默认是1 是html展示
     */
    private final static String TYPE = "type";

    private final static String PACKAGE_BEAN = "xx.bean.";//自己包路径
    private final  static String FILL_DS = "ds";
    private final  static String FILL_CON = "con";
    private static final String[] postfix = new String[]{".pdf", ".html", ".doc", ".xls", ".xml"};
    public static final String IMAGE_NAME_REQUEST_PARAMETER = "image";


    public static void export(HttpServletRequest request, HttpServletResponse response) throws JRException, IOException, ClassNotFoundException {
        // url参数
        Map<String, Object> urlParam = new HashMap<>();
        Map<String, String[]> urlParameterMap = request.getParameterMap();
        for(String key : urlParameterMap.keySet())
        {
            urlParam.put(key, request.getParameter(key));
        }
        String pages = request.getParameter(PAGES);
        String typeStr = request.getParameter(TYPE);
        int type = StringUtils.isEmpty(typeStr) ? 1 : Integer.parseInt(typeStr);

        List<String> pageList = Arrays.asList(pages.split(","));
        List<JasperPrint> jps = new ArrayList();

        for (String pg : pageList)
        {
            JasperPrint jp;
            Object printBean = SpringUtils.getBean(Class.forName(PACKAGE_BEAN + pg));
            if(ObjectUtil.isNull(printBean))
            {
                throw new PrintException(pg+"未注册到容器!");
            }
            IHandler handler = null;
            if(printBean instanceof IHandler)
            {
                handler = (IHandler)printBean;
            }
            PrintSetting setting = new PrintSetting();
            handler.getPrintSetting(setting);

            JasperDesign jasperDesign = processFile2Design(pg,setting);

            if(handler instanceof com.qlh.yhis.report.prints.IAdvanceHandler)
            {
                ((IAdvanceHandler)handler).processPrintDesigner(jasperDesign);
            }
            if(ObjectUtil.isNull(handler))
            {
                throw new PrintException( "bean未继承IHandler!");
            }
            Map<String, Object> responseParam = new HashMap<>();

            handler.getParameters(urlParam, responseParam);

            JasperReport jasperReport = getJasperReport(jasperDesign);
            if(FILL_CON.equals(setting.getFill()))
            {
                jp = getJasperPrint(jasperReport, responseParam, setting.getConnection());
            }
            else if(FILL_DS.equals(setting.getFill()))
            {
                List<Map<String, Object>> records = new ArrayList();
                handler.getFields(urlParam, records);
                JRDataSource ds = ds(records);
                jp = getJasperPrint(jasperReport, responseParam, ds);
            }
            else
            {
                jp = getJasperPrint(jasperReport, responseParam);
            }
            jps.add(jp);
        }

        JRExporter exporter = getJRExporter(type, request, response, null);
        response.setContentType(getContentType(exporter));
        request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print_list", jps);
        exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jps);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        exporter.exportReport();
    }


    public static void image(HttpServletRequest request, HttpServletResponse response) throws JRException, IOException {
        byte[] imageData = null;
        String imageMimeType = null;

        String imageName = request.getParameter(IMAGE_NAME_REQUEST_PARAMETER);
        if ("px".equals(imageName))
        {
                Renderable pxRenderer =
                        RenderableUtil.getInstance(getJasperReportsContext()).getRenderable("net/sf/jasperreports/engine/images/pixel.GIF");
                imageData = pxRenderer.getImageData(getJasperReportsContext());
                imageMimeType = ImageTypeEnum.GIF.getMimeType();
        }
        else
        {
            List<JasperPrint> jasperPrintList = BaseHttpServlet.getJasperPrintList(request);

            if (jasperPrintList == null)
            {
                throw new JRException("No JasperPrint documents found on the HTTP session.");
            }

            JRPrintImage image = HtmlExporter.getImage(jasperPrintList, imageName);

            Renderable renderer = image.getRenderable();
            if (renderer.getTypeValue() == RenderableTypeEnum.SVG)
            {
                renderer =
                        new JRWrappingSvgRenderer(
                                renderer,
                                new Dimension(image.getWidth(), image.getHeight()),
                                ModeEnum.OPAQUE == image.getModeValue() ? image.getBackcolor() : null
                        );
            }

            imageMimeType = renderer.getImageTypeValue().getMimeType();
            imageData = renderer.getImageData(getJasperReportsContext());
        }
        if (imageData != null && imageData.length > 0)
        {
            if (imageMimeType != null)
            {
                response.setHeader("Content-Type", imageMimeType);
            }
            response.setContentLength(imageData.length);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(imageData, 0, imageData.length);
            outputStream.flush();
            outputStream.close();
        }
    }

    private static JasperReportsContext getJasperReportsContext()
    {
        return DefaultJasperReportsContext.getInstance();
    }

    private static JasperDesign processFile2Design(String id, PrintSetting setting) throws JRException, IOException
    {
        long lastModified = System.currentTimeMillis();

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("jrxml/"+id +".jrxml");
        JasperDesign jd = JRXmlLoader.load(resources[0].getInputStream());

        addDefaultStyle(jd, StyleManager.getBaseStyle());
        jd.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL);
        if (!StringUtils.isEmpty(setting.getScriptlet())) {
            jd.setScriptletClass(setting.getScriptlet());
        }

        jd.setProperty("jrxmlName", id);
        jd.setProperty("lastModified", String.valueOf(lastModified));
        fixMissingParamAndField(jd);
        return jd;
    }
    private static void addDefaultStyle(JasperDesign design, JRDesignStyle style) throws JRException {
        HashMap<String, JRStyle> map = (HashMap)design.getStylesMap();
        if (!map.containsKey(style.getName())) {
            design.addStyle(style);
        }

    }
    private static JasperDesign getJasperDesign(File file) throws JRException {
        return JRXmlLoader.load(file);
    }

    private static void fixMissingParamAndField(JasperDesign design) throws JRException {
        Map<String, JRParameter> params = design.getParametersMap();
        Map<String, JRField> fields = design.getFieldsMap();
        List<JRChild> els = getDesignElements(design);
        JRDesignStyle base = (JRDesignStyle)design.getStylesMap().get("myBaseStyleName");
        Iterator i$ = els.iterator();

        while(i$.hasNext()) {
            JRChild child = (JRChild)i$.next();
            if (child instanceof JRDesignElement) {
                JRDesignElement e = (JRDesignElement)child;
                e.setStyle(base);
                if (!(e instanceof JRDesignTextField)) {
                    if (e instanceof JRDesignStaticText) {
                        fixPDFFontEncoding((JRDesignStaticText)e, base);
                    }
                } else {
                    JRDesignTextField textField = (JRDesignTextField)e;
                    fixPDFFontEncoding(textField, base);
                    if (textField.getExpression() != null && textField.getExpression().getText().length() >= 5) {
                        String exp = textField.getExpression().getText();
                        String name = getExpressionValue(exp);
                        Class clazz;
                        if (exp.charAt(1) == 'P') {
                            if (!params.containsKey(name)) {
                                JRDesignParameter p = new JRDesignParameter();
                                p.setName(name);
                                clazz = textField.getExpression().getValueClass();
                                p.setValueClass(clazz);
                                design.addParameter(p);
                            }
                        } else if (exp.charAt(1) == 'F' && !fields.containsKey(name)) {
                            JRDesignField f = new JRDesignField();
                            f.setName(name);
                            clazz = textField.getExpression().getValueClass();
                            f.setValueClass(clazz);
                            design.addField(f);
                        }
                    }
                }
            }
        }

    }

    private static List<JRChild> getDesignElements(JasperDesign design) {
        List<JRChild> els = new ArrayList();
        List els_summary;
        if (design.getBackground() != null) {
            els_summary = ((JRDesignBand)design.getBackground()).getChildren();
            els.addAll(els_summary);
        }

        if (design.getTitle() != null) {
            els_summary = ((JRDesignBand)design.getTitle()).getChildren();
            els.addAll(els_summary);
        }

        if (design.getPageHeader() != null) {
            els_summary = ((JRDesignBand)design.getPageHeader()).getChildren();
            els.addAll(els_summary);
        }

        if (design.getColumnHeader() != null) {
            els_summary = ((JRDesignBand)design.getColumnHeader()).getChildren();
            els.addAll(els_summary);
        }

        if (design.getDetailSection().getBands().length > 0 && design.getDetailSection().getBands()[0] != null) {
            els_summary = ((JRDesignBand)design.getDetailSection().getBands()[0]).getChildren();
            els.addAll(els_summary);
        }

        if (design.getColumnFooter() != null) {
            els_summary = ((JRDesignBand)design.getColumnFooter()).getChildren();
            els.addAll(els_summary);
        }

        if (design.getPageFooter() != null) {
            els_summary = ((JRDesignBand)design.getPageFooter()).getChildren();
            els.addAll(els_summary);
        }

        if (design.getLastPageFooter() != null) {
            els_summary = ((JRDesignBand)design.getLastPageFooter()).getChildren();
            els.addAll(els_summary);
        }

        if (design.getSummary() != null) {
            els_summary = ((JRDesignBand)design.getSummary()).getChildren();
            els.addAll(els_summary);
        }

        return els;
    }

    private static void fixPDFFontEncoding(JRDesignStaticText t, JRDesignStyle s) {
        t.setFontName(s.getFontName());
        t.setPdfFontName(s.getPdfFontName());
        t.setPdfEncoding(s.getPdfEncoding());
    }

    private static void fixPDFFontEncoding(JRDesignTextField t, JRDesignStyle s) {
        t.setFontName(s.getFontName());
        t.setPdfFontName(s.getPdfFontName());
        t.setPdfEncoding(s.getPdfEncoding());
    }

    private static String getExpressionValue(String str) {
        return str.substring(3, str.length() - 1);
    }

    private static JRExporter getJRExporter(int type, HttpServletRequest request, HttpServletResponse response, String filename) {
        JRExporter exporter = null;
        if (StringUtils.isEmpty(filename)) {
            filename = String.valueOf((new Date()).getTime());
        }

        try {
            filename = new String(filename.getBytes("GBK"), "iso-8859-1");
        } catch (UnsupportedEncodingException var10) {
            var10.printStackTrace();
        }

        switch(type) {
            case 1:
                String isLandscape = request.getParameter("landscape");
                boolean landscape = false;
                if (!StringUtils.isEmpty(isLandscape) && "1".equals(isLandscape)) {
                    landscape = true;
                }

                boolean silentPrint = false;
                String isSilentPrint = request.getParameter("silentPrint");
                if (!StringUtils.isEmpty(isSilentPrint) && "1".equals(isSilentPrint)) {
                    silentPrint = true;
                }

                exporter = new JRHtmlExporter();
                StringBuffer sb = (new StringBuffer("</td><td width=\"50%\">&nbsp;</td></tr>\n</table>\n")).append("<script type='text/javascript'>\n").append("if(document.all){\n").append("}\n").append("if(jsPrintSetup){\n");
                if (landscape) {
                    sb.append("jsPrintSetup.setOption('orientation',jsPrintSetup.kLandscapeOrientation);\n");
                }

                sb.append("jsPrintSetup.setOption('marginTop',0);\n").append("jsPrintSetup.setOption('marginBottom',0);\n").append("jsPrintSetup.setOption('marginLeft',0);\n").append("jsPrintSetup.setOption('marginRight',0);\n").append("jsPrintSetup.setSilentPrint(" + silentPrint + ");\n").append("jsPrintSetup.print();\n").append("}\n").append("</script>\n").append("</body>\n</html>\n");
                ((JRExporter)exporter).setParameter(JRHtmlExporterParameter.HTML_FOOTER, sb.toString());
                ((JRExporter)exporter).setParameter(JRHtmlExporterParameter.ZOOM_RATIO, 1.25F);
                ((JRExporter)exporter).setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, false);

                ((JRExporter)exporter).setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "<div style='page-break-before:always;'></div>");
                break;
            case 2:
                exporter = new JRRtfExporter();
                response.setHeader("Content-Disposition", "inline; filename=\"" + filename + postfix[2] + "\"");
                break;
            case 3:
                exporter = new JRXlsExporter();
                ((JRExporter)exporter).setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, true);
                response.setHeader("Content-Disposition", "inline; filename=\"" + filename + postfix[3] + "\"");
                break;
            case 4:
                exporter = new JRXmlExporter();
                response.setHeader("Content-Disposition", "inline; filename=\"" + filename + postfix[4] + "\"");
                break;
            default:
                exporter = new JRPdfExporter();
                response.setHeader("Content-Disposition", "inline; filename=\"" + filename + postfix[0] + "\"");
        }

        return (JRExporter)exporter;
    }
    private static   String getContentType(JRExporter exporter) {
        String responseContentType = "text/html;charset=UTF-8";
        if (exporter instanceof JRRtfExporter) {
            responseContentType = "application/msword;charset=UTF-8";
        } else if (!(exporter instanceof JRXlsExporter) && !(exporter instanceof JExcelApiExporter)) {
            if (exporter instanceof JRPdfExporter) {
                responseContentType = "application/pdf;charset=UTF-8";
            }
        } else {
            responseContentType = "application/vnd.ms-excel;charset=UTF-8";
        }

        return responseContentType;
    }

    private static JasperPrint getJasperPrint(JasperReport jr, Map<String, Object> parameters, Connection con) throws JRException {
        return JasperFillManager.fillReport(jr, parameters, con);
    }

    private static JasperPrint getJasperPrint(JasperReport jr, Map<String, Object> parameters, JRDataSource dataSource) throws JRException {
        return JasperFillManager.fillReport(jr, parameters, dataSource);
    }

    private static JasperPrint getJasperPrint(JasperReport jr, Map<String, Object> parameters) throws JRException {
        return JasperFillManager.fillReport(jr, parameters);
    }

    private static JRDataSource ds(Collection collection) {
        return new JRMapCollectionDataSource(collection);
    }
    private static JasperReport getJasperReport(JasperDesign jd) throws JRException {
        JasperReport report = JasperCompileManager.compileReport(jd);
        return report;
    }
}

PrintSetting.java

@Data
public class PrintSetting {
    /**
     * ds : 是代码传过去数据
     * con : Jasper自己去链接数据库查数据
     */
    private String fill = "ds";
    /**
     * 别名
     */
    private String alias;
    /**
     * 貌似是js脚本 不清楚
     */
    private String scriptlet;
    /**
     * 数据库链接
     * 如果 fill = "ds" 那么需要赋值
     */
    private Connection connection;
}

StyleManager.java

public class StyleManager {
    private static JRDesignStyle base;
    private static JRDesignStyle box;
    public static final String baseStyleName = "myBaseStyleName";
    public static final String boxStyleName = "myBoxStyleName";

    public StyleManager() {
    }

    public static JRDesignStyle getBaseStyle() {
        if (base == null) {
            base = new JRDesignStyle();
            base.setName("myBaseStyleName");
            base.setVerticalAlignment(VerticalAlignEnum.MIDDLE);
            base.setFontName("宋体");
            base.setPdfFontName("STSong-Light");
            base.setPdfEncoding("UniGB-UCS2-H");
            base.setBlankWhenNull(true);
        }

        return base;
    }

    public static JRDesignStyle getboxStyle() {
        if (box == null) {
            box = new JRDesignStyle();
            box.getLinePen().setLineStyle(LineStyleEnum.SOLID);
            box.getLinePen().setLineWidth(1.0F);
        }

        return box;
    }
}

四、安装打印预览软件

CLodop_Setup_for_Win32NT与Lodop6.226_Clodop6.572

五、前端点击打印按钮

前端调用打印方法、电脑弹出预览页面

在这里插入图片描述

输出pdf
在这里插入图片描述

Logo

快速构建 Web 应用程序

更多推荐