JasperReport结合JasperReport Studio工具,生成Pdf文件,解决中文不显示问题

需要对JasperReport Studio工具的了解,可以参考链接:https://blog.csdn.net/u013456370/article/details/81389497

项目结构图:

该项目为Maven项目:

pom.xml 如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>JasperReports</groupId>
  <artifactId>JasperReports</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>JasperReports Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- iReport JasperReports -->  
<dependency>  
    <groupId>net.sf.jasperreports</groupId>  
    <artifactId>jasperreports</artifactId>  
    <version>5.6.0</version>  
</dependency>  

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.30</version>
</dependency>

<dependency> 
    <groupId>com.lowagie</groupId>
    <artifactId>itextasian</artifactId>
    <version>1.5.2</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
</dependency>

  </dependencies>
  <build>
    <finalName>JasperReports</finalName>
  </build>
</project>

创建的是Servlet类:

TestHttpReportServlet.java 如下:

package com.accord.test;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRMapArrayDataSource;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;

import com.accord.dao.Jdbc;

public class TestHttpReportServlet extends HttpServlet {

	public static void main(String[] args) {
		String path = "http://localhost:8080/JasperReports/TestHttpReportServlet";
		String str = path.substring(0, path.lastIndexOf("/"));
		System.out.println(str);

	}

	private static final long serialVersionUID = 1L;

	public TestHttpReportServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// System.out.println("1");
		doPost(request, response);
	}

	@SuppressWarnings("deprecation")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		ServletContext context = this.getServletConfig().getServletContext();
		
		try {
			//JasperCompileManager.compileReportToFile("E:/report/DbReport.jrxml");
			JasperCompileManager.compileReportToFile(context.getRealPath("/reports/Coffee.jrxml"));
		} catch (JRException e1) {
			e1.printStackTrace();
		}//编译jrxml文件,生成jasper文件

		File reportFile = new File(context.getRealPath("/reports/Coffee.jasper"));
				
		if (!reportFile.exists())
			throw new JRRuntimeException("FileWebappReport.jasper "
					+ "not found. The report design must be compiledfirst.");
		Map map = new HashMap();
		map.put("name", "张三");
		try {
			File jasperFile = new File(context.getRealPath("/reports/Coffee.jasper"));
					
			JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile);
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, Jdbc.getConnection());
			String fileName = jasperPrint.getName() + ".html";
			File destFile = new File(context.getRealPath("/reports"), fileName);
			String destFileName = destFile.toString();
			
			//生成html数据
			/*JRHtmlExporter exporter = new JRHtmlExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,destFileName);
			exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING,"GB2312"); // 关键是此句
			exporter.exportReport();
			System.out.println(request.getRequestURL());
			String path = request.getRequestURL().toString();
			String str = path.substring(0, path.lastIndexOf("/"));
			response.sendRedirect(str + "/reports/" + fileName);*/
			
			//生成Excel
			/*JRXlsExporter xls = new JRXlsExporter();
			xls.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
			xls.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, response.getOutputStream());
			xls.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
			xls.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
			response.setHeader("Content-Disposition", "attachement;filename=first.xls");
			response.setContentType("application/vnd_ms-excel");
			xls.exportReport();*/
			
			//生成pdf
			
			JRPdfExporter pdf = new JRPdfExporter();
			pdf.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			pdf.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
			response.setHeader("Content-Disposition", "attachement;filename=first.pdf");			
			response.setContentType("application/pdf");
			response.setCharacterEncoding("UTF-8");
			pdf.exportReport();
			
			
		} catch (JRException e) {
			e.printStackTrace();
		}

	}

	public JRDataSource getReportDataSource() {
		JRMapArrayDataSource dataSource = new JRMapArrayDataSource(
				getMaparray());
		return dataSource;
	}

	public Map[] getMaparray() {
		// map key键必须对应DbReport.jrxml中显示数据字段
		Map map1 = new HashMap();
		map1.put("id", 1);
		map1.put("name", "aaa");
		map1.put("age", "20");

		Map map2 = new HashMap();
		map2.put("id", 2);
		map2.put("name", "bbb");
		map2.put("age", "28");

		Map map3 = new HashMap();
		map3.put("id", 3);
		map3.put("name", "ccc");
		map3.put("age", "30");

		Map[] mapArray = new Map[3];
		mapArray[0] = map1;
		mapArray[1] = map2;
		mapArray[2] = map3;

		return mapArray;
	}

}

web.xml如下:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
  	<servlet-name>TestHttpReportServlet</servlet-name>
  	<display-name>TestHttpReportServlet</display-name>
  	<description></description>
  	<servlet-class>com.accord.test.TestHttpReportServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>TestHttpReportServlet</servlet-name>
  	<url-pattern>/TestHttpReportServlet</url-pattern>
  </servlet-mapping>
</web-app>

Jdbc.java 如下:

