怎样将html转换成pdf?

Yansharp 2005-02-16 01:33:13
在html中有一个统计报表,现在需要将这个报表以pdf的形式输出,也就是把html转变成pdf,用iText怎么做?

顺便给大家拜年了!

例如:下面这个页面,我只想把myTabel中的内容输出到pdf中。实际情况的表格比较复杂。
<html>
<title>My Test</title>
<body>
<table id="myTable">
<tr>
<td>名称</td>
<td>金额</td>
</tr>
<tr>
<td>Philips</td>
<td>5000</td>
</tr>
<tr>
<td>Nokia</td>
<td>3000</td>
</tr>
</table>
</body>
</html>
...全文
1569 18 打赏 收藏 转发到动态 举报
写回复
用AI写文章
18 条回复
切换为时间正序
请发表友善的回复…
发表回复
mxlmwl 2005-07-08
  • 打赏
  • 举报
回复
/*

* Created on 2004-1-3,创建第一个Hello World程序

*/

package test1;



import java.io.FileNotFoundException;

import java.io.FileOutputStream;



import com.lowagie.text.*;

import com.lowagie.text.pdf.*;

public class HelloWorld {



public static void main(String[] args) {

//创建一个文档对象

Document doc=new Document();

try {

//定义输出位置并把文档对象装入输出对象中

PdfWriter.getInstance(doc, new FileOutputStream("c:/hello.pdf"));

//打开文档对象

doc.open();

// 加入文字“Hello World”

doc.add(new Paragraph("HelloWorld"));

// 关闭文档对象,释放资源

doc.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (DocumentException e) {

e.printStackTrace();

}

}

}


就是楼上的那个方法,但和spring没关系。
另一种方法就是把jsp输出类型变为pdf格式,不知道是否有,我没试过,不过excel的确是可以的,你找找看。
mxlmwl 2005-07-08
  • 打赏
  • 举报
回复
用IText或者是指定jsp输出类型为pdf格式
yiwg 2005-07-07
  • 打赏
  • 举报
回复
// We can go now on the countries list
table = new PdfPTable(2);
int headerwidths[] = {20, 80};
table.setWidths(headerwidths);
table.setWidthPercentage(60);
table.getDefaultCell().setBorderWidth(2);
table.getDefaultCell().setBorderColor(Color.black);
table.getDefaultCell().setGrayFill(0.75f);
table.getDefaultCell().setPadding(3);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

table.addCell(new Phrase(getMessageSourceAccessor().getMessage( "code"), DATA_HEAD_FONT));
table.addCell(new Phrase(getMessageSourceAccessor().getMessage( "name"), DATA_HEAD_FONT));

// We set the above row as remaining title
// and adjust properties for normal cells
table.setHeaderRows(1);
table.getDefaultCell().setBorderWidth(1);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);

// We iterate now on the countries list
boolean even = false;
Iterator it = pgHolder.getSource().iterator();
while(it.hasNext()) {
if (even) {
table.getDefaultCell().setGrayFill(0.95f);
even = false;
} else {
table.getDefaultCell().setGrayFill(1.00f);
even = true;
}
ICountry country = (ICountry)it.next();
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(new Phrase(country.getCode(), BOLD_FONT));
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(new Phrase(country.getName(), TEXT_FONT));
}
document.add(table);
}


//~ Inner Classes ----------------------------------------------------------

private static class MyPageEvents extends PdfPageEventHelper {

private MessageSourceAccessor messageSourceAccessor;

// This is the PdfContentByte object of the writer
private PdfContentByte cb;

// We will put the final number of pages in a template
private PdfTemplate template;

// This is the BaseFont we are going to use for the header / footer
private BaseFont bf = null;

public MyPageEvents(MessageSourceAccessor messageSourceAccessor) {
this.messageSourceAccessor = messageSourceAccessor;
}

// we override the onOpenDocument method
public void onOpenDocument(PdfWriter writer, Document document) {
try {
bf = BaseFont.createFont( BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED );
cb = writer.getDirectContent();
template = cb.createTemplate(50, 50);
} catch (DocumentException de) {
} catch (IOException ioe) {}
}

// we override the onEndPage method
public void onEndPage(PdfWriter writer, Document document) {
int pageN = writer.getPageNumber();
String text = messageSourceAccessor.getMessage("page", "page") + " " + pageN + " " +
messageSourceAccessor.getMessage("on", "on") + " ";
float len = bf.getWidthPoint( text, 8 );
cb.beginText();
cb.setFontAndSize(bf, 8);

cb.setTextMatrix(MARGIN, 16);
cb.showText(text);
cb.endText();

cb.addTemplate(template, MARGIN + len, 16);
cb.beginText();
cb.setFontAndSize(bf, 8);

cb.endText();
}

// we override the onCloseDocument method
public void onCloseDocument(PdfWriter writer, Document document) {
template.beginText();
template.setFontAndSize(bf, 8);
template.showText(String.valueOf( writer.getPageNumber() - 1 ));
template.endText();
}
}

}
yiwg 2005-07-07
  • 打赏
  • 举报
