1. 程式人生 > >呼叫WPS服務COM元件轉換PDF

呼叫WPS服務COM元件轉換PDF

package org.pdf.tyl.convert;


import java.awt.Color;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;


import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
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;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;


/**
 * ClassName: PdfConvertUtil pdf裝換工具類
 * 
 * @Description:
 * @author JornTang
 * @email
[email protected]

 * @date 2017年9月14日
 */
public class PdfUtil {
// 文件格式轉換元件
public static final String WORDSERVER_STRING = "KWPS.Application";
// 幻燈片格式轉換元件
public static final String PPTSERVER_STRING = "KWPP.Application";
// 表格格式轉換元件
public static final String EXECLSERVER_STRING = "KET.Application";
private static final int wdFormatPDF = 17;
private static final int xlTypePDF = 0;
private static final int ppSaveAsPDF = 32;


public PdfUtil() {
}


/**
* @Description: 文件格式轉換 支援 wps、wpt、doc、docx、dot、txt等所有文件格式檔案
* @param srcFilePath
*            文件路徑
* @param pdfFilePath
*            pdf路徑
* @return void
* @throws Exception
* @throws
* @author JornTang
* @email
[email protected]

* @date 2017年9月14日
*/
public static boolean wpsTopdf(String srcFilePath, String pdfFilePath)
throws Exception {
// wps com
ActiveXComponent pptActiveXComponent = null;
ActiveXComponent workbook = null;
// open thred
ComThread.InitSTA();
try {
pptActiveXComponent = new ActiveXComponent(PPTSERVER_STRING);
Variant openParams[] = { new Variant(srcFilePath),
new Variant(true), new Variant(true) };
workbook = pptActiveXComponent.invokeGetComponent("Documents")
.invokeGetComponent("Open", openParams);
workbook.invoke("SaveAs", new Variant[] { new Variant(pdfFilePath),
new Variant(wdFormatPDF) });
} catch (Exception e) {
throw e;
} finally {
if (workbook != null) {
workbook.invoke("Close");
workbook.safeRelease();
}
if (pptActiveXComponent != null) {
pptActiveXComponent.invoke("Quit");
pptActiveXComponent.safeRelease();
}
// close thred
ComThread.Release();
}
return true;
}


/**
* @Description: 幻燈片格式轉換 支援ppt、pps、pptx、ppsx、dps、dpt、pot、uof
* @param srcFilePath
*            幻燈片路徑
* @param pdfFilePath
*            pdf路徑
* @return
* @return boolean
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static boolean pptTopdf(String srcFilePath, String pdfFilePath) {
ActiveXComponent pptActiveXComponent = null;
ActiveXComponent workbook = null;
boolean readonly = true;
ComThread.InitSTA();
try {
pptActiveXComponent = new ActiveXComponent(PPTSERVER_STRING);
workbook = pptActiveXComponent.invokeGetComponent("Presentations")
.invokeGetComponent(
"Open",
new Variant[] { new Variant(srcFilePath),
new Variant(readonly) });
workbook.invoke("SaveAs", new Variant[] { new Variant(pdfFilePath),
new Variant(ppSaveAsPDF) });
return true;
} catch (Exception e) {
throw e;
} finally {
if (workbook != null) {
workbook.invoke("Close");
workbook.safeRelease();
}
if (pptActiveXComponent != null) {
pptActiveXComponent.invoke("Quit");
pptActiveXComponent.safeRelease();
}
ComThread.Release();
}
}


/**
* @Description: 表格格式轉換 支援et、ett、xls、xlsx、xlt、uof、prn、csv
* @param srcFilePath
*            幻燈片路徑
* @param pdfFilePath
*            pdf路徑
* @return
* @return boolean
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static boolean xlsTopdf(String srcFilePath, String pdfFilePath) {
ActiveXComponent et = null;
Dispatch workbook = null;
workbook = null;
ComThread.InitSTA();
try {
et = new ActiveXComponent(EXECLSERVER_STRING);
et.setProperty("Visible", new Variant(false));
Dispatch workbooks = et.getProperty("Workbooks").toDispatch();
workbook = Dispatch.invoke(
workbooks,
"Open",
1,
new Object[] { srcFilePath, Integer.valueOf(xlTypePDF),
Boolean.valueOf(true) }, new int[1]).toDispatch();
Dispatch.call(workbook, "ExportAsFixedFormat", new Object[] {
Integer.valueOf(xlTypePDF), pdfFilePath });
return true;
} catch (Exception e) {
throw e;
} finally {
if (workbook != null) {
Dispatch.call(workbook, "Close");
workbook.safeRelease();
}
if (et != null) {
et.invoke("Quit");
et.safeRelease();
}
ComThread.Release();
}
}


/**
* @Description: 圖片轉pdf
* @param imagePath
* @param pdfFilePath
* @return
* @return boolean
* @throws DocumentException
* @throws IOException
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static boolean iamgeTopdf(String imagePath, String pdfFilePath)
throws DocumentException, IOException {
File pdfFile = new File(pdfFilePath);
if (pdfFile.exists()) {
throw new FileNotFoundException("pdfFilePath already exists");
}
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
try {
PdfWriter.getInstance(doc, new FileOutputStream(
pdfFilePath));
doc.open();


doc.newPage();
Image png1 = Image.getInstance(imagePath);
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = getPercent(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();
return true;
} catch (FileNotFoundException e) {
throw e;
} catch (DocumentException e) {
throw e;
} catch (IOException e) {
throw e;
}
}
/**
* @Description: 新增文字
* @param writer
* @param content
* @param color
* @param x
* @param y
* @param z   
* @return void  
* @throws
* @author JornTang
* @date 2017年9月14日
*/
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);
}
/**
* @Description: 在不改變圖片形狀的同時,判斷,如果h>w,則按h壓縮,否則在w>h或w=h的情況下,按寬度壓縮
* @param h
* @param w
* @return   
* @return int  
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static 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;
}
/**
* @Description: 統一按照寬度壓縮 這樣來的效果是,所有圖片的寬度是相等的,自我認為給客戶的效果是最好的 
* @param h
* @param w
* @return   
* @return int  
* @throws
* @author JornTang
* @date 2017年9月14日
*/
private static int getPercent(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}


