㈠ 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);
}
}