pdf2text.java

来自「一个搜索引擎,希望对大家有用」· Java 代码 · 共 92 行

JAVA
92
字号
package ch7.xpdf;

import java.io.*;

public class Pdf2Text {
	// PDF文件名
	private File pdffile;

	// 转换器的存放位置,默认在c:\xpdf下面
	private String CONVERTOR_STORED_PATH = "c:\\xpdf";

	// 转换器的名称,默认为pdftotext
	private String CONVERTOR_NAME = "pdftotext";

	// 构造函数,参数为pdf文件的路径

	public Pdf2Text(String pdffile) throws IOException {
		this(new File(pdffile));
	}

	// 构造函数,参数为pdf文件的对像
	public Pdf2Text(File pdffile) throws IOException {
		this.pdffile = pdffile;
	}

	// 将pdf转为文本文档
	public void toTextFile() throws IOException {
		toTextFile(pdffile, true);
	}

	// 将pdf转为文本文档,参数为目标文件的路径,默认使用PDF文件中的布局
	public void toTextFile(String targetfile) throws IOException {
		toTextFile(new File(targetfile), true);
	}

	// 将pdf转为文本文档,参数1为目标文件的路径,
	// 参数2为true则表示使用PDF文件中的布局
	public void toTextFile(String targetfile, boolean isLayout)
			throws IOException {
		toTextFile(new File(targetfile), isLayout);
	}

	// 将pdf转为文本文档,参数为目标文件
	public void toTextFile(File targetfile) throws IOException {
		toTextFile(targetfile, true);
	}

	// 将pdf转为文本文档,参数1为目标文件,
	// 参数2为true则表示使用PDF文件中的布局
	public void toTextFile(File targetfile, boolean isLayout)
			throws IOException {
		String[] cmd = getCmd(targetfile, isLayout);
		Process p = Runtime.getRuntime().exec(cmd);
	}

	// 获取PDF转换器的路径
	public String getCONVERTOR_STORED_PATH() {
		return CONVERTOR_STORED_PATH;
	}

	// 设置PDF转换器的路径
	public void setCONVERTOR_STORED_PATH(String path) {
		if (!path.trim().endsWith("\\"))
			path = path.trim() + "\\";
		this.CONVERTOR_STORED_PATH = path;
	}

	// 解析命令行参数
	private String[] getCmd(File targetfile, boolean isLayout) {
		// 命令字符
		String command = CONVERTOR_STORED_PATH + CONVERTOR_NAME;
		// PDF文件的绝对路径
		String source_absolutePath = pdffile.getAbsolutePath();
		// 输出文本文件的绝对路径
		String target_absolutePath = targetfile.getAbsolutePath();
		// 保持原来的layout
		String layout = "-layout";
		// 设置编码方式
		String encoding = "-enc";
		String character = "GBK";
		// 设置不打印任何消息和错误
		String mistake = "-q";
		// 页面之间不加入分页
		String nopagebrk = "-nopgbrk";
		// 如果isLayout为false,则设置不保持原来的layout
		if (!isLayout)
			layout = "";
		return new String[] { command, layout, encoding, character, mistake,
				nopagebrk, source_absolutePath, target_absolutePath };
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?