/**
* @Description: pdf轉圖片
* @param pdfFilePath
* @param imageFilePath
* @throws IOException
* @return void
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static void pdfTojpg(String pdfFilePath, String imageFilePath)
throws Exception {
ByteBuffer buf = null;
RandomAccessFile raf = null;
FileChannel channel = null;
try {
// load a pdf from a byte buffer
File file = new File(pdfFilePath);
raf = new RandomAccessFile(file, "r");
channel = raf.getChannel();
// 這句程式碼通道建立了map對映,如果要刪除file那麼得接觸對映
buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
int totalpage = pdffile.getNumPages();
for (int i = 1; i <= totalpage; i++) {
if (i == 1) {
// draw the first page to an image
// 以圖片的形式來描繪首頁
PDFPage page = pdffile.getPage(i);
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());
// generate the image
// 生成圖片
java.awt.Image img = page.getImage(rect.width, rect.height, // width
// &
// height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
BufferedImage tag = new BufferedImage(rect.width,
rect.height, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(
img.getScaledInstance(rect.width, rect.height,
java.awt.Image.SCALE_SMOOTH), 0, 0, rect.width,
rect.height, null);


FileOutputStream out = new FileOutputStream(imageFilePath); // 輸出到檔案流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // JPEG編碼
// 關閉輸出流
out.close();
break;
}
}
} catch (Exception e) {
throw e;
} finally {
buf.clear();
channel.close();
raf.close();
unmap(buf);
}
}


/**
* @Description: 解除map對映
* @param buffer
* @return void
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static <T> void unmap(final Object buffer) {
AccessController.doPrivileged(new PrivilegedAction<T>() {
@Override
public T run() {
try {
Method getCleanerMethod = buffer.getClass().getMethod(
"cleaner", new Class[0]);
getCleanerMethod.setAccessible(true);
sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod
.invoke(buffer, new Object[0]);
cleaner.clean();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
}


public static void main(String[] args) {
try {
xlsTopdf("E:\\FileTest\\testxls.xlsx",
"E:\\FileTest\\11111111xls.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
}

相關推薦

呼叫WPS服務COM元件轉換PDF

package org.pdf.tyl.convert; import java.awt.Color; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.Fil

asp呼叫DLL或com元件的簡述及網上摘例

動態聯接庫(DLL)是加快應用程式關鍵部分的執行速度的重要方法 asp呼叫DLL或com元件的方法: 步驟一: <!--METADATA TYPE="typelib" FILE="Path/XX.dll" --> ''裝載 METADATA 標籤中指定的型別庫。

java 呼叫windows的COM元件舉例(使用JACOB)

最近公司需要做一個效果,開發一個程式能在程式執行時開啟microsoft office的相關軟體,實時寫入,然後能關閉,你能看到資料寫入的效果。如下圖: 下面是一個java呼叫的小例子,效果是彈出一個訊息視窗。 需要引入的包如下: 主程式

通過COM元件方式實現java呼叫C#寫的DLL檔案 轉

    最近一段時間單位在做一個Web專案,工程師用JAVA語言,需要公用人員資訊,統一使用者名稱和密碼,原有的平臺中是用C#語言開發的,在網上查詢解決方法,通過JAVA呼叫C#的DLL檔案實現。網上資料很多,自己整合總結了一下,做個備忘。 一、C#寫com元件 開發環境

多執行緒呼叫系統COM元件的體會(CoInitialize)

多執行緒呼叫COM元件的體會(CoInitialize) 呼叫任何COM元件之前,你必須首先初始化COM套件環境,即呼叫CoInitialize或CoInitializeEx。COM套件環境線上程的生存週期內有效,執行緒退出前需要呼叫CoUninitializ

JAVA 使用 com.aspose.words將word轉換PDF

因為公司前端需要線上檢視word和PDF,後臺上傳需求將word等檔案轉換為PDF,原本使用的是liboffice進行轉換,後來部署到伺服器端之後,發現並不是很適合,由此找到com.aspose.words。直接貼程式碼,大部分程式碼複製百度。 public class

vs2017生成COM元件,VB呼叫

新建專案 -- ATL專案  (專案屬性--連結器--常規--逐使用者重定向 --選為是)  確定,跳出ATL選項,直接再點確定 addcom專案新增專案 新增類test(atl簡單物件) 此時test.h中的標頭檔案addcom_i.h尚未生成,只是一個

NPOI寫Excel,Spire.XLS for.NET元件轉換Excel為PDF

首先要引用NPOI動態庫和Microsoft.Office.Interop.excel.dll (Microsoft.Office.Interop.excel.dll  最好使用使用NuGet下載 ,或者使用網上下載,網上下載以後解壓檔案,把Microsoft.Offic

COM元件呼叫返回了錯誤 HRESULT E_FAIL

背景: 用C#的Aspose.word控制元件,向word的書籤中插入圖片時,需要設定圖片文字環繞:嵌於文字下方。 要實現這一功能時加入如下程式碼時報出的錯誤: 就是這個ConvertToShape()出了錯。 解決方法: 經過多次嘗試,找各種別的控制元件

COM元件可被跨語言呼叫

錯誤修正 首先修正一下上篇(《》)中的例子的一個小問題。類廠的CreateInstance裡面,上次是這麼寫的: STDMETHODIMPClassFactory::CreateInstance(_In_opt_IUnknown *pUnkOuter, _In_REFIIDriid, _

COM 元件呼叫返回了錯誤 HRESULT E_FAIL。

原文地址為: 對 COM 元件的呼叫返回了錯誤 HRESULT E_FAIL。      win7系統,用c#呼叫Interop.SHDocVw.dll時,報了個對“ COM 元件的呼叫返回了錯誤 HRESULT E_FAIL”的錯誤。網上有人說要

geoprocessor(GP)工具提示“對 COM 元件呼叫返回了錯誤 HRESULT E_FAIL”的幾種情況

以gp工具中的merge工具進行示例分析:1、當引數input所表示的要素型別不一致的時候會出現“對 COM 元件的呼叫返回了錯誤 HRESULT E_FAIL”提示。2、當引數output所表示的要素已存在,且gp工具的overwrite屬性設定為false的時候也會出現

C#生成com元件形式的dll供C++呼叫

①建立C#類庫(ClassLibrary)、設定AssemblyInfo.cs中的[assembly: ComVisible(true)]預設是false、或者在介面和類之前新增設定為true     [ComVisible(true)]     [Guid("E709D3

關於C#操作PPT時遇到的“對COM元件呼叫返回了錯誤HRESULT E_FAIL”錯誤的解決方法

最近在做一套和圖書有關的專案,其中有一個功能為使用者上傳的各類文件(doc、docx、ppt、pptx、pdf等型別)統一轉換為PDF型別。word格式的轉為PDF就不用說了,推薦一個第三方DLL:Aspose.Words.dll. Aspose這套DLL專門用來對付Offi

AE+C#把資料寫入GDB資料庫裡出現 “對COM元件呼叫返回了錯誤 HRESULTE_FAIL”

public void CreateFeatureClass_Terrain_Info(IFeatureWorkspace IFW) { IFeatureClass tempFeatureClass = IFW.OpenFeatureClass(

.NET程式連線OPC Server時出錯 對 COM 元件呼叫返回了錯誤 HRESULT E_FAIL

最近在給鹿華系統做升級,為了實時性和穩定性,程式直接從DCS取數,程式是.NET開發的,呼叫OPC的DLL是OPCDAAuto.dll 系統裝的是Windows Server 2003 R2,配置好DCOM,初次嘗試成功連線OPCServer,程式10秒取數一次,在執行30

AxShockwaveFlash控制元件CallFunction時報錯: 對 COM 元件呼叫返回了錯誤 HRESULT E_FAIL。

我在寫完第一種情況後,後來又再次遇到了這個問題,而這次把我搞了大半天。最後卻是一個坑爹的結果。詳見第二種情況第一種情況: 1.現在有兩個Form窗體:FrmGameRoom(遊戲室),FrmGameHall(遊戲大廳)   PS: 遊戲的偵聽資料寫在FrmGameHall

wps外掛開發中com元件許可權

需要對wps寫一個小的外掛,也就是幾行程式碼的事情,但卻碰到了一個坑 wps中的com元件的呼叫和MSoffice非常的相似,幾乎只需要把包的頭修改一下就可以用了。 比如開發wps文件的外掛,需要引用 1. Kingsoft Add-In Designer 2. Ki

C++呼叫C# com元件:一個完整的的小例子

  我們知道C#開發效率是非常高的,特別是做一些漂亮的頁面就更適合用它了啊.如果你開發一個桌面應用程式即想效能好點又想頁面漂亮點可以考慮用C++和C#一起用.反正現在Win7都整合NetFramework了,就不用糾結為了裝個C#的應用程式而去再整個NetFramewor

c++中呼叫Com元件的方法詳解

轉載自:http://www.cppblog.com/woaidongmao/archive/2011/01/10/138250.html需求: 1.建立myCom.dll,該COM只有一個元件,兩個介面:    IGetRes--方法Hello(),    IGetResEx--方法HelloEx() 2