1. 程式人生 > >Word轉PDF(Java實現)

Word轉PDF(Java實現)

目前在做一個與文件有關的專案,網上看到的都是利用OpenOffice來轉化word為pdf的,其實侷限性很大,下載那麼大一個軟體,卻只是為了它的服務。所以決定找一下有沒有別的方法,終於遇到了docx4j這個神一樣的JAR包,完美解決了我的問題!不說了,直接上程式碼!

所需Jar包
avalon-framework-4.1.5
commons-io-2.4
docx4j-2.7.1
log4j-1.2.15
serializer-2.7.1
xmlgraphics-commons-1.3
batik-util-1.6-1
commons-logging-1.1.3
fop-0.93
xalan-2.7.1

程式碼:

package in.javadomain;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper; import org.docx4j.fonts.PhysicalFont; import org.docx4j.fonts.PhysicalFonts; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; public class Word2Pdf { public static void main(String[] args) { try { long start = System.currentTimeMillis
(); InputStream is = new FileInputStream( new File("D:\\javadomain.docx")); WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage .load(is); List sections = wordMLPackage.getDocumentModel().getSections(); for (int i = 0; i < sections.size(); i++) { System.out.println("sections Size" + sections.size()); wordMLPackage.getDocumentModel().getSections().get(i) .getPageDimensions().setHeaderExtent(3000); } Mapper fontMapper = new IdentityPlusMapper(); PhysicalFont font = PhysicalFonts.getPhysicalFonts().get( "Comic Sans MS"); fontMapper.getFontMappings().put("Algerian", font); wordMLPackage.setFontMapper(fontMapper); PdfSettings pdfSettings = new PdfSettings(); org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion( wordMLPackage); OutputStream out = new FileOutputStream(new File( "D:\\javadomain.pdf")); conversion.output(out, pdfSettings); System.err.println("Time taken to Generate pdf " + (System.currentTimeMillis() - start) + "ms"); } catch (Exception e) { e.printStackTrace(); } } }