java word转pdf,可以解决转pdf后word横版变窄问题(pdf显示不全)

友情提醒,这个是目前不支持Linux,只支持wind.

最近公司业务需要在pdf中显示表格,但是表格内容列数有点长,导致 word 转pdf的时候 显示不全;

如上图这种显示不全的情况(截图中没有放表格,表格同理一样)。

 具体做法:第一、word的模板文件中需要 进行设置 word 横向布局;打开word => 选择【页面布局】=> 选择右下角的那个 箭头符号; 在页面设置 中,设置 纸张方向为横向,应用到本节,本节就是当前页面;全部就是所有页面了;设置完成后就行了;

第二、代码这一块,建立Word2PdfUtil .java类;这里要引用jacob相关的jar包: jacob.jar、aspectjweaver.jar; 其他的 poi、dom4j;

注意:这里需要引用jacob-1.17-x64.dll这个东西;把jacob.dll(不同版本的jacob的dll文件名有所不同)复制到jdk环境中,例如:【C:\Program Files\Java\jdk1.6.0_17\jre\bin】目录下即可。

相关jar 和 这个java我放到 我的资源页面上了;

https://download.csdn.net/download/qq_30515213/11022381


import java.io.File;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
 
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant; 
public class Word2PdfUtil {  
    static final int wdFormatPDF = 17;// PDF 格式    
    public int wordToPDF(String sfileName,String toFileName) throws Exception{    
            
        System.out.println("启动Word...");      
        long start = System.currentTimeMillis();      
        ActiveXComponent app = null;  
        Dispatch doc = null;  
        try {      
            app = new ActiveXComponent("Word.Application"); 
            // 设置word不可见
            app.setProperty("Visible", new Variant(false));  
            // 打开word文件
            Dispatch docs = app.getProperty("Documents").toDispatch();   
//          doc = Dispatch.call(docs,  "Open" , sourceFile).toDispatch();   
            doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] {                    
               sfileName, new Variant(false),new Variant(true) }, new int[1]).toDispatch();
            System.out.println("打开文档..." + sfileName);  
            System.out.println("转换文档到PDF..." + toFileName);      
            File tofile = new File(toFileName);    
           // System.err.println(getDocPageSize(new File(sfileName)));
            if (tofile.exists()) {      
                tofile.delete();      
            }        
//          Dispatch.call(doc, "SaveAs",  destFile,  17);   
         // 作为html格式保存到临时文件::参数 new Variant(8)其中8表示word转html;7表示word转txt;44表示Excel转html;17表示word转成pdf。。
            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {                
                toFileName, new Variant(17) }, new int[1]);    
            long end = System.currentTimeMillis();      
            System.out.println("转换完成..用时:" + (end - start) + "ms.");                
        } catch (Exception e) {  
            e.printStackTrace();  
            System.out.println("========Error:文档转换失败:" + e.getMessage());      
        }catch(Throwable t){
        	t.printStackTrace();
        } finally {  
        	// 关闭word
            Dispatch.call(doc,"Close",false);  
            System.out.println("关闭文档");  
            if (app != null)      
                app.invoke("Quit", new Variant[] {});      
            }  
          //如果没有这句话,winword.exe进程将不会关闭  
           ComThread.Release();  
           return 1;
           }  
    private static Document read(File xmlFile) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        return saxReader.read(xmlFile);
    }
//    public String getDocPageSize(File file){
//        String pages = null;
//        try{
//            Document doc = read(file);
//            List<Node> nodes = doc.selectNodes("//o:Pages");
//            if(nodes != null && nodes.size() > 0){
//                pages = nodes.get(0).getText();
//                System.out.println("/");
//                System.out.println("该word文档的页数为:"+Integer.parseInt(pages));
//                System.out.println("/");
//            }else{
//                System.out.println("*********");
//                System.out.println("页面转换错误");
//                System.out.println("*********");
//            }
//        }catch(Exception ex){
//            ex.printStackTrace(); 
//        }
//        return pages;
//    }
    public  int getDocPageSize(String filePath)  throws Exception {
        XWPFDocument docx = new XWPFDocument(POIXMLDocument.openPackage(filePath));
        int pages = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();//总页数
        int wordCount = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters();// 忽略空格的总字符数 另外还有getCharactersWithSpaces()方法获取带空格的总字数。        
        System.out.println ("pages=" + pages + " wordCount=" + wordCount);
        return pages;
    }
     
    public static void main(String[] args) throws Exception {  
    	Word2PdfUtil d = new Word2PdfUtil();  
    	//System.err.println(d.getDocPageSize("E:\\test.doc"));
        d.wordToPDF("E:\\test.doc", "E:\\test\\mm.pdf");  
    }  
  
}  

main方法直接运行,效果如下:

 

到此已经结束,关于word 模板 数据填充,这里不讲,新人可以自行百度,就是在最终生成好word后,在调用这个类即可。

出错总结:

1.没引入jar包,,这个错误我就不说了,,基本上所有人都可以避免.jacob.jar

2.出现这个错误是因为缺少了jacob-1.17-x64.dll这个东西,报错

3.需要安装Microsoft Save as PDF 或 XPS

com.jacob.com.ComFailException: Invoke of: SaveAs 

Source: Microsoft Word 

Description: 命令失败

出现这种错误网上也有很多解决办法:如下

Office版本使用2007,因为2007提供了一个加载项:Microsoft Save as PDF 或 XPS,可将文档另存为PDF格式。下载地址:http://www.microsoft.com/downloads/zh-cn/details.aspx?FamilyID=4D951911-3E7E-4AE6-B059-A2E79ED87041,安装即可使用。 

 

本文参考:https://blog.csdn.net/u013238430/article/details/52943075

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值