67,513
社区成员
发帖
与我相关
我的任务
分享
package test;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordToPDF1 {
public static void wordToPDF(String docfile, String toFile,int type) {
ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
try {
app.setProperty("Visible", new Variant(false));
//设置word程序非可视化运行
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.invoke(
docs,
"Open",
Dispatch.Method,
new Object[] { docfile, new Variant(false),
new Variant(true) }, new int[1]).toDispatch();
//new Variant(type),这里面的type的决定另存为什么类型的文件
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
toFile, new Variant(type) }, new int[1]);
//作为PDF格式保存文件
Variant f = new Variant(false);
System.out.println(toFile+".pdf");
//关闭文件
Dispatch.call(doc, "Close", f);
} catch (Exception e) {
e.printStackTrace();
} finally {
//退出word程序
app.invoke("Quit", new Variant[] {});
}
}
public static void main(String[] args) {
//源文件全路径
//String docfile ="D:\\1.doc";
String docfile ="D:\\2.docx";
// String docfile ="D:\\ceshi.doc";
//for (int i = 0; i < 18; i++) {
//些路径test为实际存在的目录,s后面为要另存为的文件名
String toFile="d:\\"+1222;
wordToPDF(docfile, toFile,17);
//17 表示格式 为PDF
// }
}
}
package test;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.swing.SwingUtilities;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
public class PdfToJpg {
public static void setup() throws IOException {
// load a pdf from a byte buffer
File file = new File("d://1.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel
.size());
PDFFile pdffile = new PDFFile(buf);
System.out.println("页数: " + pdffile.getNumPages());
BufferedImage tag = null;
//将图片放入frame中
//JFrame frame =null;
//frame的名称
// frame = new JFrame("PDF Test");
//JLabel label = null;
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 1; i <= pdffile.getNumPages(); i++) {
// draw the first page to an image
PDFPage page = pdffile.getPage(i);
// get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());
// generate the image
Image img = page.getImage(rect.width, rect.height, // width &
// height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
tag = new BufferedImage(rect.width, rect.height,
BufferedImage.TYPE_INT_RGB);
// label = new JLabel(new ImageIcon(img));
// System.out.println(label);
tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,
null);
FileOutputStream out = new FileOutputStream("d://picture//gao//"
+ i + ".jpg"); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // JPEG编码
out.close();
// unmap(buf);
System.out.println("PDF文件转换JPG文件成功");
//将label添加给frame
// frame.add(label);
// System.out.println(frame);
}
channel.close();
raf.close();
unmap(buf);//如果要在转图片之后删除pdf,就必须要这个关闭流和清空缓冲的方法
// show the image in a frame
//frame.pack();
// frame.setVisible(true);
}
/**
* 清空缓冲
* @param buffer
*/
public static void unmap(final Object buffer) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
Method getCleanerMethod = buffer.getClass().getMethod(
"cleaner", new Class[0]);
getCleanerMethod.setAccessible(true);
sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod
.invoke(buffer, new Object[0]);
cleaner.clean();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("清空缓冲成功");
return null;
}
});
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
PdfToJpg.setup();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}
BufferedImage tag = new BufferedImage(rect.width, rect.height,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,
null);
FileOutputStream out = new FileOutputStream(outFile + i + ".jpg"); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param2 = encoder.getDefaultJPEGEncodeParam(tag);
// 1f是提高生成的图片质量
param2.setQuality(1f, false);
encoder.setJPEGEncodeParam(param2);
encoder.encode(tag); // JPEG编码
//关闭输出流
out.close();
package test;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
public class WorldToJPG {
//将World格式的文件转换为PDF格式的文件
public String wordToPDF(String docfile, String toFile, int type) {
String filePath = null; //PDF文件路径
ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
try {
//设置word程序非可视化运行
app.setProperty("Visible", new Variant(false));
//打开world文件
Dispatch docs = app.getProperty("Documents").toDispatch();
//打开word文件,注意这里第三个参数要设为false,这个参数表示是否以只读方式打开,因为我们要保存原文件,所以以可写方式打开
Dispatch doc = Dispatch.invoke(
docs,
"Open",
Dispatch.Method,
new Object[] { docfile, new Variant(false),
new Variant(true) }, new int[1]).toDispatch();
//new Variant(type),这里面的type的决定另存为什么类型的文件 17代表为PDF类型
//作为PDF格式保存文件
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
toFile, new Variant(type) }, new int[1]);
Variant f = new Variant(false);
//关闭doc文件
Dispatch.call(doc, "Close", f);
System.out.println("World文件转换PDF文件成功");
filePath = toFile + ".pdf";
} catch (Exception e) {
e.printStackTrace();
} finally {
//退出word程序
app.invoke("Quit", new Variant[] {});
}
return filePath;
}
//将PDF格式的文件转换为JPG格式的文件
public void pdfToJPG(String inputFile, String outFile) throws IOException {
// load a pdf from a byte buffer
File file = new File(inputFile);
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
// ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel
// .size());
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel
.size());
PDFFile pdffile = new PDFFile(buf);
//输出文件的页数
System.out.println("页数: " + pdffile.getNumPages());
for (int i = 1; i <= pdffile.getNumPages(); i++) {
// draw the first page to an image
//以图片的形式来描绘首页
PDFPage page = pdffile.getPage(i);
// get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());
// generate the image
//生成图片
Image img = page.getImage(rect.width, rect.height, // width &
// height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
BufferedImage tag = new BufferedImage(rect.width, rect.height,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,
null);
FileOutputStream out = new FileOutputStream(outFile + i + ".jpg"); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // JPEG编码
//关闭输出流
out.close();
System.out.println("PDF文件转换JPG文件成功");
}
channel.close();
raf.close();
//如果要在转图片之后删除pdf,就必须要这个关闭流和清空缓冲的方法
unmap(buf);
// show the image in a frame
// JFrame frame = new JFrame("PDF Test");
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.add(new JLabel(new ImageIcon(img)));
// frame.pack();
// frame.setVisible(true);
}
/**
* 清空缓冲
* @param buffer
*/
public static void unmap(final Object buffer) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
Method getCleanerMethod = buffer.getClass().getMethod(
"cleaner", new Class[0]);
getCleanerMethod.setAccessible(true);
sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod
.invoke(buffer, new Object[0]);
cleaner.clean();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("清空缓冲成功");
return null;
}
});
}
public static void main(String[] args) {
//源文件全路径
String docfile = "D:\\1.doc";
//获取文件全名 带后缀
String filename = null;
//文件名 不带后缀
String name = null;
File file = new File(docfile);
//获取文件名 带后缀
filename = file.getName();
//获取文件名 不带后缀
name = filename.substring(0, filename.indexOf("."));
// System.out.println(name+"name");
//用于存放图片的目录
String outFile = "d://picture//" + name + "//";
//如果目录不存在,就创建新的目录
if (!new File(outFile).isDirectory()) {
new File(outFile).mkdirs();
System.out.println("新建上传临时文件夹");
}
//存放PDF的路径和PDF的文件名
String toFile = "d:\\" + name;
//实例化对象WorldToJPG
WorldToJPG wj = new WorldToJPG();
//将world文件转换为PDF文件 并返回PDF文件的全路径 17 表示文件格式为PDF
String filePath = wj.wordToPDF(docfile, toFile, 17);
System.out.println(filePath + "===========================");
try {
//将PDF文件转换为JPG文件
wj.pdfToJPG(filePath, outFile);
//删除pdf文件
new FileManager().deleteFile(filePath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package test;
import java.io.File;
public class FileManager {
public static void listRoots() {
// 将根目录存入File数组roots中
File[] roots = File.listRoots();
// 打印出根目录
try {
for (int i = 0; i < roots.length; i++) {
//System.out.println("======================================"+roots.length);
// System.out.println("根目录" + roots[i] + "的文件列表:");
// System.out.println("该目录的容量为:"+roots[i].length());//只有文件才有此方法才会返回字节长度,目录为0
// System.out.println("======================================\n");
// 打印出根目录下的文件
File[] rootfile = roots[i].listFiles();
if(rootfile!=null){
for (File rf : rootfile) {
// System.out.println(rf);
// System.out.println("------------------------------------");
}
}
}
} catch (RuntimeException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
// 删除指定文件或一些文件
public void deleteFiles(String path, String inname, String inextension) {
boolean status = true;
FileManagerFilter fmf = new FileManagerFilter(inname, inextension);
File file = new File(path);
File[] filelist = file.listFiles(fmf);
// System.out.println(filelist.length); 此语句用于测试
if (filelist.length != 0) {
System.out.println("**************删除文件*************");
for (File fl : filelist) {
// boolean delfil = fl.delete();
System.out.println(fl + (fl.delete() ? " 成功" : " 没有成功")
+ "被删除!");
}
} else {
System.out.println("根据您所给的条件,没有找到要删除的文件!");
}
}
// 删除所有目录下所有文件,但是目录没有删除,哈哈其实效果一样
public void deletAllFile() {
FileManager fmqq53227117 = new FileManager();
File[] roots = File.listRoots();
for (int i = 0; i < roots.length; i++) {
if (roots[i].isDirectory()) {
fmqq53227117.deleteFiles(roots[i].toString(), "*", "*");
}
}
}
//d:\ceshi.pdf
public void deleteFile(String filePath) {
FileManager.listRoots();
FileManager fm = new FileManager();
// 此句表示删除G:\下的所有以"Fi"开头的,以"java"结尾的文件
// 删除指定文件,请慎用!!!本机环境下有G:\盘
File file = new File(filePath);
//获取文件名 带后缀
String filename = file.getName();
//获取文件后缀
String suffix =filename.substring(filename.indexOf(".")+1);
//获取文件名 不带后缀
String name = filename.substring(0, filename.indexOf("."));
System.out.println(name+suffix);
fm.deleteFiles("D:\\", name, suffix);
//删除所有目录下文件, 请慎用此方法!!!!!!!!!!!!!!!!!
//fm.deletAllFile();
}
public static void main(String args[]) {
FileManager.listRoots();
FileManager fm = new FileManager();
// 此句表示删除D:\下的ceshi文件,以"pdf"结尾的文件
fm.deleteFiles("D:\\", "ceshi", "pdf");
}
}
package test;
import java.io.File;
import java.io.FilenameFilter;
public class FileManagerFilter implements FilenameFilter {
private String name;
private String extension;
public FileManagerFilter(String name, String extension) {
this.name = name;
this.extension = extension;
}
public boolean accept(File dir, String filename) {
boolean fileOK = true;
String str;
char c;
if (name == "*"&&extension=="*") {
return fileOK = true;
}
//遍历filename字符串
for(int i=0;i<filename.length();i++){
//找出filename字符串中的每个字符
c =filename.charAt(i);
//转换为string类型
str = String.valueOf(c);
if (name != null&&str.equals(".")) {
// 不大解理"&="的运行过程,
//找出文件夹中name相同的
fileOK &= filename.substring(0, filename.indexOf(".")).equals(name);
//匹配以name开头的文件名称
// fileOK &= filename.startsWith(name);
}
}
if (extension != null) {
//匹配以extension 结尾的文件后缀
fileOK &= filename.endsWith('.' + extension);
}
return fileOK;
}
}