java开发PDF转Word

pom.xml文件引用java包

    
    
        org.apache.pdfbox
        pdfbox
        2.0.20

 

PDFUtils.java

package com.view.web.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.view.web.common.dto.FontsProvider;

/**
 * 
 * @DATE 2017年9月29日
 * @Description 新的生成PDF方法
 *
 */
public class PDFUtils {

	private static Logger logger = Logger.getLogger(PDFUtils.class);

	
	
	
	/**
	 * PDF转Word
	 */
	public static void PdfToWord(String pdfPath,String docPath){
		PDDocument pdf = null;
		FileOutputStream docFos = null;
		Writer docWriter = null;
		 try {

	            pdf = PDDocument.load(new File(pdfPath));
	            int pagenumber = pdf.getNumberOfPages();
	            String pdfFileName = pdfPath.substring(pdfPath.lastIndexOf("/")+1, pdfPath.lastIndexOf("."));
	            String docFileName = pdfFileName + ".doc";
	            File docFile = new File(docPath+File.separator+ docFileName);
	            if (!docFile.exists()) {
	            	docFile.createNewFile();
	            }
	            
	            docFos = new FileOutputStream(docFile);
	            docWriter = new OutputStreamWriter(docFos, "UTF-8");
	            PDFTextStripper stripper = new PDFTextStripper();
	            stripper.setSortByPosition(true);// 排序
	            stripper.setStartPage(1);// 设置转换的开始页
	            stripper.setEndPage(pagenumber);// 设置转换的结束页
	            stripper.writeText(pdf, docWriter);
	            logger.info(pdfFileName+"文件已转换完成");
	        } catch (IOException e) {
	        	logger.error("PDF转word失败:",e);
	        }finally{
	        	if(docWriter!=null){
	        		try {
						docWriter.close();
					} catch (IOException e) {
						logger.error("PDF转word后,关闭docWriter流失败:",e);
					}
	        	}
	        	
	        	if(pdf!=null){
	        		try {
						pdf.close();
					} catch (IOException e) {
						logger.error("PDF转word后,关闭pdf流失败:",e);
					}
	        	}
	        	
	        }
	}
	
	
	
	

}

 

你可能感兴趣的:(JAVA,java)