我写的一个例子,在tomcat下成功了,但是中文不能显示,还没解决,要使谁解决了告诉我分享:[email protected] package x2pdf;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.Map; import java.util.TreeMap; import java.util.Enumeration; import java.util.Iterator;// import the iText package files for deal with PDF import com.lowagie.text.DocumentException; import com.lowagie.text.Document; import com.lowagie.text.PageSize; import com.lowagie.text.pdf.PdfWriter; import com.lowagie.text.HeaderFooter; import com.lowagie.text.Phrase; import com.lowagie.text.Paragraph; import com.lowagie.text.Element; import com.lowagie.text.Table; import com.lowagie.text.Cell; import com.lowagie.text.BadElementException; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.Font; //import com.lowagie.text.pdf.CJKFont; //import com.lowagie.text.DocumentException;/** * <p>Title: X2PDFServlet</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2004</p> * <p>Company: </p> * @author silver * @version 1.0 */ public class X2PDFServlet extends HttpServlet { private static final String CONTENT_TYPE = "application/pdf; charset=UTF-8"; private static final String CONTENT_DISPOSITION = "inline;filename=X2PDFofMyExample.pdf"; private static BaseFont bfChinese = null; private static Font FontChinese = null; //Initialize global variables public void init() throws ServletException { } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } //Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //DocumentException dePDF = null; request.setCharacterEncoding("UTF-8"); ByteArrayOutputStream baosPDF = null; try { // 创建中文字体 //bfChinese = BaseFont.createFont(BaseFont.FONT_TYPE_CJK,"UTF-8",BaseFont.NOT_EMBEDDED); //bfChinese = new CJKFont("STSong-Light",CJKFont.CJK_ENCODING,BaseFont.NOT_EMBEDDED);//BaseFont.createFont(CJKFont); //FontChinese = new Font(bfChinese); // 创建PDF文件 baosPDF = genPDFDocByteStream(request,this.getServletContext()); // 设置HTTP头属性 response.setContentType(CONTENT_TYPE); response.setHeader("Content-disposition",CONTENT_DISPOSITION); response.setContentLength(baosPDF.size()); ServletOutputStream sos = null; sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); }catch(DocumentException de){ response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>X2PDFServlet</title></head>"); out.println("<body bgcolor=\"#ffffff\">"); out.println("<p>The servlet has received a GET. But this is the error reply:</p>"); out.println("<p>" + this.getClass().getName() + "caught an exception: " + de.getClass().getName() + "<br>" + "</p>"); out.println("<pre>"); de.printStackTrace(out); out.println("<pre>"); out.println("</body></html>"); }finally { if(baosPDF!=null){ baosPDF.reset(); } } } //Clean up resources public void destroy() { }
接上: /** * @param req non-null * @param ctx ServletContext * @return a non-null output stream. The output stream contains the bytes for the PDF document * @throws DocumentException */ protected ByteArrayOutputStream genPDFDocByteStream( final HttpServletRequest req, final ServletContext ctx) throws DocumentException{ Document doc = new Document(); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter docWriter = null; try{ docWriter = PdfWriter.getInstance(doc, baosPDF); doc.addAuthor(this.getClass().getName() + "/written by silver"); doc.addCreationDate(); doc.addProducer(); doc.addCreator(this.getClass().getName() + "/written by silver"); doc.addTitle("使用java生成PDF"); doc.addSubject("iText创建PDF的解决方案"); doc.addKeywords("Java,PDF,iText,Open source"); doc.setPageSize(PageSize.LETTER); HeaderFooter header = new HeaderFooter( new Phrase("页眉"), false); HeaderFooter footer = new HeaderFooter( new Phrase("页脚"), false); doc.setHeader(header); doc.setFooter(footer); doc.open(); doc.add(new Paragraph( "产生本PDF的类: " + this.getClass().getName() + "/written by silver")); doc.add(new Paragraph( "产生时间: " + new Date())); String strServerInfo = ctx.getServerInfo(); if (strServerInfo != null) { doc.add(new Paragraph( "Servlet engine: " + strServerInfo)); } doc.add( makeEnglishContentElement(req) ); doc.newPage(); doc.add( makeChineseContentElement(req) ); doc.newPage(); doc.add( makeHTTPParameterInfoElement(req) ); }catch (DocumentException dex){ baosPDF.reset(); throw dex; }catch (Exception ex){ }finally{ if (doc != null){ doc.close(); } if (docWriter != null){ docWriter.close(); } } if (baosPDF.size() < 1) { throw new DocumentException( "document has " + baosPDF.size() + " bytes"); } return baosPDF; } /** * @param req * @return */ protected Element makeChineseContentElement( final HttpServletRequest req) { Map mapRequestDetails = new TreeMap(); mapRequestDetails.put("公司", "时力永联"); mapRequestDetails.put("地址", "中华人民共和国 北京"); mapRequestDetails.put("邮编", "100044"); Table tab = null; tab = makeTableFromMap( "字段名", "字段值", mapRequestDetails); return (Element) tab; } /** * @param firstColumnTitle * @param secondColumnTitle * @param m * @return */ private static Table makeTableFromMap( final String firstColumnTitle, final String secondColumnTitle, final java.util.Map m) { Table tab = null; try{ tab = new Table(2);/* columns */ }catch (BadElementException ex){ throw new RuntimeException(ex); } tab.setBorderWidth(1.0f); tab.setPadding(5); tab.setSpacing(5); tab.addCell(new Cell(firstColumnTitle)); tab.addCell(new Cell(secondColumnTitle)); tab.endHeaders(); if (m.keySet().size() == 0) { Cell c = new Cell("none"); c.setColspan(tab.columns()); tab.addCell(c); }else{ Iterator iter = m.keySet().iterator(); while (iter.hasNext()) { String strName = (String) iter.next(); Object value = m.get(strName); String strValue = null; if (value == null){ strValue = ""; }else if (value instanceof String[]){ String[] aValues = (String[]) value; strValue = aValues[0]; }else{ strValue = value.toString(); } tab.addCell(new Cell(strName)); tab.addCell(new Cell(strValue)); } } return tab; } /** * @param req * @return */ protected Element makeEnglishContentElement( final HttpServletRequest req) { Map mapRequestDetails = new TreeMap(); mapRequestDetails.put("Company", "Forlink"); mapRequestDetails.put("Addres", "Beijing China,P.R."); mapRequestDetails.put("ZipCode", "100044"); Table tab = null; tab = makeTableFromMap( "key name", "Value", mapRequestDetails); return (Element) tab; } /** * @param req * @return */ protected Element makeHTTPParameterInfoElement( final HttpServletRequest req){ Map mapParameters = null; mapParameters = new TreeMap(req.getParameterMap()); Table tab = null; tab = makeTableFromMap( "HTTP parameter name", "HTTP parameter value", mapParameters); return (Element) tab; } }
用jsp页面实现的,不生成服务器端文件,直接下载,已解决中文问题。(resin2.1.12下测试成功。)<%@ page import="java.io.*,java.awt.Color,com.lowagie.text.*,com.lowagie.text.pdf.*" errorPage="error.jsp" %> <% response.setContentType( "application/pdf"); // step 1: creation of a document-object Document document = new Document(PageSize.A4);// step 2: // we create a writer that listens to the document // and directs a PDF-stream to a temporary buffer ByteArrayOutputStream buffer = new ByteArrayOutputStream(); PdfWriter writer=PdfWriter.getInstance( document, buffer );// step 3: we open the document document.open();// step 4: we add a paragraph to the document BaseFont bfComic = BaseFont.createFont("c:\\winnt\\fonts\\SIMSUN.TTC,0", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); Font font = new Font(bfComic, 20); String str=new String("aaa 同志们辛苦了!".getBytes("ISO8859_1"),"gb2312"); document.add(new Paragraph(str,font));// step 5: we close the document document.close();// step 6: we output the writer as bytes to the response output DataOutput output = new DataOutputStream( response.getOutputStream() ); byte[] bytes = buffer.toByteArray(); response.setContentLength(bytes.length); for( int i = 0; i < bytes.length; i++ ) { output.writeByte( bytes[i] ); }%>
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.*;
import com.lowagie.text.html.HtmlWriter;
import java.awt.color.*;
import java.awt.font.*;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;public class MultiRow_pdf extends HttpServlet
{ protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
Document document = null;
try {
java.sql.Connection F_Connection=null;
java.sql.Statement F_Statement=null;
java.sql.ResultSet F_ResultSet=null;
String DriveString="com.microsoft.jdbc.sqlserver.SQLServerDriver";
java.lang.Class.forName(DriveString);
String ConURL="jdbc:microsoft:sqlserver://192.168.0.1:1433;user=sa;password=root;DatabaseName=Northwind";
F_Connection=DriverManager.getConnection(ConURL.trim(),"sa","root");
F_Statement=F_Connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
F_ResultSet = F_Statement.executeQuery("select * from orders");
/*打开已经定义好字段以后的pdf模板*/
PdfReader reader = new PdfReader("iText多行报表.pdf");
document = new Document(reader.getPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("iText多行报表结果.pdf"));
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page1 = writer.getImportedPage(reader, 1);
/*使用中文字体*/
BaseFont bf = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bf, 12, Font.NORMAL);
F_ResultSet.first();
int PageTotalRows=5;
int currentRow=1;
int RowHeight=100;
int Field1X,Field1Y,Field2X,Field3X,Field4X,Field5X;
Field1X=80;
Field2X=160;
Field3X=230;
Field4X=380;
Field5X=480;
Field1Y=580;
cb.addTemplate(page1, 1f, 0, 0, 1f, 0, 0);
while (currentRow<=PageTotalRows && F_ResultSet.next())
{
currentRow++;
java.io.File fImg = new java.io.File("cover.png");
Image img = Image.getInstance(fImg.toURL());
/*295是从左下角开始的横向坐标,Field1Y-70是从左下角开始的纵向坐标*/
img.setAbsolutePosition(295, Field1Y-70);
/*把图片缩小50% 以适宜cell大小*/
img.scalePercent(50);
cb.addImage(img);
cb.beginText();
cb.setFontAndSize(bf, 12);
//field1
cb.setTextMatrix(Field1X, Field1Y); //这里就是用来定位的值
cb.showText(F_ResultSet.getString("CustomerID"));
//field2
cb.setTextMatrix(Field2X, Field1Y); //这里就是用来定位的值
cb.showText(F_ResultSet.getString("OrderDate").substring(0,10));
//field3
cb.setTextMatrix(Field3X, Field1Y); //这里就是用来定位的值
cb.showText(F_ResultSet.getString("shipvia"));
//field4
cb.setTextMatrix(Field4X, Field1Y); //这里就是用来定位的值
cb.showText(F_ResultSet.getString("ShipCountry"));
Field1Y-=RowHeight;
cb.endText();
if (currentRow==6)
{
currentRow=1;
Field1X=80;
Field2X=160;
Field3X=230;
Field4X=380;
Field5X=480;
Field1Y=580;
reader = new PdfReader("iText多行报表.pdf");
page1 = writer.getImportedPage(reader, 1);
document.newPage();
cb.addTemplate(page1, 1f, 0, 0, 1f, 0, 0);
}
} //end of while
document.close();
F_ResultSet.close();
F_Statement.close();
F_Connection.close();
}
catch(DocumentException de) {
System.err.println(de.getMessage());
}
catch(IOException ioe) {
System.err.println(ioe.getMessage());
}
catch(Exception e)
{
System.err.println(e.getMessage());
System.err.println(e.getStackTrace());
} }
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
}
}
请问能调用这个servlet的时候,IE弹出下载对话框么?
应该把这句话:PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("iText多行报表结果.pdf"));改为:ByteArrayOutputStream ba = new ByteArrayOutputStream();
ServletOutputStream out = response.getOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, ba));
并且在catch结束后这样写:
try{
ba.writeTo(out);
out.flush();
out.close();
ba.close();
}catch(IOException e){
e.printStackTrace();
System.err.println("A Document error:" +e.getMessage());
}
请高手指点啊,最好能贴出过例子来。
package x2pdf;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.Enumeration;
import java.util.Iterator;// import the iText package files for deal with PDF
import com.lowagie.text.DocumentException;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Phrase;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Element;
import com.lowagie.text.Table;
import com.lowagie.text.Cell;
import com.lowagie.text.BadElementException;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.Font;
//import com.lowagie.text.pdf.CJKFont;
//import com.lowagie.text.DocumentException;/**
* <p>Title: X2PDFServlet</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author silver
* @version 1.0
*/
public class X2PDFServlet extends HttpServlet {
private static final String CONTENT_TYPE = "application/pdf; charset=UTF-8";
private static final String CONTENT_DISPOSITION = "inline;filename=X2PDFofMyExample.pdf";
private static BaseFont bfChinese = null;
private static Font FontChinese = null; //Initialize global variables
public void init() throws ServletException {
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//DocumentException dePDF = null;
request.setCharacterEncoding("UTF-8");
ByteArrayOutputStream baosPDF = null; try {
// 创建中文字体
//bfChinese = BaseFont.createFont(BaseFont.FONT_TYPE_CJK,"UTF-8",BaseFont.NOT_EMBEDDED);
//bfChinese = new CJKFont("STSong-Light",CJKFont.CJK_ENCODING,BaseFont.NOT_EMBEDDED);//BaseFont.createFont(CJKFont);
//FontChinese = new Font(bfChinese);
// 创建PDF文件
baosPDF = genPDFDocByteStream(request,this.getServletContext());
// 设置HTTP头属性
response.setContentType(CONTENT_TYPE);
response.setHeader("Content-disposition",CONTENT_DISPOSITION);
response.setContentLength(baosPDF.size()); ServletOutputStream sos = null;
sos = response.getOutputStream();
baosPDF.writeTo(sos);
sos.flush();
}catch(DocumentException de){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>X2PDFServlet</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p>The servlet has received a GET. But this is the error reply:</p>");
out.println("<p>" + this.getClass().getName()
+ "caught an exception: "
+ de.getClass().getName()
+ "<br>"
+ "</p>");
out.println("<pre>");
de.printStackTrace(out);
out.println("<pre>");
out.println("</body></html>");
}finally {
if(baosPDF!=null){
baosPDF.reset();
}
} }
//Clean up resources
public void destroy() {
}
/**
* @param req non-null
* @param ctx ServletContext
* @return a non-null output stream. The output stream contains the bytes for the PDF document
* @throws DocumentException
*/
protected ByteArrayOutputStream genPDFDocByteStream(
final HttpServletRequest req,
final ServletContext ctx)
throws DocumentException{ Document doc = new Document(); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
PdfWriter docWriter = null; try{
docWriter = PdfWriter.getInstance(doc, baosPDF); doc.addAuthor(this.getClass().getName() + "/written by silver");
doc.addCreationDate();
doc.addProducer();
doc.addCreator(this.getClass().getName() + "/written by silver");
doc.addTitle("使用java生成PDF");
doc.addSubject("iText创建PDF的解决方案");
doc.addKeywords("Java,PDF,iText,Open source"); doc.setPageSize(PageSize.LETTER); HeaderFooter header = new HeaderFooter(
new Phrase("页眉"),
false);
HeaderFooter footer = new HeaderFooter(
new Phrase("页脚"),
false);
doc.setHeader(header);
doc.setFooter(footer); doc.open(); doc.add(new Paragraph(
"产生本PDF的类: "
+ this.getClass().getName() + "/written by silver")); doc.add(new Paragraph(
"产生时间: "
+ new Date())); String strServerInfo = ctx.getServerInfo(); if (strServerInfo != null)
{
doc.add(new Paragraph(
"Servlet engine: " + strServerInfo));
} doc.add( makeEnglishContentElement(req) ); doc.newPage(); doc.add( makeChineseContentElement(req) ); doc.newPage(); doc.add( makeHTTPParameterInfoElement(req) ); }catch (DocumentException dex){
baosPDF.reset();
throw dex;
}catch (Exception ex){
}finally{
if (doc != null){
doc.close();
}
if (docWriter != null){
docWriter.close();
}
} if (baosPDF.size() < 1)
{
throw new DocumentException(
"document has "
+ baosPDF.size()
+ " bytes");
}
return baosPDF;
} /**
* @param req
* @return
*/
protected Element makeChineseContentElement(
final HttpServletRequest req)
{
Map mapRequestDetails = new TreeMap(); mapRequestDetails.put("公司", "时力永联"); mapRequestDetails.put("地址", "中华人民共和国 北京"); mapRequestDetails.put("邮编", "100044"); Table tab = null; tab = makeTableFromMap(
"字段名",
"字段值",
mapRequestDetails); return (Element) tab;
}
/**
* @param firstColumnTitle
* @param secondColumnTitle
* @param m
* @return
*/
private static Table makeTableFromMap(
final String firstColumnTitle,
final String secondColumnTitle,
final java.util.Map m)
{
Table tab = null; try{
tab = new Table(2);/* columns */
}catch (BadElementException ex){
throw new RuntimeException(ex);
} tab.setBorderWidth(1.0f);
tab.setPadding(5);
tab.setSpacing(5); tab.addCell(new Cell(firstColumnTitle));
tab.addCell(new Cell(secondColumnTitle)); tab.endHeaders(); if (m.keySet().size() == 0)
{
Cell c = new Cell("none");
c.setColspan(tab.columns());
tab.addCell(c);
}else{
Iterator iter = m.keySet().iterator();
while (iter.hasNext())
{
String strName = (String) iter.next();
Object value = m.get(strName);
String strValue = null;
if (value == null){
strValue = "";
}else if (value instanceof String[]){
String[] aValues = (String[]) value;
strValue = aValues[0];
}else{
strValue = value.toString();
} tab.addCell(new Cell(strName));
tab.addCell(new Cell(strValue));
}
} return tab;
} /**
* @param req
* @return
*/
protected Element makeEnglishContentElement(
final HttpServletRequest req)
{
Map mapRequestDetails = new TreeMap(); mapRequestDetails.put("Company", "Forlink"); mapRequestDetails.put("Addres", "Beijing China,P.R."); mapRequestDetails.put("ZipCode", "100044"); Table tab = null; tab = makeTableFromMap(
"key name",
"Value",
mapRequestDetails); return (Element) tab;
} /**
* @param req
* @return
*/
protected Element makeHTTPParameterInfoElement(
final HttpServletRequest req){
Map mapParameters = null; mapParameters = new TreeMap(req.getParameterMap()); Table tab = null; tab = makeTableFromMap(
"HTTP parameter name",
"HTTP parameter value",
mapParameters); return (Element) tab;
} }
page import="java.io.*,java.awt.Color,com.lowagie.text.*,com.lowagie.text.pdf.*"
errorPage="error.jsp"
%>
<%
response.setContentType( "application/pdf");
// step 1: creation of a document-object
Document document = new Document(PageSize.A4);// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a temporary buffer
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter writer=PdfWriter.getInstance( document, buffer );// step 3: we open the document
document.open();// step 4: we add a paragraph to the document
BaseFont bfComic = BaseFont.createFont("c:\\winnt\\fonts\\SIMSUN.TTC,0", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
Font font = new Font(bfComic, 20);
String str=new String("aaa 同志们辛苦了!".getBytes("ISO8859_1"),"gb2312");
document.add(new Paragraph(str,font));// step 5: we close the document
document.close();// step 6: we output the writer as bytes to the response output
DataOutput output = new DataOutputStream( response.getOutputStream() );
byte[] bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
for( int i = 0; i < bytes.length; i++ ) { output.writeByte( bytes[i] ); }%>