本帖最后由 qqwwdr 于 2014-2-26 21:47 编辑
我在网上找到了一个 可以做出来,
我也测试过可行,
要导入几个包:tm-extractors.jar,bcprov-jdk16-145.jar,iText.jar,iTextAsian.jar;
这个网站上可以下载到这几个包,http://www.java2s.com/;
注意:为了偷懒,这里要求输入的 文件路径 以 “/”作为分割符,“\\"这样的分割符在程序里没有处理。
而且,对路径没有做判断,小心 ,呵呵。
- package wxn.itheima.com;
- import java.io.*;
- import java.util.Scanner;
- import org.textmining.text.extraction.WordExtractor;
- import com.lowagie.text.Document;
- import com.lowagie.text.DocumentException;
- import com.lowagie.text.Font;
- import com.lowagie.text.PageSize;
- import com.lowagie.text.Paragraph;
- import com.lowagie.text.pdf.BaseFont;
- import com.lowagie.text.pdf.PdfWriter;
- public class Word2Pdf {
-
- public static void main(String[] args){
- System.out.println("请输入需要转换成pdf的word文档路径:");
- Scanner scanner = new Scanner(System.in);
- String path = null;
- if(scanner.hasNext()){
- path = scanner.next();
- }
- if(path == null || path.length()<=3){
- System.out.println("路径错误");
- }
- //调用方法
- try {
- String fileName = path.substring(path.lastIndexOf('/') +1, path.lastIndexOf('.'));
- write(getWord(path),"D:/Download/"+fileName+".pdf");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static String getWord(String path) {
- System.out.println("==============================");
- System.out.println("Extract word start:===========");
- File file = new File(path);
- String returnString = "";
- InputStream is;
- try {
- is = new FileInputStream(file);
- WordExtractor extractor = new WordExtractor();
- returnString = extractor.extractText(is);
- System.out.println("Extract word end:===========");
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return returnString;
- }
- public static void write(String content, String filePath)
- throws IOException {
- System.out.println("==============================");
- System.out.println("Write to pdf start:===========");
- final int margin = 10;
- // create the file
- File file = new File(filePath);
- if (!file.exists()) {
- Document doc = null;
- FileOutputStream fos = null;
- PdfWriter pdfWriter = null;
-
- try {
- BaseFont bFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
- Font font = new Font(bFont);
- font.setSize(8);
- doc = new Document(PageSize.A4, margin, margin, margin, margin);
- fos = new FileOutputStream(file);
- pdfWriter = PdfWriter.getInstance(doc, fos);
- doc.open();
- //doc.addTitle(filePath.replace("D:\\", ""));
- doc.add(new Paragraph(content, font));
- System.out.println("Write to pdf end:===========");
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (DocumentException e) {
- e.printStackTrace();
- } finally {
- if (doc != null) {
- doc.close();
- }
- if (pdfWriter != null) {
- pdfWriter.close();
- }
- if (fos != null) {
- fos.close();
- }
- }
- }
- }
- }
复制代码
原网页:http://bbs.csdn.net/topics/390118992
|