logo头像

技术是一种信念

使用OFFICE把office文档转换为pdf文档

一、所需要的资源

二、使用前准备

  • 把dll文件放在%JAVA_HOME%\bin下(注意系统是32位还是64位),也可以放在C:\Windows\System32下,如果是64位应该放在C:\Windows\SysWOW64 下。建议放在项目使用的jdk的bin目录下
  • 如果是在eclipse下开发,需要重新引入jdk(Preference/Java/Installed JREs)
  • 开发时将jacab.jar包放在项目lib下并add到liabraries中即可。
  • 当前电脑获取服务器必须安装office软件,否则无法进行文档转换操作。

三、编写office转换的工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;

/**
* 这是一个工具类,主要是为了使Office2003-2007全部格式的文档(.doc|.docx|.xls|.xlsx|.ppt|.pptx)
* 转化为pdf文件<br>
* @date 2017-02-21
*
*/
public class Office2PDFUtil {


/*********************************************** 调用服务器office安装来转换 *******************************************************/

private static final int wdFormatPDF = 17;
private static final int xlTypePDF = 0;
private static final int ppSaveAsPDF = 32;
private static final int msoTrue = -1;
private static final int msofalse = 0;
//直接调用这个方法即可
public static boolean convert2PDF(String inputFile, String pdfFile) {
String suffix = getFileSufix(inputFile);
File file = new File(inputFile);
if(!file.exists()){
System.out.println("文件不存在!");
return false;
}
if(suffix.equals("pdf")){
System.out.println("PDF not need to convert!");
return false;
}
if(suffix.equals("doc")||suffix.equals("docx")||suffix.equals("txt")){
return word2PDF(inputFile,pdfFile);
}else if(suffix.equals("ppt")||suffix.equals("pptx")){
return ppt2PDF(inputFile,pdfFile);
}else if(suffix.equals("xls")||suffix.equals("xlsx")){
return excel2PDF(inputFile,pdfFile);
}else if(suffix.equals("png") || suffix.equals("jpg") || suffix.equals("jpeg") || suffix.equals("gif")){
return img2PDF(inputFile,pdfFile);
}else{
System.out.println("文件格式不支持转换!");
return false;
}
}
public static String getFileSufix(String fileName){
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(splitIndex + 1);
}
public static boolean word2PDF(String inputFile,String pdfFile){
try{
//打开word应用程序
ActiveXComponent app = new ActiveXComponent("Word.Application");
//设置word不可见
app.setProperty("Visible", false);
//获得word中所有打开的文档,返回Documents对象
Dispatch docs = app.getProperty("Documents").toDispatch();
//调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
Dispatch doc = Dispatch.call(docs,
"Open",
inputFile,
false,
true
).toDispatch();
//调用Document对象的SaveAs方法,将文档保存为pdf格式
/*
Dispatch.call(doc,
"SaveAs",
pdfFile,
wdFormatPDF //word保存为pdf格式宏,值为17
);
*/
Dispatch.call(doc,
"ExportAsFixedFormat",
pdfFile,
wdFormatPDF //word保存为pdf格式宏,值为17
);
//关闭文档
Dispatch.call(doc, "Close",false);
//关闭word应用程序
app.invoke("Quit", 0);
return true;
}catch(Exception e){
return false;
}
}
/**
*excel转换的时候如果有多个工作簿或者数据量太大的时候转换还是存在问题的
*
*/
public static boolean excel2PDF(String inputFile,String pdfFile){
try{
ActiveXComponent app = new ActiveXComponent("Excel.Application");
app.setProperty("Visible", false);
Dispatch excels = app.getProperty("Workbooks").toDispatch();
Dispatch excel = Dispatch.call(excels,
"Open",
inputFile,
false,
true
).toDispatch();
Dispatch.call(excel,
"ExportAsFixedFormat",
xlTypePDF,
pdfFile
);
Dispatch.call(excel, "Close",false);
app.invoke("Quit");
return true;
}catch(Exception e){
return false;
}

}
public static boolean ppt2PDF(String inputFile,String pdfFile){
try{
ActiveXComponent app = new ActiveXComponent("PowerPoint.Application");
//app.setProperty("Visible", msofalse);
Dispatch ppts = app.getProperty("Presentations").toDispatch();

Dispatch ppt = Dispatch.call(ppts,
"Open",
inputFile,
true,//ReadOnly
true,//Untitled指定文件是否有标题
false//WithWindow指定文件是否可见
).toDispatch();

Dispatch.call(ppt,
"SaveAs",
pdfFile,
ppSaveAsPDF
);

Dispatch.call(ppt, "Close");

app.invoke("Quit");
return true;
}catch(Exception e){
return false;
}
}


/******************************************* 图片转pdf *****************************************/
private static void handleText(PdfWriter writer, String content, String color,
float x, float y, float z) {
PdfContentByte canvas = writer.getDirectContent();
Phrase phrase = new Phrase(content);
if (color != null) {
phrase = new Phrase(content, FontFactory.getFont(
FontFactory.COURIER, 12, Font.NORMAL, new Color(255, 0, 0)));
}

ColumnText.showTextAligned(canvas, Element.ALIGN_UNDEFINED, phrase, x,
y, z);
}

public static Boolean img2PDF(String imagePath, String mOutputPdfFileName) {
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
try {
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(
mOutputPdfFileName));
doc.open();

doc.newPage();
Image png1 = Image.getInstance(imagePath);
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = getPercent2(heigth, width);
png1.setAlignment(Image.MIDDLE);
png1.setAlignment(Image.TEXTWRAP);
png1.scalePercent(percent + 3);
doc.add(png1);
handleText(writer, "This is a test", "red", 400, 725, 0);
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

File mOutputPdfFile = new File(mOutputPdfFileName);
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return false;
}
return true;
}

public int getPercent1(float h, float w) {
int p = 0;
float p2 = 0.0f;
if (h > w) {
p2 = 297 / h * 100;
} else {
p2 = 210 / w * 100;
}
p = Math.round(p2);
return p;
}

private static int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}

/**
* 测试方法
*/
public static void main(String[] args) {
Office2PDFUtil office2pdf = new Office2PDFUtil();
office2pdf.convert2PDF("C:/Users/cheryl/Desktop/视屏/g.txt", "C:/Users/cheryl/Desktop/视屏/g_" + new Date().getTime() + ".pdf" );
}

}

四、在普通的action中的使用

1
2
//注意srcfilePath,与destFilePath 都是文件在硬盘中的绝对位置
convertResult = Office2PDFUtil.convert2PDF(srcfilePath, destFilePath);

五、使用到的相关知识

  1. 使用jacob处理office文档
  2. 使用iText处理 转换之后的pdf文件