Docx4j的Word转PDF及下载PDF

现将html页面转为word文档在转为PDF(预览)或PDF文件下载


Word转PDF

  1.   /** 
  2.      * docx文档转换为PDF 
  3.      * 
  4.      * @param docx docx文档 
  5.      * @param pdfPath PDF文档存储路径 
  6.      * @throws Exception 可能为Docx4JException, FileNotFoundException, IOException等 
  7.      */  
  8.     public static void convertDocxToPDF(String docxPath, String pdfPath) throws Exception {  
  9.         OutputStream os = null;  
  10.         try {  
  11.             WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(new File(docxPath));
  12.             Mapper fontMapper = new IdentityPlusMapper();  
  13.             fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai"));  
  14.             fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong"));  
  15.             fontMapper.put("隶书", PhysicalFonts.get("LiSu"));  
  16.             mlPackage.setFontMapper(fontMapper);  
  17.   
  18.             os = new java.io.FileOutputStream(pdfPath);  
  19.   
  20.             FOSettings foSettings = Docx4J.createFOSettings();  
  21.             foSettings.setWmlPackage(mlPackage);  
  22.             Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);  
  23.   
  24.         }catch(Exception ex){  
  25.             ex.printStackTrace();  
  26.         }finally {  
  27.             IOUtils.closeQuietly(os);  
  28.         }  
  29.     }  

  1.   public  void pdf(WordprocessingMLPackage wordMLPackage,OutputStream os) 
  2. throws Exception {
  3.     
  4. String regex = null;

    FieldUpdater updater = new FieldUpdater(wordMLPackage);
    updater.update(true);

    // Set up font mapper (optional)
    Mapper fontMapper = new IdentityPlusMapper();
    wordMLPackage.setFontMapper(fontMapper);


    PhysicalFont font 
    = PhysicalFonts.get("Arial Unicode MS"); 


    // FO exporter setup (required)
    // .. the FOSettings object
        FOSettings foSettings = Docx4J.createFOSettings();
     
    foSettings.setWmlPackage(wordMLPackage);

    // Document format: 
    // The default implementation of the FORenderer that uses Apache Fop will output
    // a PDF document if nothing is passed via 
    // foSettings.setApacheFopMime(apacheFopMime)
    // apacheFopMime can be any of the output formats defined in org.apache.fop.apps.MimeConstants eg org.apache.fop.apps.MimeConstants.MIME_FOP_IF or
    // FOSettings.INTERNAL_FO_MIME if you want the fo document as the result.
    //foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);

    // Specify whether PDF export uses XSLT or not to create the FO
    // (XSLT takes longer, but is more complete).

    // Don't care what type of exporter you use
    Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

    // Prefer the exporter, that uses a xsl transformation
    // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

    // Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor)
    // .. faster, but not yet at feature parity
    // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);
       
    // Clean up, so any ObfuscatedFontPart temp files can be deleted 
    // if (wordMLPackage.getMainDocumentPart().getFontTablePart()!=null) {
    // wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
    // }
    // This would also do it, via finalize() methods
    updater = null;
    foSettings = null;
    wordMLPackage = null;

        }   
 

下载PDF


  1.   public  void pdfFile(WordprocessingMLPackage wordMLPackage,OutputStream os) 
                throws Exception {
     
    // Font regex (optional)
    // Set regex if you want to restrict to some defined subset of fonts
    // Here we have to do this before calling createContent,
    // since that discovers fonts
    String regex = null;



    /* // Refresh the values of DOCPROPERTY fields 
    FieldUpdater updater = new FieldUpdater(wordMLPackage);
    updater.update(true);*/

    // Set up font mapper (optional)
    Mapper fontMapper = new IdentityPlusMapper();
    wordMLPackage.setFontMapper(fontMapper);

    // .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs
    // eg Glyph "ي" (0x64a, afii57450) not available in font "TimesNewRomanPS-ItalicMT".
    // eg Glyph "ج" (0x62c, afii57420) not available in font "TimesNewRomanPS-ItalicMT".
    // to a font which does
    PhysicalFont font 
    = PhysicalFonts.get("Arial Unicode MS"); 
    String directory = "D:\\upload\\pdf";
    String fileName = "OUT_ConvertInXHTMLURL.pdf";
    File f = new File(directory,fileName);
            if(f.exists()) {
              // 文件已经存在,输出文件的相关信息
                System.out.println(f.getAbsolutePath());
                System.out.println(f.getName());
                System.out.println(f.length());
            } else {
              //  先创建文件所在的目录
                f.getParentFile().mkdirs();
            }
    File file = new File(directory+"/"+fileName);


           OutputStream os34 = new java.io.FileOutputStream(file);


           Docx4J.toPDF(wordMLPackage, os34);


           os.flush();
           os.close();
           
         /*  updater = null;*/
    wordMLPackage = null;
        }   

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Docx4j是一个用于处理Word文档的Java库,它提供了丰富的功能,包括创建、修改和Word文档等。要将Word文档换为PDF,可以使用Docx4j提供的功能。 首先,你需要在项目中引入Docx4j库的依赖。你可以在Maven或Gradle中添加以下依赖: Maven: ```xml <dependency> <groupId>org.docx4j</groupId> <artifactId>docx4j</artifactId> <version>8.2.9</version> </dependency> ``` Gradle: ```groovy implementation 'org.docx4j:docx4j:8.2.9' ``` 接下来,你可以使用以下代码将Word文档换为PDF: ```java import org.docx4j.Docx4J; import org.docx4j.convert.out.FOSettings; public class WordToPdfConverter { public static void main(String[] args) throws Exception { // 加载Word文档 String inputFilePath = "path/to/input.docx"; org.docx4j.openpackaging.packages.WordprocessingMLPackage wordMLPackage = Docx4J.load(new java.io.File(inputFilePath)); // 创建FOSettings对象,并设置输出格式为PDF FOSettings foSettings = Docx4J.createFOSettings(); foSettings.setWmlPackage(wordMLPackage); foSettings.setApacheFopMime("application/pdf"); // 设置输出路径 String outputFilePath = "path/to/output.pdf"; java.io.OutputStream outputStream = new java.io.FileOutputStream(outputFilePath); // 执行Docx4J.toFO(foSettings, outputStream, Docx4J.FLAG_EXPORT_PREFER_XSL); // 关闭输出流 outputStream.close(); System.out.println("Word文档换为PDF成功!"); } } ``` 以上代码中,你需要将`inputFilePath`替换为要换的Word文档的路径,将`outputFilePath`替换为要保存的PDF文件的路径。执行代码后,将会生成对应的PDF文件。 希望以上信息对你有所帮助!如果你有任何其他问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值