package com.accord.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Jdbc {
	public static String driver="com.mysql.jdbc.Driver";  
    public static String url="jdbc:mysql://localhost:3306/db_studentinfo";  
    public static String user="root";  
    public static String pwd="123456";  
    public static Connection conn= getConnection();  
    public static Statement statement= getStatement();  
  
    public static Connection getConnection(){  
        if(conn==null){  
            try{  
                 Class.forName(driver);  
                 conn=DriverManager.getConnection(url,user,pwd);  
            }catch(Exception e){  
                e.printStackTrace();  
            }  
        }  
        return conn;  
    }  
    private static Statement getStatement(){  
        if(statement==null){  
            try{  
                statement=conn.createStatement();  
            }catch(Exception e){  
                e.printStackTrace();  
            }  
        }  
        return statement;  
    }  
    public static ResultSet getResultSet(String sql){  
        ResultSet rs=null;  
        try{  
            rs=statement.executeQuery(sql);  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
        return rs;  
    }  
    
    public static void closeAll(ResultSet rs,Statement st,Connection cn){  
        try{  
            if(rs!=null){  
                rs.close();  
            }  
            if(st!=null){  
                st.close();  
            }  
            if(cn!=null){  
                cn.close();  
            }  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
    }  

}

Coffee.jrxml 如下:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.6.0.final using JasperReports Library version 6.6.0  -->
<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="Coffee" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="ced95029-b569-4027-895c-af2843a4e088">
	<property name="com.jaspersoft.studio.data.sql.tables" value="IkFERFJFU1MiICwxNSwxNSxhZGQ2NGM2OC0wNDcxLTRjYWItOWE3Mi1hMDFlMjYzZTJmMWM7"/>
	<property name="com.jaspersoft.studio.data.defaultdataadapter" value="Sample DB"/>
	<style name="Title" fontName="Times New Roman" fontSize="50" isBold="true"/>
	<style name="SubTitle" forecolor="#736343" fontName="Arial" fontSize="18"/>
	<style name="Column header" forecolor="#666666" fontName="Arial" fontSize="12" isBold="true"/>
	<style name="Detail" fontName="Arial" fontSize="12"/>
	<style name="Row" mode="Transparent">
		<conditionalStyle>
			<conditionExpression><![CDATA[$V{REPORT_COUNT}%2 == 0]]></conditionExpression>
			<style backcolor="#E6DAC3"/>
		</conditionalStyle>
	</style>
	<queryString language="SQL">
		<![CDATA[select ID,NAME,AGE from USER]]>
	</queryString>
	<field name="ID" class="java.lang.Integer">
		<property name="com.jaspersoft.studio.field.label" value="ID"/>
		<property name="com.jaspersoft.studio.field.tree.path" value="USER"/>
	</field>
	<field name="NAME" class="java.lang.String">
		<property name="com.jaspersoft.studio.field.label" value="NAME"/>
		<property name="com.jaspersoft.studio.field.tree.path" value="USER"/>
	</field>
	<field name="AGE" class="java.lang.String">
		<property name="com.jaspersoft.studio.field.label" value="AGE"/>
		<property name="com.jaspersoft.studio.field.tree.path" value="USER"/>
	</field>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="136" splitType="Stretch">
			<staticText>
				<reportElement style="Title" x="170" y="0" width="263" height="62" uuid="1a652692-054a-40f3-ade5-68d8da36626d"/>
				<textElement verticalAlignment="Middle"/>
				<text><![CDATA[Coffee Title]]></text>
			</staticText>
			<staticText>
				<reportElement style="SubTitle" x="219" y="62" width="196" height="22" uuid="88d4231e-f014-4b0d-b871-1737ba63a1ae"/>
				<textElement>
					<font fontName="Times New Roman"/>
				</textElement>
				<text><![CDATA[Coffee SubTitle]]></text>
			</staticText>
			<staticText>
				<reportElement x="172" y="94" width="383" height="42" uuid="f0bfb1ea-a85a-47cd-a1a4-43f22b45e80f"/>
				<textElement textAlignment="Right">
					<font size="10"/>
				</textElement>
				<text><![CDATA[Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor purus gravida arcu aliquam mattis. Donec et nulla libero, ut varius massa. Nulla sed turpis elit. Etiam aliquet mauris a ligula hendrerit in auctor leo lobortis.]]></text>
			</staticText>
		</band>
	</title>
	<pageHeader>
		<band splitType="Stretch"/>
	</pageHeader>
	<columnHeader>
		<band height="16" splitType="Stretch">
			<line>
				<reportElement positionType="FixRelativeToBottom" x="0" y="15" width="555" height="1" uuid="1a61a836-d137-48b1-ad67-6ff64600bf93"/>
				<graphicElement>
					<pen lineWidth="0.5" lineColor="#999999"/>
				</graphicElement>
			</line>
			<staticText>
				<reportElement style="Column header" x="0" y="0" width="185" height="15" forecolor="#736343" uuid="53782cec-a88c-40d0-979c-b7e9dae2eae7">
					<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="03a1728b-5947-4c03-a90b-f15156887030"/>
				</reportElement>
				<text><![CDATA[ID]]></text>
			</staticText>
			<staticText>
				<reportElement style="Column header" x="185" y="0" width="185" height="15" forecolor="#736343" uuid="ee1e223b-74db-4b71-a854-79451f5fe81a">
					<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="1fa12e5b-839b-4304-9a45-75a52927faf1"/>
				</reportElement>
				<text><![CDATA[NAME]]></text>
			</staticText>
			<staticText>
				<reportElement style="Column header" x="370" y="0" width="185" height="15" forecolor="#736343" uuid="1d84c6e8-38e4-420f-9521-46e407d6c6e3">
					<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="9541bb7f-5e1c-48df-8df9-7123e6e97aaa"/>
				</reportElement>
				<text><![CDATA[AGE]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="15" splitType="Stretch">
			<frame>
				<reportElement style="Row" mode="Opaque" x="0" y="0" width="555" height="15" uuid="a98495d8-3c8d-4fa0-81f5-30c3efc2f766"/>
				<textField isStretchWithOverflow="true">
					<reportElement style="Detail" x="0" y="0" width="185" height="15" uuid="7f121ff2-dff5-48de-91bf-993c75eff89e">
						<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="03a1728b-5947-4c03-a90b-f15156887030"/>
					</reportElement>
					<textFieldExpression><![CDATA[$F{ID}]]></textFieldExpression>
				</textField>
				<textField isStretchWithOverflow="true">
					<reportElement style="Detail" x="185" y="0" width="185" height="15" uuid="234b1282-317d-4a28-8db3-81cff0ca876d">
						<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="1fa12e5b-839b-4304-9a45-75a52927faf1"/>
					</reportElement>
					<!--<textElement>
						<font fontName="myfont" isBold="true"/>
					</textElement>-->
					<textElement>
					   <font fontName="宋体" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
					</textElement>
					<textFieldExpression><![CDATA[$F{NAME}]]></textFieldExpression>
				</textField>
				<textField isStretchWithOverflow="true">
					<reportElement style="Detail" x="370" y="0" width="185" height="15" uuid="7542dc1b-702e-44da-addd-090b05e53974">
						<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="9541bb7f-5e1c-48df-8df9-7123e6e97aaa"/>
					</reportElement>
					<textFieldExpression><![CDATA[$F{AGE}]]></textFieldExpression>
				</textField>
			</frame>
		</band>
	</detail>
	<columnFooter>
		<band height="45" splitType="Stretch">
			<line>
				<reportElement positionType="FixRelativeToBottom" x="0" y="3" width="555" height="1" uuid="fa45a887-615a-4d84-a2d7-8a2219671b3c"/>
				<graphicElement>
					<pen lineWidth="0.5" lineColor="#999999"/>
				</graphicElement>
			</line>
		</band>
	</columnFooter>
	<pageFooter>
		<band height="25" splitType="Stretch">
			<frame>
				<reportElement mode="Opaque" x="-21" y="1" width="597" height="24" forecolor="#D0B48E" backcolor="#F2EBDF" uuid="183682bc-d976-4756-83e0-6625a3f98ed1"/>
				<textField evaluationTime="Report">
					<reportElement style="Column header" x="533" y="0" width="40" height="20" forecolor="#736343" uuid="0193f9b3-1559-491a-8580-b6988863b6a1"/>
					<textElement verticalAlignment="Middle">
						<font size="10" isBold="false"/>
					</textElement>
					<textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
				</textField>
				<textField>
					<reportElement style="Column header" x="453" y="0" width="80" height="20" forecolor="#736343" uuid="d00b105e-494b-418b-8ac9-8b1b4824f4f0"/>
					<textElement textAlignment="Right" verticalAlignment="Middle">
						<font size="10" isBold="false"/>
					</textElement>
					<textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
				</textField>
				<textField pattern="EEEEE dd MMMMM yyyy">
					<reportElement style="Column header" x="22" y="1" width="197" height="20" forecolor="#736343" uuid="0616f3fe-0354-456f-8911-ec30ec51a5ae"/>
					<textElement verticalAlignment="Middle">
						<font size="10" isBold="false"/>
					</textElement>
					<textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
				</textField>
			</frame>
		</band>
	</pageFooter>
	<summary>
		<band splitType="Stretch"/>
	</summary>
</jasperReport>

注:Coffee.jrxml  中属性名的大小写!

如果想设置某个属性值是汉字的话,直接可以在.jrxml文件中进行修改!设置如下:

<textElement>
   <font fontName="宋体" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
</textElement>

在Maven项目的pom.xml中:选下面的

<dependency> 
    <groupId>com.lowagie</groupId>
    <artifactId>itextasian</artifactId>
    <version>1.5.2</version>
</dependency>

引入itextasian-1.5.2.jar文件,注意该文件的目录结构为com/lowagie/text/pdf/fonts/*,

防止被坑:最新的itext-asian.jar包不是该结构无法正常使用!  注意这是个坑!千万别选错了!如果选择这个,pdf中汉字还是不显示的!

可以在这下载:https://download.csdn.net/download/u013456370/10582020

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页