word轉(zhuǎn)pdf的時(shí)候,需要引入jacob包!
jacob包已上傳到碼云
https://gitee.com/kong_qing_rong/daily-component-library/tree/master/jacob%E5%8C%85
public class test {
static final int wdFormatPDF = 17;// PDF 格式
private static int interval = -5;
/**
* word轉(zhuǎn)pdf
* @param fromAddress 待轉(zhuǎn)文件地址
* @param toAddress 新文件地址
*/
public static void wordToPdf(String fromAddress,String toAddress){
ActiveXComponent ax = null;
try {
long startTime = System.currentTimeMillis();
/*
* 創(chuàng)建不同的控件調(diào)用不同的值
* Word——Word.Application
* Excel——Excel.Application
* Powerpoint——Powerpoint.Application
* Outlook——Outlook.Application
* */
ax = new ActiveXComponent("Word.Application");
/*設(shè)置打開(kāi)word文檔不可見(jiàn)*/
ax.setProperty("Visible", false);
//獲取Word文檔中所有內(nèi)容
Dispatch docs = ax.getProperty("Documents").toDispatch();
//打開(kāi)word文檔则吟,并設(shè)置word為不可編輯和不需確認(rèn)
Dispatch doc = Dispatch.call(docs,
"Open",
fromAddress,// FileName
false,// ConfirmConversions
true // ReadOnly
).toDispatch();
File tofile = new File(toAddress);
if (tofile.exists()) {
tofile.delete();
}
//word文件另存為pdf文件
Dispatch.call(doc,//
"SaveAs", //
toAddress, // FileName
wdFormatPDF);
//關(guān)閉word文檔
Dispatch.call(doc, "Close", false);
long endTime = System.currentTimeMillis();
System.out.println("轉(zhuǎn)化完成,總共耗時(shí)" + (endTime - startTime) + "ms。");
} catch (Exception e) {
System.out.println("========Error:文檔轉(zhuǎn)換失敗:" + e.getMessage());
} finally {
if (ax != null)
ax.invoke("Quit", new Variant[]{});
}
}
public static void waterMark(String inputFile,
String outputFile, String waterMarkName, String password) {
try {
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
outputFile));
byte[] ownerPassword = password.getBytes();
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_ASSEMBLY, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_COPY, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_DEGRADED_PRINTING, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_FILL_IN, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_ANNOTATIONS, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_MODIFY_CONTENTS, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_PRINTING, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.ALLOW_SCREENREADERS, false);
stamper.setEncryption(null, ownerPassword, PdfWriter.DO_NOT_ENCRYPT_METADATA, true);
stamper.setViewerPreferences(PdfWriter.HideToolbar|PdfWriter.HideMenubar);
BaseFont base = BaseFont.createFont("c://windows//fonts//simsun.ttc,1" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED);// 使用系統(tǒng)字體
Rectangle pageRect = null;
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.3f);
gs.setStrokeOpacity(0.4f);
int total = reader.getNumberOfPages() + 1;
JLabel label = new JLabel();
FontMetrics metrics;
int textH = 0;
int textW = 0;
label.setText(waterMarkName);
metrics = label.getFontMetrics(label.getFont());
textH = metrics.getHeight();//字符串的高, 只和字體有關(guān)
textW = metrics.stringWidth(label.getText());//字符串的寬
PdfContentByte under;
for (int i = 1; i < total; i++) {
pageRect = reader.getPageSizeWithRotation(i);
// 計(jì)算水印X,Y坐標(biāo)
float x = pageRect.getWidth() / 2;
float y = pageRect.getHeight() / 2;
under = stamper.getOverContent(i);
under.saveState();
under.setGState(gs);
under.beginText();
under.setFontAndSize(base, 15);
// 水印文字成45度角傾斜
for (int height = interval + textH; height < pageRect.getHeight();
height = height + textH*8) {
for (int width = interval + textW; width < pageRect.getWidth() + textW;
width = width + textW) {
under.showTextAligned(Element.ALIGN_LEFT
, waterMarkName, width - textW,
height - textH, 45);
}
}
// 添加水印文字
under.endText();
}
stamper.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void concatPDFs(List<InputStream> streamOfPDFFiles,
OutputStream outputStream, boolean paginate) {
Document document = new Document();
try {
List<InputStream> pdfs = streamOfPDFFiles;
List<PdfReader> readers = new ArrayList<PdfReader>();
int totalPages = 0;
Iterator<InputStream> iteratorPDFs = pdfs.iterator();
// Create Readers for the pdfs.
while (iteratorPDFs.hasNext()) {
InputStream pdf = iteratorPDFs.next();
PdfReader pdfReader = new PdfReader(pdf);
readers.add(pdfReader);
totalPages += pdfReader.getNumberOfPages();
}
// Create a writer for the outputstream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
// data
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
document.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = writer.getImportedPage(pdfReader,
pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
// Code for pagination.
if (paginate) {
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520,
5, 0);
cb.endText();
}
}
pageOfCurrentReaderPDF = 0;
}
outputStream.flush();
document.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen())
document.close();
try {
if (outputStream != null)
outputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
String to = "C:/Desktop/to.pdf";
String wordUrl = "C:/Desktop/1501139857165.doc";
File file = File.createTempFile("tempFile", ".pdf");
wordToPdf(wordUrl,file.getPath());
waterMark(file.getPath(), to, "圣賢庸才痹籍,大人小心!;扌6撞!S贫狻O叨ā!","000000");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}