回复
给你个spring下的例子参考:
package org.springframework.samples.countries.web.views;

import java.awt.*;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

import org.springframework.beans.support.RefreshablePagedListHolder;
import org.springframework.beans.support.SortDefinition;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.samples.countries.appli.ICountry;
import org.springframework.samples.countries.web.CountriesFilter;
import org.springframework.web.servlet.view.document.AbstractPdfView;

/**
* This view demonstrates how to send a PDF file with the Spring Framework
* using the iText PDF library.
*
* @author Jean-Pierre Pawlak
*/
public class CountriesPdfView extends AbstractPdfView {

private static final Font HEADLINE_FONT = new Font( Font.HELVETICA, 18, Font.BOLD, Color.blue );
private static final Font HEADING_FONT = new Font( Font.HELVETICA, 12, Font.ITALIC, Color.black );
private static final Font HEADING_DATA_FONT = new Font( Font.HELVETICA, 12, Font.ITALIC, Color.blue );
private static final Font DATA_HEAD_FONT = new Font( Font.HELVETICA, 10, Font.ITALIC, Color.black );
private static final Font TEXT_FONT = new Font( Font.TIMES_ROMAN, 8, Font.NORMAL, Color.black );
private static final Font BOLD_FONT = new Font( Font.TIMES_ROMAN, 8, Font.BOLD, Color.black );
private static final int MARGIN = 32;

protected void buildPdfMetadata(Map model, Document document, HttpServletRequest request) {
document.addTitle("Countries List");
document.addCreator("SPRING-Countries");
}

protected void buildPdfDocument(Map model, Document document, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response)
throws DocumentException, NoSuchMessageException {

// We search the data to insert.
RefreshablePagedListHolder pgHolder = (RefreshablePagedListHolder) model.get("countries");
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, pgHolder.getLocale());

// We prepare some data.
SortDefinition sort = pgHolder.getSort();
CountriesFilter filter = (CountriesFilter) pgHolder.getFilter();

// We create and add the event handler.
// So we can well paging, ensuring that only entire cells are printed
// at end of pages (the latter is useless in this example as records
// keep in one row, but in your own developpment it's not always the case).
MyPageEvents events = new MyPageEvents(getMessageSourceAccessor());
writer.setPageEvent(events);
events.onOpenDocument(writer, document);

String title = getMessageSourceAccessor().getMessage("app.name");
document.add(new Paragraph(title, HEADLINE_FONT));
document.add(new Paragraph(" "));
document.add(new Paragraph(" "));
document.add(new Paragraph(" "));

// We create a table for used criteria and extracting information
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(50);
table.getDefaultCell().setBorderWidth(1);
table.getDefaultCell().setBorderColor(Color.black);
table.getDefaultCell().setPadding(4);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setVerticalAlignment( Element.ALIGN_MIDDLE);

PdfPCell cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage("criteria"), HEADING_FONT));
cell.setColspan(2);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setGrayFill(0.7f);
table.addCell(cell);
cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage("property"), HEADING_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setGrayFill(0.9f);
table.addCell(cell);
cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage( "value"), HEADING_FONT));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setGrayFill(0.9f);
table.addCell(cell);

// We put the used criteria and extracting information
cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage( "date.extraction"), HEADING_FONT));
table.addCell(cell);
cell = new PdfPCell(new Phrase(df.format(pgHolder.getRefreshDate()), HEADING_DATA_FONT));
table.addCell(cell);

cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage( "nbRecords"), HEADING_FONT));
table.addCell(cell);
cell = new PdfPCell(new Phrase(String.valueOf(pgHolder.getNrOfElements()), HEADING_DATA_FONT));
table.addCell(cell);

cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage( "sort.name"), HEADING_FONT));
table.addCell(cell);
cell = new PdfPCell(new Phrase(sort.getProperty(), HEADING_DATA_FONT));
table.addCell(cell);

cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage( "sort.asc"), HEADING_FONT));
table.addCell(cell);
cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage(new Boolean(sort.isAscending()).toString()),
HEADING_DATA_FONT));
table.addCell(cell);

cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage( "sort.igncase"), HEADING_FONT));
table.addCell(cell);
cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage(new Boolean(sort.isIgnoreCase()).toString()),
HEADING_DATA_FONT));
table.addCell(cell);

cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage( "filter.name"), HEADING_FONT));
table.addCell(cell);
cell = new PdfPCell(new Phrase(null == filter.getName() ? "" : filter.getName(), HEADING_DATA_FONT));
table.addCell(cell);

cell = new PdfPCell(new Phrase(getMessageSourceAccessor().getMessage( "filter.code"), HEADING_FONT));
table.addCell(cell);
cell = new PdfPCell(new Phrase(null == filter.getCode() ? "" : filter.getCode(), HEADING_DATA_FONT));
table.addCell(cell);

document.add(table);
document.newPage();

108041217 2005-07-07
  • 打赏
  • 举报
回复
用Jasper吧,很好的.
zghmu007 2005-07-07
  • 打赏
  • 举报
回复
学习,帮顶
laughsmile 2005-07-07
  • 打赏
  • 举报
回复
第一个页面:
<html>
<title>My Test</title>
<body>
<form name="form1">
<input type="hidden" name="buttons" value="">
<table id="myTable">
<tr>
<td>名称</td>
<td>金额</td>
</tr>
<tr>
<td>Philips</td>
<td>5000</td>
</tr>
<tr>
<td>Nokia</td>
<td>3000</td>
</tr>
</table>
</form>
</body>
<script>
document.form1.buttons.value=myTable.innerHTML;
document.form1.action="下一个jsp";
document.form1.submit();
</script>
</html>

下一个jsp:
//假设有2列
request.setCharacterEncoding("gb2312");
String str = request.getParameter("buttons");
if(str ==null) str ="";
str = str.replaceAll("\\<[^\\>]*\\>",",");
str = str.replaceAll("[,]+",",");
if (str.startsWith(","))
str = str.substring(1);
if (str.endsWith(","))
str = str.substring(0,str.length()-1);
System.out.println(str);
String[] strResult = str.split(",");

//接着把strResult 的内容打印出来
.....
...
int[] nTitleItemWidth={50,50};
PdfPTable datatable = new PdfPTable(2);
datatable.setWidths(nTitleItemWidth);
datatable.getDefaultCell().setPadding(3);
datatable.setWidthPercentage(100); // percentage

for (int i = 0 ;i<strResult.length ; i++){
PdfPCell pCTitle=new PdfPCell(new Phrase(strResult[i],boldFont));
pCTitle.setColspan(1);
pCTitle.setBorderWidth(1);
pCTitle.setHorizontalAlignment(0);
pCTitle.setFixedHeight(20);
datatable.addCell(pCTitle);
i++;
}
crazy_he 2005-07-07
  • 打赏
  • 举报
回复
继续帮你顶,有没有好的开源项目?
mayeyun 2005-07-07
  • 打赏
  • 举报
回复
好难啊,帮你顶了,呵呵
chinatelly 2005-07-07
  • 打赏
  • 举报
回复
xuex学习
Yansharp 2005-02-17
  • 打赏
  • 举报
回复
沉了
clearwater21cn 2005-02-16
  • 打赏
  • 举报
回复
使用Display Tag可以实现
http://www.displaytag.org/example-export.jsp
这个例子没有导出pdf,但实际可以
Yansharp 2005-02-16
  • 打赏
  • 举报
回复
难道真的没有人用过?
rategy 2005-02-16
  • 打赏
  • 举报
回复
打印到pdf的虚拟打印机就行了
sparkling_lwp 2005-02-16
  • 打赏
  • 举报
回复
楼主,能否将HTML->XML->PDF???赐教
dabo1980 2005-02-16
  • 打赏
  • 举报
回复
没。。。遇见过!UP!
EverythingMaster 2005-02-16
  • 打赏
  • 举报
回复
我不会。。。。
帮你顶了!
以梦为马 2005-02-16
  • 打赏
  • 举报
回复
新春愉快!

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