给你提供一个参考例子,你可以在这个例子上试试,修改修改.也是解析PDF的.
import?java.io.File;?
import?java.io.FileOutputStream;?
import?java.io.OutputStreamWriter;?
import?java.io.Writer;?
import?java.net.MalformedURLException;?
import?java.net.URL;?
import?org.apache.pdfbox.pdmodel.PDDocument;
import?org.apache.pdfbox.util.PDFTextStripper;
public?class?PdfReader?{?
public?void?readFdf(String?file)?throws?Exception?{?
//?是否排序?
boolean?sort?=?false;?
//?pdf文件名?
String?pdfFile?=?file;?
//?输入文本文件名称?
String?textFile?=?null;?
//?编码方式?
//?开始提取页数?
int?startPage?=?1;?
//?结束提取页数?
int?endPage?=?Integer.MAX_VALUE;?
//?文件输入流,生成文本文件?
Writer?output?=?null;?
//?内存中存储的PDF?Document?
PDDocument?document?=?null;?
try?{?
//?首先当作一个URL来装载文件,如果得到异常再从本地文件系统//去装载文件?
URL?url?=?new?URL(pdfFile);?
//注意参数已不是以前版本中的URL.而是File.?
document?=?PDDocument.load(pdfFile);?
//?获取PDF的文件名?
String?fileName?=?url.getFile();?
//?以原来PDF的名称来命名新产生的txt文件?
File?outputFile?=?new?File(fileName.substring(0,?fileName?
◆?".txt");?
textFile?=?outputFile.getName();?
}?
}?catch?(MalformedURLException?e)?{?
//?如果作为URL装载得到异常则从文件系统装载?
◆?".txt";?
//?文件输入流,写入文件倒textFile?
output?=?new?OutputStreamWriter(new?FileOutputStream(textFile),?
encoding);?
//?PDFTextStripper来提取文本?
PDFTextStripper?stripper?=?null;?
stripper?=?new?PDFTextStripper();?
//?设置是否排序?
stripper.setSortByPosition(sort);?
//?设置起始页?
stripper.setStartPage(startPage);?
//?设置结束页?
stripper.setEndPage(endPage);?
//?调用PDFTextStripper的writeText提取并输出文本?
stripper.writeText(document,?output);?
}?finally?{?
if?(output?!=?null)?{?
//?关闭输出流?
output.close();?
if?(document?!=?null)?{?
//?关闭PDF?Document?
document.close();?
/**?
*/?
public?static?void?main(String[]?args)?{?
//?TODO?Auto-generated?method?stub?
PdfReader?pdfReader?=?new?PdfReader();?
//?取得E盘下的SpringGuide.pdf的内容?
pdfReader.readFdf("d:\\b.pdf");?
}?catch?(Exception?e)?{?
e.printStackTrace();?
}
第一段:前言
第二段:iText简介
iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件.
第三段:建立第一个PDF文档
①建立com.lowagie.text.Document对象的实例.
Document document = new Document();
②建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中.
PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF"));
③打开文档.
document.open();
④向文档中添加内容.
document.add(new Paragraph("Hello World"));
⑤关闭文档.
document.close();
建立com.lowagie.text.Document对象的实例
com.lowagie.text.Document对象的构建函数有三个,分别是:
public Document();
public Document(Rectangle pageSize);
public Document(Rectangle pageSize,
int marginLeft,
int marginRight,
int marginTop,
int marginBottom);
书写器(Writer)对象
一旦文档(document)对象建立好之后,需要建立一个或多个书写器(Writer)对象与之关联.通过书写器(Writer)对象可以将具体文档存盘成需要的格式,如com.lowagie.text.PDF.PDFWriter可以将文档存成PDF文件,com.lowagie.text.html.HtmlWriter可以将文档存成html文件.
设定文档属性
public boolean addTitle(String title)
public boolean addSubject(String subject)
public boolean addKeywords(String keywords)
public boolean addAuthor(String author)
public boolean addCreator(String creator)
public boolean addProducer()
public boolean addCreationDate()
public boolean addHeader(String name, String content)
其中方法addHeader对于PDF文档无效,addHeader仅对html文档有效,用于添加文档的头信息.
当新的页面产生之前,可以设定页面的大小、书签、脚注(HeaderFooter)等信息,调用的方法是:
public boolean setPageSize(Rectangle pageSize)
public boolean add(Watermark watermark)
public void removeWatermark()
public void setHeader(HeaderFooter header)
public void resetHeader()
public void setFooter(HeaderFooter footer)
public void resetFooter()
public void resetPageCount()
public void setPageCount(int pageN)
如果要设定第一页的页面属性,这些方法必须在文档打开之前调用.
对于PDF文档,iText还提供了文档的显示属性,通过调用书写器的setViewerPreferences方法可以控制文档打开时Acrobat Reader的显示属性,如是否单页显示、是否全屏显示、是否隐藏状态条等属性.
另外,iText也提供了对PDF文件的安全保护,通过书写器(Writer)的setEncryption方法,可以设定文档的用户口令、只读、可打印等属性.
添加文档内容
所有向文档添加的内容都是以对象为单位的,如Phrase、Paragraph、Table、Graphic对象等.比较常用的是段落(Paragraph)对象,用于向文档中添加一段文字.
第四段:文本处理
iText中用文本块(Chunk)、短语(Phrase)和段落(paragraph)处理文本.
文本块(Chunk)是处理文本的最小单位,有一串带格式(包括字体、颜色、大小)的字符串组成.如以下代码就是产生一个字体为HELVETICA、大小为10、带下划线的字符串:
第五段:表格处理
iText中处理表格的类为:com.lowagie.text.Table和com.lowagie.text.PDF.PDFPTable,对于比较简单的表格处理可以用com.lowagie.text.Table,但是如果要处理复杂的表格,这就需要com.lowagie.text.PDF.PDFPTable进行处理.这里就类com.lowagie.text.Table进行说明.
类com.lowagie.text.Table的构造函数有三个:
①Table (int columns)
②Table(int columns, int rows)
③Table(Properties attributes)
参数columns、rows、attributes分别为表格的列数、行数、表格属性.创建表格时必须指定表格的列数,而对于行数可以不用指定.
建立表格之后,可以设定表格的属性,如:边框宽度、边框颜色、衬距(padding space 即单元格之间的间距)大小等属性.下面通过一个简单的例子说明如何使用表格,代码如下:
①.0:table.endHeaders();
运行结果如下:
header
cell test1 big cell
第六段:图像处理
iText中处理表格的类为com.lowagie.text.Image,目前iText支持的图像格式有:GIF, Jpeg, PNG, wmf等格式,对于不同的图像格式,iText用同样的构造函数自动识别图像格式.通过下面的代码分别获得gif、jpg、png图像的实例.
Image gif = Image.getInstance("vonnegut.gif");
Image jpeg = Image.getInstance("myKids.jpg");
Image png = Image.getInstance("hitchcock.png");
图像的位置
图像的位置主要是指图像在文档中的对齐方式、图像和文本的位置关系.IText中通过函数public void setAlignment(int alignment)进行处理,参数alignment为Image.RIGHT、Image.MIDDLE、Image.LEFT分别指右对齐、居中、左对齐;当参数alignment为Image.TEXTWRAP、Image.UNDERLYING分别指文字绕图形显示、图形作为文字的背景显示.这两种参数可以结合以达到预期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)显示的效果为图像右对齐,文字围绕图像显示.
图像的尺寸和旋转
如果图像在文档中不按原尺寸显示,可以通过下面的函数进行设定:
public void scaleAbsolute(int newWidth, int newHeight)
public void scalePercent(int percent)
public void scalePercent(int percentX, int percentY)
第七段:中文处理
Paragraph pragraph=new Paragraph("土嘎嘎的粉丝们大家好", FontChinese);
第八段:后计
iText还有很多高级的功能,这里就不一一介绍了,具体开发时可参考发布的文档.看完小编介绍的mysql怎么查看线程数,iText是一套java环境下不错的制作PDF的组件.因为iText支持jsp/javabean下的开发,这使得B/S应用中的报表问题能得到很好的解决.由于iText毕竟不是专门为制作报表设计,所有报表中的内容、格式都需要通过写代码实现,相对于那些专业的支持可视化设计的报表软件来说,编程的工作量就有一定程度的增加.
方法完全一致,有的机器不报错,有的报错,去他们论坛找高人解决也说不出原因,项目部署用它有点玄;itxt好像写很方便但是我查了好久资料没有见到过关
于读的好办法.经过一番选择还是折中点采用rtf最好,毕竟rtf是开源格式,不需要借助任何插件,只需基本IO操作外加编码转换即可.rtf格式文件表
面看来和doc没啥区别,都可以用word打开,各种格式都可以设定.
----- 实现的功能:读取rtf模板内容(格式和文本内容),替换变化部分,形成新的rtf文档.
----- 实现思路:模板中固定部分手动输入,变化的部分用$info$表示,只需替换$info$即可.
①.、采用字节的形式读取rtf模板内容
主要程序如下:
StringBuffer sb = new StringBuffer("");
byte[] bs = bin.getBytes();
int bit;
for (int i = 0; i bs.length;i◆◆) {
bit = (bs[i] 0x0f0)
sb.append("\\'");
sb.append(digital[bit]);
bit = bs[i] 0x0f;
return sb.toString();
public String readByteRtf(InputStream ins, String path){
String sourcecontent =
"";
try{
ins = new
FileInputStream(path);
byte[] b
if (ins == null) {
System.out.println("源模板文件不存在");
int bytesRead = 0;
while (true) {
counts
if(bytesRead == -1) {// end of InputStream
System.out.println("读取模板文件结束");
break;
sourcecontent ◆= new String(b, 0, bytesRead); // convert to string
using bytes
}catch(Exception e){
e.printStackTrace();
return sourcecontent ;
以上为核心代码,剩余部分就是替换,从新组装java中的String.replace(oldstr,newstr);方法可以实现,在这就不贴了.源代码部分详见附件.
运行源代码前提:
的文件.
package com;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class OperatorRTF {
public String strToRtf(String content){
byte[] bs = content.getBytes();
for (int i = 0; i bs.length; i◆◆) {
public String replaceRTF(String content,String replacecontent,int
flag){
String rc = strToRtf(replacecontent);
String target = "";
if(flag==0){
target = content.replace("$timetop$",rc);
if(flag==1){
target = content.replace("$info$",rc);
target = content.replace("$idea$",rc);
target = content.replace("$advice$",rc);
target = content.replace("$infosend$",rc);
return target;
public String getSavePath() {
String path = "C:\\YQ";
File fDirecotry = new File(path);
if (!fDirecotry.exists()) {
fDirecotry.mkdirs();
return path;
public String ToSBC(String input){
char[] c =
input.toCharArray();
for (int i =
0; i c.length; i◆◆){
continue;
return new
String(c);
public void rgModel(String username, String content) {
// TODO Auto-generated method stub
Date current=new Date();
SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd
HH:mm:ss");
targetname ◆= "_" ◆ username ◆"_记录.rtf";
String strpath = getSavePath();
String sourname = strpath◆"\\"◆"模板.rtf";
String sourcecontent = "";
InputStream ins = null;
ins = new FileInputStream(sourname);
String targetcontent = "";
String array[] = content.split("~");
for(int i=0;iarray.length;i◆◆){
if(i==0){
targetcontent = replaceRTF(sourcecontent, array[i], i);
}else{
targetcontent = replaceRTF(targetcontent, array[i], i);
try {
FileWriter fw = new FileWriter(getSavePath()◆"\\" ◆
targetname,true);
PrintWriter out = new PrintWriter(fw);
if(targetcontent.equals("")||targetcontent==""){
out.println(sourcecontent);
out.println(targetcontent);
out.close();
fw.close();
System.out.println(getSavePath()◆" 该目录下生成文件" ◆
targetname ◆ " 成功");
} catch (IOException e) {
// TODO Auto-generated catch block
public static void main(String[] args) {
OperatorRTF oRTF = new OperatorRTF();
String content =
oRTF.rgModel("cheney",content);
java字符串如何解析成运行的java代码
int i = 10;
code ◆= "for(int i=0;i" ◆ i ◆ ";i◆◆){";
code ◆= "}";
run(code);
} catch (Exception e) {
private synchronized static File compile(String code) throws Exception {
File file = File.createTempFile("JavaRuntime", ".java", new File(System.getProperty("user.dir")));
file.deleteOnExit();
// 获得类名
String classname = getBaseFileName(file);
// 将代码输出到文件
PrintWriter out = new PrintWriter(new FileOutputStream(file));
out.println(getClassCode(code, classname));
// 编译生成的java文件
String[] cpargs = new String[] { "-d",
System.getProperty("user.dir") ◆ "\\WebRoot\\WEB-INF\\classes",
file.getName() };
int status = Main.compile(cpargs);
if (status != 0) {
throw new Exception("语法错误!");
return file;
private static synchronized void run(String code) throws Exception {
String classname = getBaseFileName(compile(code));
new File(System.getProperty("user.dir")
◆ "\\WebRoot\\WEB-INF\\classes\\" ◆ classname ◆ ".class")
.deleteOnExit();
Class cls = Class.forName(classname);
Method main = cls.getMethod("method", null);
main.invoke(cls, null);
} catch (Exception se) {
se.printStackTrace();
private static String getClassCode(String code, String className) {
StringBuffer text = new StringBuffer();
text.append("public class " ◆ className ◆ "{\n");
text.append(" public static void method(){\n");
text.append(" " ◆ code ◆ "\n");
text.append(" }\n");
text.append("}");
return text.toString();
private static String getBaseFileName(File file) {
String fileName = file.getName();
int index = fileName.indexOf(".");
String result = "";
if (index != -1) {
result = fileName.substring(0, index);
} else {
result = fileName;
return result;
建一个Student实体类封装数据
public static ListStudent readXml() {
ListStudent list = new ArrayListStudent();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder dom = factory.newDocumentBuilder();
Document doc=dom.parse(file);
//
Element root = doc.getDocumentElement();
NodeList stuNodeList = root.getChildNodes();
for (int i = 0; i stuNodeList.getLength(); i◆◆) {
Node stu = stuNodeList.item(i);
Student student = new Student();
if (stu != null stu.getNodeType() == Node.ELEMENT_NODE) {
// System.out.println(stu);
Element stuElement = (Element) stu;
student.setNo(stuElement.getAttribute("id"));
// stu.getAttributes().getNamedItem(null);
// Element stu=(Element)stuNodeList
NodeList info = stuElement.getChildNodes();
for (int j = 0; j info.getLength(); j◆◆) {
info.item(j).getNodeName();
Node n = info.item(j);
if ("name".equals(n.getNodeName())) {
// n.getFirstChild().getNodeValue();
student.setName(n.getLastChild().getNodeValue());
} else if ("age".equals(n.getNodeName())) {
student.setAge(Integer.parseInt(n.getFirstChild()
.getNodeValue()));
list.add(student);
} catch (ParserConfigurationException e) {
} catch (SAXException e) {
// System.out.println(root.getNodeValue());
return list;
lrc可以通过如下util工具类进行转换,如果想知道结果是否读取的有问题,可以直接用记事本打开lrc文件的,之后和输出结果比对一下就行.
package com.routon.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.util.Log;
/**
* parse lrc file tool
* eg:
* utilLrc lrc = new utilLrc("/sdcard/test.lrc");
* get song name : String title = lrc.getTitle();
* get performer name : String artist = lrc.getArtist();
* get album name: String album = lrc.getAlbum();
* get lrcmaker name: String lrcMaker = lrc.getLrcMaker();
* get song list: ListStatement list = lrc.getLrcList();
*
* @author xuweilin
*/
public class utilLrc {
private static String TAG = "utilLrc";
public class Statement {
private double time = 0.0;//time, 0.01s
private String lyric = "";//song word
/*
* get time
public double getTime() {
return time;
* set time
public void setTime(double time) {
this.time = time;
* set time.format:mm:ss.ms
public void setTime(String time) {
String str[] = time.split(":|\\.");
* get lrc word
public String getLyric() {
return lyric;
* set lrc word
public void setLyric(String lyric) {
this.lyric = lyric;
private BufferedReader bufferReader = null;
private String title = "";
private String artist = "";
private String album = "";
private String lrcMaker = "";
private ListStatement statements = new ArrayListStatement();
* fileName
public utilLrc(String fileName) throws IOException{
FileInputStream file = new FileInputStream(fileName);
readData();
* read the file
private void readData() throws IOException{
statements.clear();
String strLine;
while(null != (strLine = bufferReader.readLine()))
{
if("".equals(strLine.trim()))
if(null == title || "".equals(title.trim()))
Pattern pattern = Pattern.compile("\\[ti:(.◆?)\\]");
Matcher matcher = pattern.matcher(strLine);
if(matcher.find())
title=matcher.group(1);
if(null == artist || "".equals(artist.trim()))
Pattern pattern = Pattern.compile("\\[ar:(.◆?)\\]");
artist=matcher.group(1);
if(null == album || "".equals(album.trim()))
Pattern pattern = Pattern.compile("\\[al:(.◆?)\\]");
album=matcher.group(1);
if(null == lrcMaker || "".equals(lrcMaker.trim()))
Pattern pattern = Pattern.compile("\\[by:(.◆?)\\]");
lrcMaker=matcher.group(1);
int timeNum=0;
String str[] = strLine.split("\\]");
for(int i=0; istr.length; ◆◆i)
if(isTime(str[i])){
◆◆timeNum;
for(int i=0; itimeNum;◆◆i)
Statement sm = new Statement();
sm.setTime(str[i]);
if(timeNumstr.length)
sm.setLyric(str[str.length-1]);
statements.add(sm);
sortLyric();
* judge the string is or not date format.
private boolean isTime(String string)
String str[] = string.split(":|\\.");
return false;
for(int i=0;istr.length;◆◆i)
Integer.parseInt(str[i]);
catch(NumberFormatException e)
Log.e(TAG, "isTime exception:"◆e.getMessage());
return true;
* sort the word by time.
private void sortLyric()
for(int i=0;istatements.size()-1;◆◆i)
int index=i;
double delta=Double.MAX_VALUE;
boolean moveFlag = false;
for(int j=i◆1;jstatements.size();◆◆j)
double sub;
if(0=(sub=statements.get(i).getTime()-statements.get(j).getTime()))
moveFlag=true;
if(subdelta)
delta=sub;
index=j◆1;
if(moveFlag)
statements.add(index, statements.get(i));
statements.remove(i);
--i;
* get title
* @return
public String getTitle(){
return title;
* get artist
public String getArtist(){
return artist;
* get album
public String getAlbum(){
return album;
* get lrc maker
public String getLrcMaker(){
return lrcMaker;
* get song list
public ListStatement getLrcList(){
return statements;