word文档 pdf在线预览方案
2016-06-29 11:34
288 查看
word转pdf
往java jdk的bin 目录下加文件jacob-1.18-M3-x64.dll或者jacob-1.18-M3-x86.dll 不记得自己jdk啥版本的就都加好了
word转pdf的代码
public class Word2PDF {
static final int wdDoNotSaveChanges = 0;
static final int wdFormatPDF = 17;// PDF 格式
public static void main(String[] args) {
List<File> words = listWordFiles(new File("G:\\chen"));
for (File file : words) {
word2pdf(file);
}
}
public static void word2pdf(File file) {
if (file.exists() && file.canExecute() && file.isFile()) {
String fileName = file.getName();
int lastDotIndex = fileName.lastIndexOf(".");
String toFileName = fileName.substring(0, lastDotIndex) + ".pdf";
String toFilePath = file.getParent() + "/" + toFileName;
System.out.println("启动Word...");
long start = System.currentTimeMillis();
ActiveXComponent app = null;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);
Dispatch docs = app.getProperty("Documents").toDispatch();
System.out.println("打开文档..." + file.getAbsolutePath());
Dispatch doc = Dispatch.call(docs, "Open", file.getAbsolutePath(), false,true ).toDispatch();
System.out.println("转换文档到PDF..." + toFilePath);
File tofile = new File(toFilePath);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc,"SaveAs", toFilePath, wdFormatPDF);
Dispatch.call(doc, "Close", false);
long end = System.currentTimeMillis();
System.out.println("转换完成..用时:" + (end - start) + "ms.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("文档转换失败:" + e.getMessage());
} finally {
if (app != null)
app.invoke("Quit", wdDoNotSaveChanges);
}
}
}
}
public class LineFileWriter {
private final static String TAG = "\t";
private String separator;
private BufferedWriter writer;
public LineFileWriter(File toFile) throws IOException {
this(toFile, TAG);
}
public LineFileWriter(File toFile, String separator) throws IOException {
this.separator = separator;
if (!toFile.getParentFile().exists()) {
toFile.getParentFile().mkdirs();
}
writer = new BufferedWriter(new FileWriter(toFile));
}
public void write(String... terms) throws IOException {
for (String term : terms) {
writer.write(term);
writer.write(separator);
}
writer.newLine();
}
public void close() throws IOException {
writer.flush();
writer.close();
}
}
转成pdf后 有两种预览方式
一种 直接用pdf.js 只了解过 没实际用过 哈哈
一种 用 flexpaper 这个麻烦些 他需要把pdf转成swf格式 才行 可以下个swfTools
辅助代码
public class PDF2SWF {
public final static String replaceBase = "G:\\chen\\";
public final static String CMD_PDF_2_SWF = "E:\\Program Files (x86)\\SWFTools\\pdf2swf.exe";
public static void main(String[] args) throws IOException {
List<File> words = listWordFiles(new File("G:\\chen\\"));
LineFileWriter infoWriter = new LineFileWriter(new File("E:\\chen\\info.log"));
LineFileWriter errWriter = new LineFileWriter(new File("E:\\chen\\err.log"));
for (File word : words) {
pdf2swf(word, infoWriter, errWriter);
}
infoWriter.close();
errWriter.close();
}
public static void pdf2swf(File docFile, LineFileWriter infoWriter, LineFileWriter errWriter) {
try {
long startTime = System.currentTimeMillis();
String docAbsolutePath = docFile.getAbsolutePath();
String fileKey = docAbsolutePath.replace(replaceBase, "");
String pdfAbsolutePath = docAbsolutePath.replace(".docx", ".pdf").replace(".doc", ".pdf");
File pdfFile = new File(pdfAbsolutePath);
String swfBasePath = pdfAbsolutePath.replace(".pdf", "");
PDDocument doc = PDDocument.load(pdfFile);
int pageCount = doc.getNumberOfPages();
doc.close();
boolean result = true;
System.out.println("处理:" + pdfAbsolutePath + ",页数:" + String.valueOf(pageCount) + "");
for (int i = 1; i <= pageCount; i++) {
String command = CMD_PDF_2_SWF + " " + pdfFile.getAbsolutePath() + " -o " + swfBasePath + "_" + i
+ ".swf -f -T 9 -t -s storeallcharacters -s linknameurl -p " + i;
ArrayList commands = commandLineAsList(command);
ProcessBuilder pb = new ProcessBuilder(commands);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
if (line.toLowerCase().startsWith("warning")) {
errWriter.write(pdfAbsolutePath, "WARNING: " + line, String.valueOf(i));
} else if (line.toLowerCase().startsWith("error")) {
errWriter.write(pdfAbsolutePath, "ERROR:" + line, String.valueOf(i));
result = false;
} else if (line.toLowerCase().startsWith("fatal")) {
errWriter.write(pdfAbsolutePath, "FATAL:" + line, String.valueOf(i));
result = false;
} else {
// infoWriter.write(pdfFile.getAbsolutePath(), pageCount + "");
// System.out.println("\t" + line);
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
errWriter.write(pdfAbsolutePath, "FATAL:" + line, String.valueOf(i));
result = false;
}
}
}
if (result) {
infoWriter.write(fileKey, String.valueOf(pageCount));
}
System.out.println("用时:" + (System.currentTimeMillis() - startTime) + "毫秒");
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList commandLineAsList(String commandLine) {
ArrayList commands = new ArrayList();
String elt = "";
boolean insideString = false;
for (int i = 0; i < commandLine.length(); i++) {
char c = commandLine.charAt(i);
if (!insideString && (c == ' ' || c == '\t')) {
if (elt.length() > 0) {
commands.add(elt);
elt = "";
}
continue;
} else
4000
if (c == '"') {
insideString = !insideString;
}
elt += c;
}
if (elt.length() > 0) {
commands.add(elt);
}
return commands;
}
public static List<File> listWordFiles(File file) {
List<File> fs = new ArrayList<>();
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
if (f.isFile() && isWordFile(f)) {
fs.add(f);
} else if (f.isDirectory()) {
fs.addAll(listWordFiles(f));
}
}
}
return fs;
}
public static boolean isWordFile(File file) {
return file != null && file.isFile() && (file.getName().endsWith(".doc") || file.getName().endsWith(".docx"));
}
}
前端使用
先去下载 flexpaper.js 和FlexPaperViewer.swf
<div id="documentViewer" class="flexpaper_viewer" style="width:760px;height:1000px"></div>
js:
function getDocumentUrl(document){
var numPages = ${paper.swfCount};
var id = ${paper.id};
var url = "{"+ id +"/swf?pageNum=[*,0],{numPages}}";
url = url.replace("{numPages}",numPages);
return url;
}
$('#documentViewer').FlexPaperViewer(
{ config : {
SWFFile : escape(getDocumentUrl()),
Scale : 1.0,
ZoomTransition : 'easeOut',
ZoomTime : 0.5,
ZoomInterval : 0.1,
FitPageOnLoad : false,
FitWidthOnLoad : true,
FullScreenAsMaxWindow : false,
ProgressiveLoading : false,
MinZoomSize : 0.1,
MaxZoomSize : 5,
SearchMatchAll : false,
InitViewMode : 'Portrait',
RenderingOrder : 'flash',
StartAtPage : '',
ViewModeToolsVisible : true,
ZoomToolsVisible : true,
NavToolsVisible : true,
CursorToolsVisible : true,
SearchToolsVisible : true,
WMode : 'opaque',
key : 'XXXXXXX',
localeChain: 'zh_CN'
}}
);
大致如此 都是前人的智慧,掏出来做个笔记
往java jdk的bin 目录下加文件jacob-1.18-M3-x64.dll或者jacob-1.18-M3-x86.dll 不记得自己jdk啥版本的就都加好了
word转pdf的代码
public class Word2PDF {
static final int wdDoNotSaveChanges = 0;
static final int wdFormatPDF = 17;// PDF 格式
public static void main(String[] args) {
List<File> words = listWordFiles(new File("G:\\chen"));
for (File file : words) {
word2pdf(file);
}
}
public static void word2pdf(File file) {
if (file.exists() && file.canExecute() && file.isFile()) {
String fileName = file.getName();
int lastDotIndex = fileName.lastIndexOf(".");
String toFileName = fileName.substring(0, lastDotIndex) + ".pdf";
String toFilePath = file.getParent() + "/" + toFileName;
System.out.println("启动Word...");
long start = System.currentTimeMillis();
ActiveXComponent app = null;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);
Dispatch docs = app.getProperty("Documents").toDispatch();
System.out.println("打开文档..." + file.getAbsolutePath());
Dispatch doc = Dispatch.call(docs, "Open", file.getAbsolutePath(), false,true ).toDispatch();
System.out.println("转换文档到PDF..." + toFilePath);
File tofile = new File(toFilePath);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc,"SaveAs", toFilePath, wdFormatPDF);
Dispatch.call(doc, "Close", false);
long end = System.currentTimeMillis();
System.out.println("转换完成..用时:" + (end - start) + "ms.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("文档转换失败:" + e.getMessage());
} finally {
if (app != null)
app.invoke("Quit", wdDoNotSaveChanges);
}
}
}
}
public class LineFileWriter {
private final static String TAG = "\t";
private String separator;
private BufferedWriter writer;
public LineFileWriter(File toFile) throws IOException {
this(toFile, TAG);
}
public LineFileWriter(File toFile, String separator) throws IOException {
this.separator = separator;
if (!toFile.getParentFile().exists()) {
toFile.getParentFile().mkdirs();
}
writer = new BufferedWriter(new FileWriter(toFile));
}
public void write(String... terms) throws IOException {
for (String term : terms) {
writer.write(term);
writer.write(separator);
}
writer.newLine();
}
public void close() throws IOException {
writer.flush();
writer.close();
}
}
转成pdf后 有两种预览方式
一种 直接用pdf.js 只了解过 没实际用过 哈哈
一种 用 flexpaper 这个麻烦些 他需要把pdf转成swf格式 才行 可以下个swfTools
辅助代码
public class PDF2SWF {
public final static String replaceBase = "G:\\chen\\";
public final static String CMD_PDF_2_SWF = "E:\\Program Files (x86)\\SWFTools\\pdf2swf.exe";
public static void main(String[] args) throws IOException {
List<File> words = listWordFiles(new File("G:\\chen\\"));
LineFileWriter infoWriter = new LineFileWriter(new File("E:\\chen\\info.log"));
LineFileWriter errWriter = new LineFileWriter(new File("E:\\chen\\err.log"));
for (File word : words) {
pdf2swf(word, infoWriter, errWriter);
}
infoWriter.close();
errWriter.close();
}
public static void pdf2swf(File docFile, LineFileWriter infoWriter, LineFileWriter errWriter) {
try {
long startTime = System.currentTimeMillis();
String docAbsolutePath = docFile.getAbsolutePath();
String fileKey = docAbsolutePath.replace(replaceBase, "");
String pdfAbsolutePath = docAbsolutePath.replace(".docx", ".pdf").replace(".doc", ".pdf");
File pdfFile = new File(pdfAbsolutePath);
String swfBasePath = pdfAbsolutePath.replace(".pdf", "");
PDDocument doc = PDDocument.load(pdfFile);
int pageCount = doc.getNumberOfPages();
doc.close();
boolean result = true;
System.out.println("处理:" + pdfAbsolutePath + ",页数:" + String.valueOf(pageCount) + "");
for (int i = 1; i <= pageCount; i++) {
String command = CMD_PDF_2_SWF + " " + pdfFile.getAbsolutePath() + " -o " + swfBasePath + "_" + i
+ ".swf -f -T 9 -t -s storeallcharacters -s linknameurl -p " + i;
ArrayList commands = commandLineAsList(command);
ProcessBuilder pb = new ProcessBuilder(commands);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
if (line.toLowerCase().startsWith("warning")) {
errWriter.write(pdfAbsolutePath, "WARNING: " + line, String.valueOf(i));
} else if (line.toLowerCase().startsWith("error")) {
errWriter.write(pdfAbsolutePath, "ERROR:" + line, String.valueOf(i));
result = false;
} else if (line.toLowerCase().startsWith("fatal")) {
errWriter.write(pdfAbsolutePath, "FATAL:" + line, String.valueOf(i));
result = false;
} else {
// infoWriter.write(pdfFile.getAbsolutePath(), pageCount + "");
// System.out.println("\t" + line);
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
errWriter.write(pdfAbsolutePath, "FATAL:" + line, String.valueOf(i));
result = false;
}
}
}
if (result) {
infoWriter.write(fileKey, String.valueOf(pageCount));
}
System.out.println("用时:" + (System.currentTimeMillis() - startTime) + "毫秒");
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList commandLineAsList(String commandLine) {
ArrayList commands = new ArrayList();
String elt = "";
boolean insideString = false;
for (int i = 0; i < commandLine.length(); i++) {
char c = commandLine.charAt(i);
if (!insideString && (c == ' ' || c == '\t')) {
if (elt.length() > 0) {
commands.add(elt);
elt = "";
}
continue;
} else
4000
if (c == '"') {
insideString = !insideString;
}
elt += c;
}
if (elt.length() > 0) {
commands.add(elt);
}
return commands;
}
public static List<File> listWordFiles(File file) {
List<File> fs = new ArrayList<>();
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
if (f.isFile() && isWordFile(f)) {
fs.add(f);
} else if (f.isDirectory()) {
fs.addAll(listWordFiles(f));
}
}
}
return fs;
}
public static boolean isWordFile(File file) {
return file != null && file.isFile() && (file.getName().endsWith(".doc") || file.getName().endsWith(".docx"));
}
}
前端使用
先去下载 flexpaper.js 和FlexPaperViewer.swf
<div id="documentViewer" class="flexpaper_viewer" style="width:760px;height:1000px"></div>
js:
function getDocumentUrl(document){
var numPages = ${paper.swfCount};
var id = ${paper.id};
var url = "{"+ id +"/swf?pageNum=[*,0],{numPages}}";
url = url.replace("{numPages}",numPages);
return url;
}
$('#documentViewer').FlexPaperViewer(
{ config : {
SWFFile : escape(getDocumentUrl()),
Scale : 1.0,
ZoomTransition : 'easeOut',
ZoomTime : 0.5,
ZoomInterval : 0.1,
FitPageOnLoad : false,
FitWidthOnLoad : true,
FullScreenAsMaxWindow : false,
ProgressiveLoading : false,
MinZoomSize : 0.1,
MaxZoomSize : 5,
SearchMatchAll : false,
InitViewMode : 'Portrait',
RenderingOrder : 'flash',
StartAtPage : '',
ViewModeToolsVisible : true,
ZoomToolsVisible : true,
NavToolsVisible : true,
CursorToolsVisible : true,
SearchToolsVisible : true,
WMode : 'opaque',
key : 'XXXXXXX',
localeChain: 'zh_CN'
}}
);
大致如此 都是前人的智慧,掏出来做个笔记
相关文章推荐
- 一款免费且安全的在线 PDF 转换软件
- PDF里的文字显示模糊的解决方法
- 微软Word 2007数学插件 Microsoft Math 提供下载
- Office Word九条常用技巧
- PDF编辑工具 Foxit PDF Editor 1.5 Build 2911 下载
- 没有文件大小限制并免费的PDF到HTML转换工具
- MicroAdobe PDF Editor 6.2 英文正式版附破解补丁 下载
- C#实现简单合并word文档的方法
- C#使用iTextSharp设置PDF所有页面背景图功能实例
- powershell操作word详解
- C#生成Word文档代码示例
- C#怎么给PDF添加背景图片
- PDF的VBS小程序代码
- 用vbscript把 Word 文档保存为文本文件的代码
- C#实现PDF文件添加图片背景
- 如何使用C#从word文档中提取图片
- C#根据Word模版生成Word文件
- C#采用OpenXml给Word文档添加表格
- C#实现合并多个word文档的方法
- C#采用OpenXml给word里面插入图片