㈠ java使用jodconverter包實現office轉pdf的時候,報錯文件格式錯誤是為什麼啊
1 有幾種原因可以參考一下:
1)從資料庫讀取出來的內容 與 寫死的文件名是否 物理一致,即是否是其他編碼。
2)注意從資料庫讀取出來的字元串是否在前後有多餘的空格,即驗證其長度
3)查找物理位置上的文件是否真的存在。
4) 是否能夠連接到soffice上,soffice是否啟動了多次。
5) 我曾經遇到的問題是:在應用程序中寫死的和從資料庫讀取的一樣,但在系統磁碟上所保存的就不是這個文件名,而是某種編碼的字元。
正確代碼如下;
* 將Office文檔轉換為PDF. 運行該函數需要用到OpenOffice, OpenOffice下載地址為
* http://www.openoffice.org/
*
* <pre>
* 方法示例:
* String sourcePath = "F:\\office\\source.doc";
* String destFile = "F:\\pdf\\dest.pdf";
* Converter.office2PDF(sourcePath, destFile);
* </pre>
*
* @param sourceFile
* 源文件, 絕對路徑. 可以是Office2003-2007全部格式的文檔, Office2010的沒測試. 包括.doc,
* .docx, .xls, .xlsx, .ppt, .pptx等. 示例: F:\\office\\source.doc
* @param destFile
* 目標文件. 絕對路徑. 示例: F:\\pdf\\dest.pdf
* @return 操作成功與否的提示信息. 如果返回 -1, 表示找不到源文件, 或url.properties配置錯誤; 如果返回 0,
* 則表示操作成功; 返回1, 則表示轉換失敗
*/
public static int office2PDF(String sourceFile, String destFile) {
try {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
return -1;// 找不到源文件, 則返回-1
}
// 如果目標路徑不存在, 則新建該路徑
File outputFile = new File(destFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
String OpenOffice_HOME = "D:\\Program Files\\OpenOffice.org 3";//這里是OpenOffice的安裝目錄, 在我的項目中,為了便於拓展介面,沒有直接寫成這個樣子,但是這樣是絕對沒問題的
// 如果從文件中讀取的URL地址最後一個字元不是 '\',則添加'\'
if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {
OpenOffice_HOME += "\\";
}
// 啟動OpenOffice的服務
String command = OpenOffice_HOME
+ "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
Process pro = Runtime.getRuntime().exec(command);
// connect to an OpenOffice.org instance running on port 8100
OpenOfficeConnection connection = new SocketOpenOfficeConnection(
"127.0.0.1", 8100);
connection.connect();
// convert
DocumentConverter converter = new OpenOfficeDocumentConverter(
connection);
converter.convert(inputFile, outputFile);
// close the connection
connection.disconnect();
// 關閉OpenOffice服務的進程
pro.destroy();
return 0;
} catch (FileNotFoundException e) {
e.printStackTrace();
return -1;
} catch (ConnectException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
㈡ 在linux環境下,java怎麼實現從word格式轉換為pdf格式
WORD轉換到PDF
WORD轉換到PDF的步驟就相對簡單了,我們只需要安裝一款虛擬列印機軟體「Virtual Pdf Printer」即可,它可以將你編輯好的WORD文檔直接輸出為PDF文件格式。(下載地址: http://www.newhua.com/soft/21190.htm)
安裝後在WORD中點擊「打開」→「列印」,在「列印機名稱」中會看到多了一個「Virtual Printer」選項,選中它,點擊確定後(未注冊版本有10秒的等待時間),彈出「保存PDF文件」對話框,先選擇文件的保存路徑,再點擊「生成設置」按鈕,彈出「系統設置」面板(如圖3),對輸出後的PDF文件進行加密和字體等設置,點擊兩次確定,當前的WORD文檔就被轉換成PDF格式的文件了
㈢ 如何用純java代碼實現word轉pdf
1:用apache pio 讀取doc文件,然後轉成html文件用Jsoup格式化html文件,最後用itext將html文件轉成pdf。
2:使用jdoctopdf來實現,這是一個封裝好的包,可以把doc轉換成pdf,html,xml等格式,調用很方便。
3:地址http://www.maxstocker.com/jdoctopdf/downloads.php
需要注意中文字體的寫入問題。
4:使用jodconverter來調用openOffice的服務來轉換,openOffice有個各個平台的版本,所以這種方法跟方法1一樣都是跨平台的。
jodconverter的下載地址:http://www.artofsolving.com/opensource/jodconverter
首先要安裝openOffice,下載地址:office.org/download/index.html" target="_blank">http://www.openoffice.org/download/index.html
5:安裝完後要啟動openOffice的服務,具體啟動方法請自行google。
6:效果最好的一種方法,但是需要window環境,而且速度是最慢的需要安裝msofficeWord以及SaveAsPDFandXPS.exe(word的一個插件,用來把word轉化為pdf)
7:Office版本是2007,因為SaveAsPDFandXPS是微軟為office2007及以上版本開發的插件。
8:SaveAsPDFandXPS下載地址:microsoft.com/zh-cn/download/details.aspx?id=7" target="_blank">http://www.microsoft.com/zh-cn/download/details.aspx?id=7。
9:需要轉換的工具 ,看你是linux還是word 。word還好不需要安裝。linux就麻煩了。
㈣ 如何用純java代碼實現word轉pdf
幾種方案:
方法一:用apache pio 讀取doc文件,然後轉成html文件用Jsoup格式化html文件,最後用itext將html文件轉成pdf。
方法2:使用jdoctopdf來實現,這是一個封裝好的包,可以把doc轉換成pdf,html,xml等格式,調用很方便
地址:
需要注意中文字體的寫入問題。
方法3:使用jodconverter來調用openOffice的服務來轉換,openOffice有個各個平台的版本,所以這種方法跟方法1一樣都是跨平台的。
jodconverter的下載地址:
首先要安裝openOffice,下載地址:
安裝完後要啟動openOffice的服務,具體啟動方法請自行google
方法4:效果最好的一種方法,但是需要window環境,而且速度是最慢的需要安裝msofficeWord以及SaveAsPDFandXPS.exe(word的一個插件,用來把word轉化為pdf)
Office版本是2007,因為SaveAsPDFandXPS是微軟為office2007及以上版本開發的插件
SaveAsPDFandXPS下載地址:
jacob 包下載地址:
㈤ 用Java可以把pdf轉doc嗎
可以,要藉助一些第三方PDF類庫,下面是Spire.PDF for Java轉換PDF到.doc和.docx的代碼給你參考。
import com.spire.pdf.*;
public class PdfToDoc {
public static void main(String[] args) {
//create a PdfDocument object
PdfDocument doc = new PdfDocument();
//load a sample PDF file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Introction of Spire.PDF for Java.pdf");
//save as .doc file
doc.saveToFile("output/ToDoc.doc",FileFormat.DOC);
//save as. docx file
doc.saveToFile("output/ToDocx.docx",FileFormat.DOCX);
doc.close();
}
}
㈥ java 調用OpenOffice 將docx轉換為pdf,出現異常。
OpenOffice java api:
簡單的說就是利用java程序可以操作OpenOffice的所有功能,比如創建doc文檔,插入文字,設置文字格式等等。
1. OpenOffice 給程序員提供了一個叫UNO (UniversalNetwork Objects)的組件技術.我理解的UNO: OpenOffice 類似於web程序中的伺服器,程序員寫的代碼類似於客戶端,利用UNO提供的介面和服務去完成對OpenOffice文檔的操作。所以寫程序首先要搭建 UNO環境:
1. 下載 OpenOffice
2.復制UNO提供的jar包: unoil.jar, java_uno.jar, juh.jar, jurt.jar, ridl.jar, unoloader.jar. (ps: 安裝了SDK之後在文件夾找)到自己的工程中,引入它們。
3. 下載文檔:DevelopersGuide.pdf.
4. 安裝了SDK後,重新啟動一下機器,然後就可以按照 DevelopersGuide 來學習 UNO 編程了。
5. 需要ava 環境。
補充: 安裝了SDK後, java, c++幫助文檔,樣常式序,其他關於sdk的信息 都放在本地openOffice安裝路徑一個叫sdk目錄下面,enjoy it !
總結一下已經實現的功能和碰到的問題匯總:
1. 首先要得到遠程office組件的上下文.通過:
com.sun.star.uno.XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
得到,如果OpenOffice安裝路徑不是在工程的路徑下面(我自己猜的), 就會報:
com.sun.star.comp.helper.BootstrapException: no office executable found!
解決辦法: 黑其源代碼, 看了源代碼就會發現其實OpenOffice是在尋找本地的soffice的shell文件,所以弄個變數來保存soffice在系統中的路徑,重新寫一 個Bootstrap就可以了。詳細請參照:論壇 。
2. 得到 XMultiComponentFactory (ComponentFactory 工廠)
com.sun.star.lang.XMultiComponentFactory xMCF = xContext.getServiceManager();
3. 得到各種組件可以通過下面代碼:
// docType 是 與 soffice 同目錄下面的OpenOffice的其他shell文件,swrite等等
protected XComponent newDocComponent(String docType)
throws java.lang.Exception {
String loadUrl = "private:factory/" + docType;
mxRemoteServiceManager = this.getRemoteServiceManager();
Object desktop = mxRemoteServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", mxRemoteContext);
XComponentLoader xComponentLoader = (XComponentLoader) UnoRuntime
.queryInterface(XComponentLoader.class, desktop);
PropertyValue[] loadProps = new PropertyValue[0];
return xComponentLoader.loadComponentFromURL(loadUrl, "_blank", 0,
loadProps);
}
4.得到 XTextDocument
XComponent xEmptyWriterComponent = newDocComponent("swriter");
XTextDocument mxDoc = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class,
xEmptyWriterComponent);
5. 得到一個文檔的引用
XText mxDocText = mxDoc.getText();
6. 得到文檔的屬性列表
XPropertySet mxDocProps = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, mxDoc);
7. 建立游標,用來插入新的內容。
XTextCursor mxDocCursor = mxDocText.createTextCursor();
XSentenceCursor xSentenceCursor = (XSentenceCursor) UnoRuntime
.queryInterface(XSentenceCursor.class, mxDocCursor);
XWordCursor xWordCursor = (XWordCursor) UnoRuntime.queryInterface(
XWordCursor.class, mxDocCursor);
8.得到游標屬性列表
XPropertySet xCursorProps = (XPropertySet) UnoRuntime .queryInterface(XPropertySet.class, mxDocCursor);
9.設置插入文字格式
xCursorProps.setPropertyValue("CharFontName", "宋體");
xCursorProps.setPropertyValue("CharWeight", new Float(FontWeight.BOLD));
xCursorProps.setPropertyValue("CharHeight", new Float(10.5));
// 居中顯示
xCursorProps.setPropertyValue("ParaAdjust", com.sun.star.style.ParagraphAdjust.CENTER);
10.在該游標處插入信息
mxDocText.insertString(xSentenceCursor, 逗Hello World", true);
11. 保存的關鍵代碼
protected void storeDocComponent(XComponent xDoc, String storeUrl)
throws java.lang.Exception {
XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
XStorable.class, xDoc);
PropertyValue[] storeProps = new PropertyValue[1];
storeProps[0] = new PropertyValue();
storeProps[0].Name = "FilterName";
storeProps[0].Value = "MS Word 97";
openOfficeJavaLogger.debug("... store \"" + xDoc.toString() + "\" to \"" + storeUrl
+ "\".");
xStorable.storeAsURL(storeUrl, storeProps);
}
㈦ java中如何實現向已有的PDF文件插入附件
可以用Spire.Pdf for Java類庫給PDF文檔添加附件,下面的代碼是插入Excel和Word附件給你參考:
import com.spire.pdf.annotations.*;
import com.spire.pdf.attachments.PdfAttachment;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class AttachFiles {
public static void main(String[] args) throws IOException {
//創建PdfDocument對象
PdfDocument doc = new PdfDocument();
//載入PDF文檔
doc.loadFromFile("C:\Users\Administrator\Desktop\sample.pdf");
//添加附件到PDF
PdfAttachment attachment = new PdfAttachment("C:\Users\Administrator\Desktop\使用說明書.docx");
doc.getAttachments().add(attachment);
//繪制標簽
String label = "財務報表.xlsx";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,12),true);
double x = 35;
double y = doc.getPages().get(0).getActualSize().getHeight() - 200;
doc.getPages().get(0).getCanvas().drawString(label, font, PdfBrushes.getOrange(), x, y);
//添加註釋附件到PDF
String filePath = "C:\Users\Administrator\Desktop\財務報表.xlsx";
byte[] data = toByteArray(filePath);
Dimension2D size = font.measureString(label);
Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 2), (float) y, 10, 15);
PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);
annotation.setColor(new PdfRGBColor(new Color(0, 128, 128)));
annotation.setFlags(PdfAnnotationFlags.Default);
annotation.setIcon(PdfAttachmentIcon.Graph);
annotation.setText("點擊打開財務報表.xlsx");
doc.getPages().get(0).getAnnotationsWidget().add(annotation);
//保存文檔
doc.saveToFile("Attachments.pdf");
}
//讀取文件到byte數組
public static byte[] toByteArray(String filePath) throws IOException {
File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
System.out.println("file too big...");
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
if (offset != buffer.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
fi.close();
return buffer;
}
}
效果:
㈧ 在linux環境下,java怎麼實現從word格式轉換為pdf格式
linux環境下,word格式轉換為pdf格式
word轉換到PDF的步驟就相對簡單了,我們只需要安裝一款虛擬列印機軟體「Virtual Pdf Printer」即可,它可以將你編輯好的word文檔直接輸出為PDF文件格式。
安裝後在word中點擊「打開」→「列印」,
在「列印機名稱」中會看到多了一個「Virtual Printer」選項,
選中它,點擊確定後(未注冊版本有10秒的等待時間),
彈出「保存PDF文件」對話框,先選擇文件的保存路徑,
再點擊「生成設置」按鈕,彈出「系統設置」面板,
對輸出後的PDF文件進行加密和字體等設置,
點擊兩次確定,當前的word文檔就被轉換成PDF格式的文件了.
㈨ java讀取doc,pdf問題。
PDFBox是一個開源的對pdf文件進行操作的庫。 PDFBox-0.7.3.jar加入classpath。同時FontBox1.0.jar加入classpath,否則報錯
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importorg.pdfbox.pdfparser.PDFParser;
importorg.pdfbox.pdmodel.PDDocument;
importorg.pdfbox.util.PDFTextStripper;
publicclassPdfReader{
/**
*.
*.
*2008-2-25
*@parampdfFilePathfilepath
*@returnalltextinthepdffile
*/
(StringpdfFilePath)
{
Stringresult=null;
FileInputStreamis=null;
PDDocumentdocument=null;
try{
is=newFileInputStream(pdfFilePath);
PDFParserparser=newPDFParser(is);
parser.parse();
document=parser.getPDDocument();
PDFTextStripperstripper=newPDFTextStripper();
result=stripper.getText(document);
}catch(FileNotFoundExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}finally{
if(is!=null){
try{
is.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
if(document!=null){
try{
document.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
returnresult;
}
publicstaticvoidmain(String[]args)
{
Stringstr=PdfReader.getTextFromPDF("C:\Read.pdf");
System.out.println(str);
}
}
代碼2:
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.OutputStreamWriter;
importjava.io.Writer;
importjava.net.MalformedURLException;
importjava.net.URL;
importorg.pdfbox.pdmodel.PDDocument;
importorg.pdfbox.util.PDFTextStripper;
publicclassPDFReader{
publicvoidreadFdf(Stringfile)throwsException{
booleansort=false;
StringpdfFile=file;
StringtextFile=null;
Stringencoding="UTF-8";
intstartPage=1;
intendPage=Integer.MAX_VALUE;
Writeroutput=null;
PDDocumentdocument=null;
try{
try{
//首先當作一個URL來裝載文件,如果得到異常再從本地文件系統//去裝載文件
URLurl=newURL(pdfFile);
//注意參數已不是以前版本中的URL.而是File。
document=PDDocument.load(pdfFile);
//獲取PDF的文件名
StringfileName=url.getFile();
//以原來PDF的名稱來命名新產生的txt文件
if(fileName.length()>4){
FileoutputFile=newFile(fileName.substring(0,fileName
.length()-4)
+".txt");
textFile=outputFile.getName();
}
}catch(MalformedURLExceptione){
//如果作為URL裝載得到異常則從文件系統裝載
//注意參數已不是以前版本中的URL.而是File。
document=PDDocument.load(pdfFile);
if(pdfFile.length()>4){
textFile=pdfFile.substring(0,pdfFile.length()-4)
+".txt";
}
}
output=newOutputStreamWriter(newFileOutputStream(textFile),
encoding);
PDFTextStripperstripper=null;
stripper=newPDFTextStripper();
//設置是否排序
stripper.setSortByPosition(sort);
//設置起始頁
stripper.setStartPage(startPage);
//設置結束頁
stripper.setEndPage(endPage);
//調用PDFTextStripper的writeText提取並輸出文本
stripper.writeText(document,output);
}finally{
if(output!=null){
//關閉輸出流
output.close();
}
if(document!=null){
//關閉PDFDocument
document.close();
}
}
}
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
PDFReaderpdfReader=newPDFReader();
try{
//取得E盤下的SpringGuide.pdf的內容
pdfReader.readFdf("C:\Read.pdf");
}catch(Exceptione){
e.printStackTrace();
}
}
}
2、抽取支持中文的pdf文件-xpdf
xpdf是一個開源項目,我們可以調用他的本地方法來實現抽取中文pdf文件。
http://www.java-cn.com/technology/tech_downs/1880_004.zip
補丁包:
http://www.java-cn.com/technology/tech_downs/1880_005.zip
按照readme放好中文的patch,就可以開始寫調用本地方法的java程序了。
下面是一個如何調用的例子:
importjava.io.*;
/**
*<p>Title:pdfextraction</p>
*<p>Description:email:[email protected]</p>
*<p>Copyright:MatrixCopyright(c)2003</p>
*<p>Company:Matrix.org.cn</p>
*@authorchris
*@version1.0,
*/
publicclassPdfWin{
publicPdfWin(){
}
publicstaticvoidmain(Stringargs[])throwsException
{
StringPATH_TO_XPDF="C:ProgramFilesxpdfpdftotext.exe";
Stringfilename="c:a.pdf";
String[]cmd=newString[]{PATH_TO_XPDF,"-enc","UTF-8","-q",filename,"-"};
Processp=Runtime.getRuntime().exec(cmd);
BufferedInputStreambis=newBufferedInputStream(p.getInputStream());
InputStreamReaderreader=newInputStreamReader(bis,"UTF-8");
StringWriterout=newStringWriter();
char[]buf=newchar[10000];
intlen;
while((len=reader.read(buf))>=0){
//out.write(buf,0,len);
System.out.println("thelengthis"+len);
}
reader.close();
Stringts=newString(buf);
System.out.println("thestris"+ts);
}
}