word文件 pdf線上預覽方案
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 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'
}}
);
大致如此 都是前人的智慧,掏出來做個筆記