PDFBOX操作pdf文件,pdf转word,pdf分割

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;

import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.junit.Test;

public class PDFToWord {
	/**
	 * 第一版
	 * 只是转换文字
	 */
	@Test
	public void pdfToWordOfText(){
		try {
			//pdf文件路径
			String filePath = "C:/Users/Administrator/Desktop/测试1.pdf";
			File fdf = new File(filePath);
			//生成的word的文件路径
			String wordPath = "C:/Users/Administrator/Desktop/测试1.doc";
			//通过文件名加载文档
			PDDocument doc = PDDocument.load(fdf);
			//获取文档的页数
			int pageNumber = doc.getNumberOfPages();
			//剥离器(读取pdf文件)
			PDFTextStripper  stripper = new PDFTextStripper();
			//排序
			stripper.setSortByPosition(true);
			//设置要读取的起始页码
			stripper.setStartPage(1);
			//设置要读取的结束页码
			stripper.setEndPage(pageNumber);
			File word = new File(wordPath);
			if(!word.exists()){
				word.createNewFile();
			}
			//文件输出流
			FileOutputStream fos = new FileOutputStream(word);
			//
			Writer  writer = new OutputStreamWriter(fos, "utf-8");
			stripper.writeText(doc, writer);
			writer.close();
			fos.close();
			System.out.println("转码完成");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 拆分pdf文件
	 */
	@Test
	public void pdfOfSplit(){
		String resourcePath = "C:/Users/Administrator/Desktop/测试.pdf";
		File resource = new File(resourcePath);		
		try {
			//加载文档
			PDDocument doc = PDDocument.load(resource);
			//分割操作
			Splitter  split = new Splitter ();
			//设置从那页开始分割
			split.setStartPage(1);
			//设置每个文件多少页
			split.setSplitAtPage(200);
			//分割文档
			List docs = split.split(doc);
			int i =1;
			//生成分割文档
			for(PDDocument document:docs){
				String fileName = "C:/Users/Administrator/Desktop/测试"+i+".pdf";
				File file = new File(fileName);
				if(!file.exists()){
					file.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(file);
				document.save(fos);
				document.close();
				i++;
				
			}
			doc.close();
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

 

你可能感兴趣的:(pdfbox)